')
+ })
+ }
+
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts b/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts
+new file mode 100644
+index 00000000..acdfa239
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts
+@@ -0,0 +1,132 @@
++import { nextTestSetup } from 'e2e-utils'
++import type { NextAdapter } from 'next'
++
++describe('adapter-partial-fallback-blocking', () => {
++ const { next } = nextTestSetup({
++ files: __dirname,
++ })
++
++ function expectAllowedParams(allowQuery: string[], expected: string[]) {
++ // Adapter query allowlists are sets. Their serialized order is not part
++ // of the build output contract.
++ expect(new Set(allowQuery)).toEqual(new Set(expected))
++ }
++
++ it('should exclude never-prerenderable params from allowQuery for blocking routes with empty shells', async () => {
++ const { outputs }: Parameters[0] =
++ await next.readJSON('build-complete.json')
++
++ const genericEmptyShellPrerender = outputs.prerenders.find(
++ (output) => output.pathname === '/empty-shell/[one]/[two]'
++ )
++ const genericEmptyShellDataPrerender = outputs.prerenders.find(
++ (output) => output.pathname === '/empty-shell/[one]/[two].rsc'
++ )
++ const genericEmptyShellSegmentPrerenders = outputs.prerenders.filter(
++ (output) =>
++ output.pathname.startsWith('/empty-shell/[one]/[two].segments/')
++ )
++ const generatedEmptyShellPrerender = outputs.prerenders.find(
++ (output) => output.pathname === '/empty-shell/a/[two]'
++ )
++
++ expect(genericEmptyShellPrerender).toBeDefined()
++ expect(genericEmptyShellDataPrerender).toBeDefined()
++ expect(genericEmptyShellSegmentPrerenders.length).toBeGreaterThan(0)
++ expect(generatedEmptyShellPrerender).toBeDefined()
++
++ expectAllowedParams(genericEmptyShellPrerender.config.allowQuery, [
++ 'nxtPone',
++ ])
++ expectAllowedParams(genericEmptyShellDataPrerender.config.allowQuery, [
++ 'nxtPone',
++ ])
++ for (const output of genericEmptyShellSegmentPrerenders) {
++ expectAllowedParams(output.config.allowQuery, ['nxtPone'])
++ }
++
++ expect(generatedEmptyShellPrerender.config.partialFallback).toBeUndefined()
++ expectAllowedParams(generatedEmptyShellPrerender.config.allowQuery, [])
++ })
++
++ it('should exclude never-prerenderable params from allowQuery for entries with a resolved root param', async () => {
++ const { outputs }: Parameters[0] =
++ await next.readJSON('build-complete.json')
++
++ const emptyShellPrerender = outputs.prerenders.find(
++ (output) =>
++ output.pathname === '/with-root-param/en/empty-shell/[category]/[id]'
++ )
++ const emptyShellDataPrerender = outputs.prerenders.find(
++ (output) =>
++ output.pathname ===
++ '/with-root-param/en/empty-shell/[category]/[id].rsc'
++ )
++ const nonEmptyShellPrerender = outputs.prerenders.find(
++ (output) =>
++ output.pathname ===
++ '/with-root-param/en/non-empty-shell/[category]/[id]'
++ )
++ const emptyShellLeafPrerender = outputs.prerenders.find(
++ (output) =>
++ output.pathname === '/with-root-param/en/empty-shell/shoes/[id]'
++ )
++
++ expect(emptyShellPrerender).toBeDefined()
++ expect(emptyShellDataPrerender).toBeDefined()
++ expect(nonEmptyShellPrerender).toBeDefined()
++ expect(emptyShellLeafPrerender).toBeDefined()
++
++ expectAllowedParams(emptyShellPrerender.config.allowQuery, [
++ 'nxtPcategory',
++ ])
++ expectAllowedParams(emptyShellDataPrerender.config.allowQuery, [
++ 'nxtPcategory',
++ ])
++
++ expectAllowedParams(nonEmptyShellPrerender.config.allowQuery, [
++ 'nxtPcategory',
++ ])
++ expect(nonEmptyShellPrerender.config.partialFallback).toBe(true)
++
++ expectAllowedParams(emptyShellLeafPrerender.config.allowQuery, [])
++ })
++
++ it('should exclude never-prerenderable params from allowQuery for entries with an unresolved root param', async () => {
++ const { outputs }: Parameters[0] =
++ await next.readJSON('build-complete.json')
++
++ const emptyShellBasePrerender = outputs.prerenders.find(
++ (output) =>
++ output.pathname ===
++ '/with-root-param/[lang]/empty-shell/[category]/[id]'
++ )
++ const emptyShellBaseDataPrerender = outputs.prerenders.find(
++ (output) =>
++ output.pathname ===
++ '/with-root-param/[lang]/empty-shell/[category]/[id].rsc'
++ )
++ const nonEmptyShellBasePrerender = outputs.prerenders.find(
++ (output) =>
++ output.pathname ===
++ '/with-root-param/[lang]/non-empty-shell/[category]/[id]'
++ )
++
++ expect(emptyShellBasePrerender).toBeDefined()
++ expect(emptyShellBaseDataPrerender).toBeDefined()
++ expect(nonEmptyShellBasePrerender).toBeDefined()
++
++ expectAllowedParams(emptyShellBasePrerender.config.allowQuery, [
++ 'nxtPlang',
++ 'nxtPcategory',
++ ])
++ expectAllowedParams(emptyShellBaseDataPrerender.config.allowQuery, [
++ 'nxtPlang',
++ 'nxtPcategory',
++ ])
++ expectAllowedParams(nonEmptyShellBasePrerender.config.allowQuery, [
++ 'nxtPlang',
++ 'nxtPcategory',
++ ])
++ })
++})
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx
+new file mode 100644
+index 00000000..65d28a99
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx
+@@ -0,0 +1,27 @@
++// This route intentionally produces EMPTY build-time shells: the params are
++// read outside of any Suspense boundary (and there is no loading.tsx), so the
++// postpone propagates to the root. `instant = false` opts the route out of
++// requiring an instant (non-empty) shell.
++//
++// The empty shells downgrade the generic route to a blocking route, but `two`
++// is still never provided by `generateStaticParams`: an on-demand render may
++// only complete `one`, so only `one` may participate in the cache key.
++export function generateStaticParams() {
++ return [{ one: 'a' }]
++}
++
++export const instant = false
++
++export default async function Page({
++ params,
++}: {
++ params: Promise<{ one: string; two: string }>
++}) {
++ const { one, two } = await params
++
++ return (
++
++ {one}:{two}
++
++ )
++}
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx
+new file mode 100644
+index 00000000..e7a42507
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx
+@@ -0,0 +1,11 @@
++import { ReactNode } from 'react'
++
++// Root layout for the (standard) branch: all params in this branch are
++// below the root layout, so none of them are root params.
++export default function Root({ children }: { children: ReactNode }) {
++ return (
++
++ {children}
++
++ )
++}
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx
+new file mode 100644
+index 00000000..d2b6d1b1
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx
+@@ -0,0 +1,38 @@
++// Empty-shell variant under a root param: the params are read outside of
++// any Suspense boundary, so the postpone propagates to the root and every
++// build-time shell is empty. `instant = false` opts the route out of
++// requiring an instant (non-empty) shell.
++//
++// `generateStaticParams` provides `lang` in every entry (required for root
++// params) and partially covers `category`; `id` is never provided, so `id`
++// must never be resolved into a cached shell and must never be part of a
++// cache key — including for requests whose `lang` value was not enumerated
++// (e.g. /fr/...), which match the base route entry where `lang` is an
++// unresolved root param.
++export async function generateStaticParams() {
++ return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
++}
++
++export const instant = false
++
++export default async function Page({
++ params,
++}: {
++ params: Promise<{ lang: string; category: string; id: string }>
++}) {
++ const { lang, category, id } = await params
++
++ // Per-render marker (prerenderable): must be re-rendered per request and
++ // never repeat across fetches — a repeated value proves a stored render
++ // is being replayed from the cache.
++ const renderedAt = performance.now()
++
++ return (
++
++
{lang}
++
{category}
++
{id}
++
{renderedAt}
++
++ )
++}
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx
+new file mode 100644
+index 00000000..bc155c67
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx
+@@ -0,0 +1,19 @@
++// The ROOT layout lives inside [lang], making `lang` a ROOT param: the
++// document itself (the html tag) varies by lang with no Suspense boundary.
++// Root params must be provided by every generateStaticParams result — the
++// build enforces this — so `lang` is always a prerenderable param.
++export default async function RootLayout({
++ children,
++ params,
++}: {
++ children: React.ReactNode
++ params: Promise<{ lang: string }>
++}) {
++ const { lang } = await params
++
++ return (
++
++ {children}
++
++ )
++}
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx
+new file mode 100644
+index 00000000..ba731670
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx
+@@ -0,0 +1,49 @@
++import { Suspense } from 'react'
++
++// Non-empty-shell variant under a root param: static page content plus
++// Suspense boundaries around the non-root param reads, so shells contain
++// static content and no empty-shell downgrade happens.
++//
++// `generateStaticParams` provides `lang` in every entry (required for root
++// params) and partially covers `category`; `id` is never provided and must
++// never resolve into a cached shell nor participate in a cache key.
++export async function generateStaticParams() {
++ return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
++}
++
++async function Id({ params }: { params: Promise<{ id: string }> }) {
++ const { id } = await params
++
++ // Per-render marker (prerenderable), read after `await params` so it
++ // belongs to the deferred region: it must be re-rendered (resumed) per
++ // request and never repeat across fetches.
++ const renderedAt = performance.now()
++
++ return (
++ <>
++
++ }
++ >
++
++
++
++ )
++}
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx
+new file mode 100644
+index 00000000..a0da238a
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx
+@@ -0,0 +1,40 @@
++import { Suspense, type ReactNode } from 'react'
++
++// `category` is read in its own Suspense boundary: shells where it is
++// concrete render it statically, and generic shells show
++// `#category-fallback`. This makes the served shell's specialization
++// observable from the static part of the response. (`lang` is a root param
++// and is part of the document itself, rendered by the root layout.)
++async function LayoutImpl({
++ children,
++ params,
++}: {
++ children: ReactNode
++ params: Promise<{ category: string }>
++}) {
++ const { category } = await params
++
++ return (
++
++
{category}
++ {children}
++
++ )
++}
++
++export default function Layout(props: {
++ children: ReactNode
++ params: Promise<{ category: string }>
++}) {
++ return (
++
++ loading category...
++
++ }
++ >
++
++
++ )
++}
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs b/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs
+new file mode 100644
+index 00000000..548129ec
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs
+@@ -0,0 +1,9 @@
++import fs from 'fs/promises'
++
++/** @type {import('next').NextAdapter } */
++export default {
++ name: 'adapter-partial-fallback-blocking',
++ async onBuildComplete(ctx) {
++ await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
++ },
++}
+diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js b/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js
+new file mode 100644
+index 00000000..39584cc1
+--- /dev/null
++++ b/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js
+@@ -0,0 +1,10 @@
++/**
++ * @type {import('next').NextConfig}
++ */
++const nextConfig = {
++ cacheComponents: true,
++ partialPrefetching: true,
++ adapterPath: require.resolve('./my-adapter.mjs'),
++}
++
++module.exports = nextConfig
diff --git a/nextjs-cache-components-dynamic-param-prerenders/tests/test.sh b/nextjs-cache-components-dynamic-param-prerenders/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c39b4bb77a61a42b675d93dd8c52c58546675868
--- /dev/null
+++ b/nextjs-cache-components-dynamic-param-prerenders/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/partial-fallback-root-blocking/next.config.js' --exclude='test/e2e/app-dir/partial-fallback-root-blocking/next.config.js/*' --exclude='test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' --exclude='test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/next.config.js' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/next.config.js/*' /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/partial-fallback-root-blocking/next.config.js' 'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' 'test/production/app-dir/adapter-partial-fallback-blocking/next.config.js' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/e2e/app-dir/partial-fallback-root-blocking/next.config.js' 'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' 'test/production/app-dir/adapter-partial-fallback-blocking/next.config.js' >/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/partial-fallback-root-blocking/next.config.js' '/app/test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' '/app/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' '/app/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js'; 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-start-webpack '"'"'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts'"'"' '"'"'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm build && pnpm test-start-webpack '"'"'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts'"'"' '"'"'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.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-start-webpack '"'"'test/e2e/app-dir/partial-fallback-shell-upgrade/partial-fallback-shell-upgrade.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 <(
+ underlyingParams: TPArams
+diff --git a/packages/next/src/client/components/instant-validation/boundary.tsx b/packages/next/src/client/components/instant-validation/boundary.tsx
+index cf39318c3a..8ed8ccd7fe 100644
+--- a/packages/next/src/client/components/instant-validation/boundary.tsx
++++ b/packages/next/src/client/components/instant-validation/boundary.tsx
+@@ -1,29 +1,9 @@
+ 'use client'
+-
+-// This facade ensures that the boundary code is DCE'd in browser bundles.
+-//
+-// It also exists to satisfy `browser-chunks.test.ts`, which looks for
+-// references to code in `packages/next/src/server` in browser bundles and errors if it finds any.
+-// A "use client" module seems to always have always have an entry in the browser bundle,
+-// so this module cannot be colocated with the rest of the instant validation code,
+-// because it ends up looking like it's importing server code in the browser
+-// even though all the server code inside is actually DCE'd.
+-
+-const {
+- InstantValidationBoundaryContext,
+- PlaceValidationBoundaryBelowThisLevel,
+- RenderValidationBoundaryAtThisLevel,
+- SlotMarker,
+-} =
+- typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS
+- ? // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
+- // ast-grep-ignore: no-typeof-window-require-tsx
+- (require('../../../server/app-render/instant-validation/boundary-impl') as typeof import('../../../server/app-render/instant-validation/boundary-impl'))
+- : ({} as typeof import('../../../server/app-render/instant-validation/boundary-impl'))
+-
++// We can't fork a `use client` boundary based on node-client vs browser-client.
++// We need to fork one level deeper.
+ export {
+ InstantValidationBoundaryContext,
+ PlaceValidationBoundaryBelowThisLevel,
+ RenderValidationBoundaryAtThisLevel,
+ SlotMarker,
+-}
++} from './impl'
+diff --git a/packages/next/src/client/components/instant-validation/impl.browser.tsx b/packages/next/src/client/components/instant-validation/impl.browser.tsx
+new file mode 100644
+index 0000000000..fad4049807
+--- /dev/null
++++ b/packages/next/src/client/components/instant-validation/impl.browser.tsx
+@@ -0,0 +1,4 @@
++export const InstantValidationBoundaryContext = null
++export const PlaceValidationBoundaryBelowThisLevel = null
++export const RenderValidationBoundaryAtThisLevel = null
++export const SlotMarker = null
+diff --git a/packages/next/src/client/components/instant-validation/impl.tsx b/packages/next/src/client/components/instant-validation/impl.tsx
+new file mode 100644
+index 0000000000..62e291f209
+--- /dev/null
++++ b/packages/next/src/client/components/instant-validation/impl.tsx
+@@ -0,0 +1,6 @@
++export {
++ InstantValidationBoundaryContext,
++ PlaceValidationBoundaryBelowThisLevel,
++ RenderValidationBoundaryAtThisLevel,
++ SlotMarker,
++} from '../../../server/app-render/instant-validation/boundary-impl'
+diff --git a/packages/next/src/client/components/layout-router.tsx b/packages/next/src/client/components/layout-router.tsx
+index efdd8d9187..52019013c5 100644
+--- a/packages/next/src/client/components/layout-router.tsx
++++ b/packages/next/src/client/components/layout-router.tsx
+@@ -33,6 +33,10 @@ import { ErrorBoundary } from './error-boundary'
+ import { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll'
+ import { RedirectBoundary } from './redirect-boundary'
+ import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'
++import {
++ InstantValidationBoundaryContext,
++ RenderValidationBoundaryAtThisLevel,
++} from './instant-validation/boundary'
+ import { createRouterCacheKey } from './router-reducer/create-router-cache-key'
+ import {
+ useRouterBFCache,
+@@ -670,10 +674,6 @@ export default function OuterLayoutRouter({
+
+ let maybeValidationBoundaryId: string | null = null
+ if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {
+- const { InstantValidationBoundaryContext } =
+- // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
+- // ast-grep-ignore: no-typeof-window-require-tsx
+- require('./instant-validation/boundary') as typeof import('./instant-validation/boundary')
+ maybeValidationBoundaryId = use(InstantValidationBoundaryContext)
+ }
+
+@@ -812,10 +812,6 @@ export default function OuterLayoutRouter({
+ process.env.__NEXT_CACHE_COMPONENTS &&
+ typeof maybeValidationBoundaryId === 'string'
+ ) {
+- const { RenderValidationBoundaryAtThisLevel } =
+- // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
+- // ast-grep-ignore: no-typeof-window-require-tsx
+- require('./instant-validation/boundary') as typeof import('./instant-validation/boundary')
+ templateValue = (
+
+ {templateValue}
+diff --git a/packages/next/src/client/components/navigation.ts b/packages/next/src/client/components/navigation.ts
+index 0c7dc84d32..2e1df203d8 100644
+--- a/packages/next/src/client/components/navigation.ts
++++ b/packages/next/src/client/components/navigation.ts
+@@ -27,12 +27,9 @@ const {
+ instrumentParamsForClientValidation,
+ instrumentSearchParamsForClientValidation,
+ expectCompleteParamsInClientValidation,
+-} =
+- typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS
+- ? // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
+- // ast-grep-ignore: no-typeof-window-require
+- (require('../../server/app-render/instant-validation/instant-samples-client') as typeof import('../../server/app-render/instant-validation/instant-samples-client'))
+- : {}
++} = process.env.__NEXT_CACHE_COMPONENTS
++ ? (require('./instant-samples') as typeof import('./instant-samples'))
++ : {}
+
+ /**
+ * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
diff --git a/nextjs-client-node-browser-variants/solution/solve.sh b/nextjs-client-node-browser-variants/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-client-node-browser-variants/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-client-node-browser-variants/tests/Dockerfile b/nextjs-client-node-browser-variants/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..dce2bcd9abd9c1a48608c7a575ad4394db065a0c
--- /dev/null
+++ b/nextjs-client-node-browser-variants/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 swc-build-native && 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-client-node-browser-variants/tests/test.patch b/nextjs-client-node-browser-variants/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..ca0f2974a6cc03dd3c233efbac7012dd79263093
--- /dev/null
+++ b/nextjs-client-node-browser-variants/tests/test.patch
@@ -0,0 +1,109 @@
+diff --git a/test/production/app-dir/browser-chunks/browser-chunks.test.ts b/test/production/app-dir/browser-chunks/browser-chunks.test.ts
+index 041a813ad0..ecf810fcb3 100644
+--- a/test/production/app-dir/browser-chunks/browser-chunks.test.ts
++++ b/test/production/app-dir/browser-chunks/browser-chunks.test.ts
+@@ -22,6 +22,14 @@ function normalizeSource(source: string): string {
+ describe('browser-chunks', () => {
+ const { next } = nextTestSetup({
+ files: __dirname,
++ dependencies: {
++ react: '19.2.7',
++ 'react-dom': '19.2.7',
++ '@types/react': '19.2.2',
++ '@types/react-dom': '19.2.1',
++ typescript: '6.0.2',
++ '@types/node': '20.17.6',
++ },
+ })
+
+ let sources: string[] = []
+@@ -45,13 +53,11 @@ describe('browser-chunks', () => {
+ )
+ })
+
+- // These snapshots document which matching modules currently reach browser
+- // chunks. Some of these we don't intend to act on yet, so we snapshot the
+- // normalized paths (rather than hard-fail) to surface regressions on review.
+ it('must not bundle any server modules into browser chunks', () => {
+ const serverSources = Array.from(
+ new Set(
+ sources
++ // normalizing in case we regress and want to keep track of the regression
+ .map(normalizeSource)
+ .filter(
+ (source) =>
+@@ -63,46 +69,7 @@ describe('browser-chunks', () => {
+ )
+ ).sort()
+
+- // This set varies along two axes, so snapshot each combination separately
+- // rather than forcing them to agree:
+- // - bundler: webpack's browser chunks contain none of these; Turbopack
+- // still pulls in a set we haven't acted on yet.
+- // - cache components: enabling it pulls additional server modules
+- // (instant-validation, async storage, dynamic rendering) into the
+- // client render path. CI runs this suite both with and without it
+- // (see test/cache-components-tests-manifest.json).
+- const cacheComponents = process.env.__NEXT_CACHE_COMPONENTS === 'true'
+- if (process.env.IS_TURBOPACK_TEST) {
+- if (cacheComponents) {
+- expect(serverSources).toMatchInlineSnapshot(`
+- [
+- "src/server/app-render/async-local-storage.ts",
+- "src/server/app-render/instant-validation/boundary-constants.ts",
+- "src/server/app-render/instant-validation/boundary-impl.tsx",
+- "src/server/app-render/instant-validation/instant-samples-client.ts",
+- "src/server/app-render/instant-validation/instant-samples.ts",
+- "src/server/app-render/instant-validation/instant-validation-error.ts",
+- "src/server/app-render/staged-rendering.ts",
+- "src/server/app-render/work-async-storage-instance.ts",
+- "src/server/app-render/work-async-storage.external.ts",
+- "src/server/app-render/work-unit-async-storage-instance.ts",
+- "src/server/app-render/work-unit-async-storage.external.ts",
+- "src/server/web/spec-extension/adapters/headers.ts",
+- "src/server/web/spec-extension/adapters/reflect.ts",
+- "src/server/web/spec-extension/adapters/request-cookies.ts",
+- "src/server/web/spec-extension/cookies.ts",
+- ]
+- `)
+- } else {
+- expect(serverSources).toMatchInlineSnapshot(`[]`)
+- }
+- } else {
+- if (cacheComponents) {
+- expect(serverSources).toMatchInlineSnapshot(`[]`)
+- } else {
+- expect(serverSources).toMatchInlineSnapshot(`[]`)
+- }
+- }
++ expect(serverSources).toEqual([])
+ })
+
+ it('must not bundle any dev overlay into browser chunks', () => {
+diff --git a/test/production/app-dir/browser-chunks/browser-runtime.test.ts b/test/production/app-dir/browser-chunks/browser-runtime.test.ts
+new file mode 100644
+index 0000000000..1891353f1f
+--- /dev/null
++++ b/test/production/app-dir/browser-chunks/browser-runtime.test.ts
+@@ -0,0 +1,21 @@
++import { nextTestSetup } from 'e2e-utils'
++
++describe('browser runtime', () => {
++ const { next } = nextTestSetup({
++ files: __dirname,
++ dependencies: {
++ react: '19.2.7',
++ 'react-dom': '19.2.7',
++ '@types/react': '19.2.2',
++ '@types/react-dom': '19.2.1',
++ typescript: '6.0.2',
++ '@types/node': '20.17.6',
++ },
++ })
++
++ it('serves the client application in production', async () => {
++ const response = await next.fetch('/')
++
++ expect(response.status).toBe(200)
++ })
++})
diff --git a/nextjs-client-node-browser-variants/tests/test.sh b/nextjs-client-node-browser-variants/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d4424ff88f1dcf2093dac0cac1c929c35a038a74
--- /dev/null
+++ b/nextjs-client-node-browser-variants/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/browser-chunks/browser-chunks.test.ts' --exclude='test/production/app-dir/browser-chunks/browser-chunks.test.ts/*' --exclude='test/production/app-dir/browser-chunks/browser-runtime.test.ts' --exclude='test/production/app-dir/browser-chunks/browser-runtime.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/browser-chunks/browser-chunks.test.ts' 'test/production/app-dir/browser-chunks/browser-runtime.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/production/app-dir/browser-chunks/browser-chunks.test.ts' 'test/production/app-dir/browser-chunks/browser-runtime.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/browser-chunks/browser-chunks.test.ts' '/app/test/production/app-dir/browser-chunks/browser-runtime.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 swc-build-native && pnpm build && pnpm test-start-experimental-turbo '"'"'test/production/app-dir/browser-chunks/browser-chunks.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm swc-build-native && pnpm build && pnpm test-start-experimental-turbo '"'"'test/production/app-dir/browser-chunks/browser-chunks.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 swc-build-native && pnpm build && pnpm test-start-experimental-turbo '"'"'test/production/app-dir/browser-chunks/browser-runtime.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 < {
+ try {
+ await runUpgrade(revision, options)
+diff --git a/packages/next-codemod/bin/upgrade.ts b/packages/next-codemod/bin/upgrade.ts
+index b7de97ce5cb1640afb7dd2fb93028d6055330801..2cb91c140a49348bb8bbd0335a14021c0441a7cd 100644
+--- a/packages/next-codemod/bin/upgrade.ts
++++ b/packages/next-codemod/bin/upgrade.ts
+@@ -112,9 +112,15 @@ function resolveSemanticRevision(
+
+ export async function runUpgrade(
+ revision: string | undefined,
+- options: { verbose: boolean }
++ options: { verbose: boolean; yes?: boolean }
+ ): Promise {
+ const { verbose } = options
++ const nonInteractive = options.yes === true || !process.stdin.isTTY
++ if (nonInteractive) {
++ console.log(
++ ` Running in non-interactive mode. Every prompt will accept its default.`
++ )
++ }
+ const appPackageJsonPath = path.resolve(cwd, 'package.json')
+ let appPackageJson = JSON.parse(fs.readFileSync(appPackageJsonPath, 'utf8'))
+
+@@ -221,22 +227,27 @@ export async function runUpgrade(
+ // We'll recommend to upgrade in the prompt but users can decide to try 18.
+ !isPureAppRouter
+ ) {
+- const shouldStayOnReact18Res = await prompts(
+- {
+- type: 'confirm',
+- name: 'shouldStayOnReact18',
+- message:
+- `Do you prefer to stay on React 18?` +
+- (isMixedApp
+- ? " Since you're using both pages/ and app/, we recommend upgrading React to use a consistent version throughout your app."
+- : ''),
+- initial: false,
+- active: 'Yes',
+- inactive: 'No',
+- },
+- { onCancel }
+- )
+- shouldStayOnReact18 = shouldStayOnReact18Res.shouldStayOnReact18
++ if (nonInteractive) {
++ // Default: upgrade React past 18.
++ shouldStayOnReact18 = false
++ } else {
++ const shouldStayOnReact18Res = await prompts(
++ {
++ type: 'confirm',
++ name: 'shouldStayOnReact18',
++ message:
++ `Do you prefer to stay on React 18?` +
++ (isMixedApp
++ ? " Since you're using both pages/ and app/, we recommend upgrading React to use a consistent version throughout your app."
++ : ''),
++ initial: false,
++ active: 'Yes',
++ inactive: 'No',
++ },
++ { onCancel }
++ )
++ shouldStayOnReact18 = shouldStayOnReact18Res.shouldStayOnReact18
++ }
+ }
+
+ // We're resolving a specific version here to avoid including "ugly" version queries
+@@ -254,12 +265,13 @@ export async function runUpgrade(
+ compareVersions(targetNextVersion, '15.0.0-canary') >= 0 &&
+ compareVersions(targetNextVersion, '16.0.0-canary') < 0
+ ) {
+- await suggestTurbopack(appPackageJson, targetNextVersion)
++ await suggestTurbopack(appPackageJson, targetNextVersion, nonInteractive)
+ }
+
+ const codemods = await suggestCodemods(
+ installedNextVersion,
+- targetNextVersion
++ targetNextVersion,
++ nonInteractive
+ )
+ const packageManager: PackageManager = getPkgManager(cwd)
+
+@@ -272,8 +284,9 @@ export async function runUpgrade(
+ compareVersions(targetReactVersion, '19.0.0-0') >= 0 &&
+ compareVersions(installedReactVersion, '19.0.0-0') < 0
+ ) {
+- shouldRunReactCodemods = await suggestReactCodemods()
+- shouldRunReactTypesCodemods = await suggestReactTypesCodemods()
++ shouldRunReactCodemods = await suggestReactCodemods(nonInteractive)
++ shouldRunReactTypesCodemods =
++ await suggestReactTypesCodemods(nonInteractive)
+
+ execCommand = getNpxCommand(packageManager)
+ }
+@@ -400,10 +413,12 @@ export async function runUpgrade(
+ // understanding of the codemods, we run all of the applicable codemods.
+ if (shouldRunReactCodemods) {
+ // https://react.dev/blog/2024/04/25/react-19-upgrade-guide#run-all-react-19-codemods
++ // `--no-interactive` skips the interactive prompt that asks for confirmation
++ // https://github.com/codemod-com/codemod/blob/c0cf00d13161a0ec0965b6cc6bc5d54076839cc8/apps/cli/src/flags.ts#L160
++ // `--allow-dirty` is required because the upgrade above modified package.json
++ // and the lockfile; the recipe refuses to run on a dirty tree otherwise.
+ execSync(
+- // `--no-interactive` skips the interactive prompt that asks for confirmation
+- // https://github.com/codemod-com/codemod/blob/c0cf00d13161a0ec0965b6cc6bc5d54076839cc8/apps/cli/src/flags.ts#L160
+- `${execCommand} codemod@latest react/19/migration-recipe --no-interactive`,
++ `${execCommand} codemod@latest react/19/migration-recipe --no-interactive --allow-dirty`,
+ { stdio: 'inherit' }
+ )
+ }
+@@ -486,7 +501,8 @@ function isUsingAppDir(projectPath: string): boolean {
+ */
+ async function suggestTurbopack(
+ packageJson: any,
+- targetNextVersion: string
++ targetNextVersion: string,
++ nonInteractive: boolean
+ ): Promise {
+ const devScript: string | undefined = packageJson.scripts?.['dev']
+ // Turbopack flag was changed from `--turbo` to `--turbopack` in v15.0.1-canary.3
+@@ -518,17 +534,21 @@ async function suggestTurbopack(
+ return
+ }
+
+- const responseTurbopack = await prompts(
+- {
+- type: 'confirm',
+- name: 'enable',
+- message: `Enable Turbopack for ${pc.bold('next dev')}?`,
+- initial: true,
+- },
+- { onCancel }
+- )
++ let enable = true
++ if (!nonInteractive) {
++ const responseTurbopack = await prompts(
++ {
++ type: 'confirm',
++ name: 'enable',
++ message: `Enable Turbopack for ${pc.bold('next dev')}?`,
++ initial: true,
++ },
++ { onCancel }
++ )
++ enable = responseTurbopack.enable
++ }
+
+- if (!responseTurbopack.enable) {
++ if (!enable) {
+ return
+ }
+
+@@ -543,6 +563,12 @@ async function suggestTurbopack(
+ `${pc.yellow('⚠')} Could not find "${pc.bold('next dev')}" in your dev script.`
+ )
+
++ if (nonInteractive) {
++ // Without a TTY we can't ask the user for a replacement script.
++ // Keep the existing dev script untouched.
++ return
++ }
++
+ const responseCustomDevScript = await prompts(
+ {
+ type: 'text',
+@@ -559,7 +585,8 @@ async function suggestTurbopack(
+
+ async function suggestCodemods(
+ initialNextVersion: string,
+- targetNextVersion: string
++ targetNextVersion: string,
++ nonInteractive: boolean
+ ): Promise {
+ // example:
+ // codemod version: 15.0.0-canary.45
+@@ -594,6 +621,16 @@ async function suggestCodemods(
+ return []
+ }
+
++ if (nonInteractive) {
++ // Default: apply every recommended codemod, matching `selected: true` below.
++ const all = relevantCodemods.map(({ value }) => value)
++ console.log(
++ ` Applying all ${pc.blue('codemods')} recommended for your upgrade:\n` +
++ all.map((value) => ` - ${value}`).join('\n')
++ )
++ return all
++ }
++
+ const { codemods } = await prompts(
+ {
+ type: 'multiselect',
+@@ -614,7 +651,10 @@ async function suggestCodemods(
+ return codemods
+ }
+
+-async function suggestReactCodemods(): Promise {
++async function suggestReactCodemods(nonInteractive: boolean): Promise {
++ if (nonInteractive) {
++ return true
++ }
+ const { runReactCodemod } = await prompts(
+ {
+ type: 'confirm',
+@@ -628,7 +668,12 @@ async function suggestReactCodemods(): Promise {
+ return runReactCodemod
+ }
+
+-async function suggestReactTypesCodemods(): Promise {
++async function suggestReactTypesCodemods(
++ nonInteractive: boolean
++): Promise {
++ if (nonInteractive) {
++ return true
++ }
+ const { runReactTypesCodemod } = await prompts(
+ {
+ type: 'confirm',
diff --git a/nextjs-codemod-noninteractive-upgrade/solution/solve.sh b/nextjs-codemod-noninteractive-upgrade/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-codemod-noninteractive-upgrade/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-codemod-noninteractive-upgrade/tests/Dockerfile b/nextjs-codemod-noninteractive-upgrade/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..638991e5b264ba6e499c1f06c27369b024dc1d10
--- /dev/null
+++ b/nextjs-codemod-noninteractive-upgrade/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 pnpm@10.33.0 install --frozen-lockfile && corepack pnpm@10.33.0 turbo build --filter=next --filter=@next/codemod' \
+ && 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-codemod-noninteractive-upgrade/tests/test.patch b/nextjs-codemod-noninteractive-upgrade/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..4caf85de3eb16b5f55e6ea76b59ca164fe83ef7c
--- /dev/null
+++ b/nextjs-codemod-noninteractive-upgrade/tests/test.patch
@@ -0,0 +1,283 @@
+diff --git a/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js b/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js
+new file mode 100644
+index 00000000..54ca42d2
+--- /dev/null
++++ b/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js
+@@ -0,0 +1,277 @@
++/* global jest */
++
++jest.autoMockOff()
++
++const fs = require('fs')
++const os = require('os')
++const path = require('path')
++const { spawnSync } = require('child_process')
++
++const codemodRoot = path.resolve(__dirname, '../..')
++const tsx = path.resolve(codemodRoot, '../../node_modules/.bin/tsx')
++const projects = []
++
++// The verifier setup builds the base revision before applying a candidate patch.
++// Run a source snapshot of the current package so tests see candidate changes
++// instead of stale generated JavaScript while still reusing the prebuilt
++// transforms. Copy the whole package rather than assuming that an implementation
++// must live in bin/ and lib/: a CLI may legitimately import a new source folder,
++// a JavaScript-only helper, or package metadata added by the candidate.
++function createSourceCli() {
++ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'next-codemod-cli-'))
++ projects.push(root)
++
++ const sourceFile = (file) => {
++ const relative = path.relative(codemodRoot, file)
++ const topLevel = relative.split(path.sep)[0]
++ if (topLevel === 'node_modules' || topLevel === 'transforms') return false
++
++ // Ignore a generated artifact only when its source sibling exists. This
++ // keeps candidate-authored JavaScript modules while ensuring tsx loads a
++ // changed TypeScript source file instead of JavaScript built from HEAD.
++ const sourceBase = file.replace(/(?:\.js(?:\.map)?|\.d\.ts(?:\.map)?)$/, '')
++ if (sourceBase !== file) {
++ if (fs.existsSync(`${sourceBase}.ts`)) return false
++ if (fs.existsSync(`${sourceBase}.tsx`)) return false
++ }
++ return true
++ }
++ fs.cpSync(codemodRoot, root, { recursive: true, filter: sourceFile })
++
++ for (const entry of ['node_modules', 'transforms']) {
++ fs.symlinkSync(
++ path.join(codemodRoot, entry),
++ path.join(root, entry),
++ 'dir'
++ )
++ }
++
++ return path.join(root, 'bin', 'next-codemod.ts')
++}
++
++function writeJson(file, value) {
++ fs.mkdirSync(path.dirname(file), { recursive: true })
++ fs.writeFileSync(file, JSON.stringify(value, null, 2))
++}
++
++function createProject({
++ installedNext,
++ installedReact,
++ targetNext,
++ targetReact,
++ devScript,
++ pages = false,
++}) {
++ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'next-codemod-upgrade-'))
++ projects.push(dir)
++
++ writeJson(path.join(dir, 'package.json'), {
++ private: true,
++ scripts: { dev: devScript },
++ dependencies: {
++ next: installedNext,
++ react: installedReact,
++ 'react-dom': installedReact,
++ },
++ })
++ writeJson(path.join(dir, 'package-lock.json'), {})
++ for (const dependency of ['next', 'react', 'react-dom']) {
++ writeJson(path.join(dir, 'node_modules', dependency, 'package.json'), {
++ name: dependency,
++ version: dependency === 'next' ? installedNext : installedReact,
++ })
++ }
++ if (pages) {
++ fs.mkdirSync(path.join(dir, 'pages'), { recursive: true })
++ fs.writeFileSync(
++ path.join(dir, 'pages', 'index.js'),
++ 'export default () => null\n'
++ )
++ }
++
++ const fakeBin = path.join(dir, 'fake-bin')
++ fs.mkdirSync(fakeBin)
++ const npm = `#!/usr/bin/env node
++const fs = require('fs')
++const args = process.argv.slice(2)
++const query = args.find((arg) => arg.includes('@')) || ''
++if (args.includes('view')) {
++ if (query.startsWith('next@') && args.includes('version')) {
++ console.log(JSON.stringify(process.env.TEST_TARGET_NEXT))
++ } else if (query.startsWith('next@')) {
++ console.log(JSON.stringify({ version: process.env.TEST_TARGET_NEXT, peerDependencies: { react: process.env.TEST_REACT_RANGE } }))
++ } else {
++ console.log(JSON.stringify(process.env.TEST_TARGET_REACT))
++ }
++} else {
++ fs.appendFileSync(process.env.TEST_COMMAND_LOG, 'npm ' + args.join(' ') + '\\n')
++}
++`
++ const npx = `#!/usr/bin/env node
++require('fs').appendFileSync(process.env.TEST_COMMAND_LOG, 'npx ' + process.argv.slice(2).join(' ') + '\\n')
++`
++ for (const [name, contents] of [
++ ['npm', npm],
++ ['npx', npx],
++ ]) {
++ const file = path.join(fakeBin, name)
++ fs.writeFileSync(file, contents)
++ fs.chmodSync(file, 0o755)
++ }
++
++ return {
++ dir,
++ cli: createSourceCli(),
++ commandLog: path.join(dir, 'commands.log'),
++ env: {
++ ...process.env,
++ PATH: `${fakeBin}${path.delimiter}${process.env.PATH}`,
++ TEST_TARGET_NEXT: targetNext,
++ TEST_TARGET_REACT: targetReact,
++ TEST_REACT_RANGE: `^${targetReact}`,
++ TEST_COMMAND_LOG: path.join(dir, 'commands.log'),
++ FORCE_COLOR: '0',
++ },
++ }
++}
++
++function runUpgrade(project, args, { tty = false, input } = {}) {
++ if (!tty) {
++ return spawnSync(tsx, [project.cli, 'upgrade', ...args], {
++ cwd: project.dir,
++ env: project.env,
++ encoding: 'utf8',
++ timeout: 15_000,
++ })
++ }
++
++ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`
++ const command = [tsx, project.cli, 'upgrade', ...args].map(quote).join(' ')
++ return spawnSync('script', ['-q', '-e', '-c', command, '/dev/null'], {
++ cwd: project.dir,
++ env: project.env,
++ encoding: 'utf8',
++ timeout: 15_000,
++ input,
++ })
++}
++
++function outputOf(result) {
++ return `${result.stdout || ''}\n${result.stderr || ''}`
++}
++
++afterEach(() => {
++ while (projects.length) {
++ fs.rmSync(projects.pop(), { recursive: true, force: true })
++ }
++})
++
++test('upgrade help exposes both non-interactive option spellings', () => {
++ const cli = createSourceCli()
++ const result = spawnSync(tsx, [cli, 'upgrade', '--help'], {
++ encoding: 'utf8',
++ timeout: 15_000,
++ })
++
++ expect(result.status).toBe(0)
++ expect(outputOf(result)).toMatch(/-y, --yes\b/)
++})
++
++test('TTY use without --yes remains interactive', () => {
++ const project = createProject({
++ installedNext: '15.0.0-canary.90',
++ installedReact: '19.0.0',
++ targetNext: '15.0.0-canary.100',
++ targetReact: '19.0.0',
++ devScript: 'next dev',
++ })
++
++ // Reject the default Turbopack suggestion. A command that incorrectly forces
++ // non-interactive defaults would update this script instead.
++ const result = runUpgrade(project, ['15.0.0-canary.100'], {
++ tty: true,
++ input: 'n\n',
++ })
++ expect(outputOf(result)).toContain('Enable Turbopack')
++ expect(result.status).toBe(0)
++
++ const manifest = JSON.parse(
++ fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
++ )
++ expect(manifest.scripts.dev).toBe('next dev')
++})
++
++test('--yes accepts prompt defaults even when the command has a TTY', () => {
++ const project = createProject({
++ installedNext: '15.0.0-canary.90',
++ installedReact: '18.2.0',
++ targetNext: '15.0.0-canary.100',
++ targetReact: '19.0.0',
++ devScript: 'next dev',
++ pages: true,
++ })
++
++ const result = runUpgrade(project, ['15.0.0-canary.100', '--yes'], {
++ tty: true,
++ })
++ expect(result.status).toBe(0)
++
++ const manifest = JSON.parse(
++ fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
++ )
++ expect(manifest.scripts.dev).toContain('next dev --turbo')
++ expect(manifest.dependencies.next).toBe('15.0.0-canary.100')
++ expect(manifest.dependencies.react).toBe('19.0.0')
++ expect(manifest.dependencies['react-dom']).toBe('19.0.0')
++
++ const commands = fs.readFileSync(project.commandLog, 'utf8')
++ expect(commands).toContain('react/19/migration-recipe')
++ expect(commands).toContain('types-react-codemod@latest')
++})
++
++test('piped stdin automatically leaves an unrecognized custom dev script unchanged', () => {
++ const devScript = 'node scripts/start-development.js --inspect'
++ const project = createProject({
++ installedNext: '15.0.0-canary.90',
++ installedReact: '19.0.0',
++ targetNext: '15.0.0-canary.100',
++ targetReact: '19.0.0',
++ devScript,
++ })
++
++ const result = runUpgrade(project, ['15.0.0-canary.100'])
++ expect(result.status).toBe(0)
++ const manifest = JSON.parse(
++ fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
++ )
++ expect(manifest.scripts.dev).toBe(devScript)
++ expect(manifest.dependencies.next).toBe('15.0.0-canary.100')
++})
++
++test('piped stdin applies every recommended Next.js codemod', () => {
++ const project = createProject({
++ installedNext: '13.5.0',
++ installedReact: '18.2.0',
++ targetNext: '14.2.0',
++ targetReact: '18.3.1',
++ devScript: 'next dev',
++ })
++ const page = path.join(project.dir, 'app', 'page.tsx')
++ fs.mkdirSync(path.dirname(page), { recursive: true })
++ fs.writeFileSync(
++ page,
++ `import { ImageResponse } from 'next/server'\n\nexport const metadata = {\n title: 'Keep this title',\n viewport: { width: 'device-width' },\n themeColor: 'black',\n}\n\nexport default function Page() { return null }\n`
++ )
++
++ const result = runUpgrade(project, ['14.2.0'])
++ expect(result.status).toBe(0)
++
++ const output = outputOf(result)
++ expect(output).toContain('metadata-to-viewport-export')
++ expect(output).toContain('next-og-import')
++
++ const transformed = fs.readFileSync(page, 'utf8')
++ expect(transformed).toMatch(/from ['"]next\/og['"]/)
++ expect(transformed).toContain('export const viewport')
++ expect(transformed).toContain("title: 'Keep this title'")
++})
diff --git a/nextjs-codemod-noninteractive-upgrade/tests/test.sh b/nextjs-codemod-noninteractive-upgrade/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..dc03d57d768f28bfaacd75df606f43aa672bc716
--- /dev/null
+++ b/nextjs-codemod-noninteractive-upgrade/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-codemod/lib/__tests__/upgrade-non-interactive.test.js' --exclude='packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js/*' /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-codemod/lib/__tests__/upgrade-non-interactive.test.js' 2>/dev/null || true
+ git -C /app clean -fd -- 'packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js' >/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-codemod/lib/__tests__/upgrade-non-interactive.test.js'; 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 'corepack pnpm@10.33.0 test-webpack '"'"'packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'corepack pnpm@10.33.0 test-webpack '"'"'packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js'"'"''; 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 'corepack pnpm@10.33.0 test-webpack '"'"'packages/next-codemod/transforms/__tests__/remove-unstable-prefix.test.js'"'"''; 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 < {
+ // TODO: should route-module itself handle rendering the 404
+ if (routerServerContext?.render404) {
++ // When the Pages and App Routers coexist, a Pages Router 404 renders
++ // the App Router not-found page. A direct route-module invocation
++ // cannot provide the postponed state needed to resume that App Router
++ // output, so an empty postponed state signals that the renderer must
++ // perform a complete dynamic render instead.
++ //
++ // TODO: Re-enter routing with the App Router not-found output so its
++ // prerender and postponed state can be selected and resumed.
++ if (
++ nextConfig.cacheComponents &&
++ !routerServerContext.isWrappedByNextServer &&
++ typeof getRequestMeta(req, 'postponed') !== 'string'
++ ) {
++ addRequestMeta(req, 'postponed', '')
++ }
+ await routerServerContext.render404(req, res, parsedUrl, false)
+ } else {
+ res.end('This page could not be found')
diff --git a/nextjs-hybrid-router-adapter-not-found/solution/solve.sh b/nextjs-hybrid-router-adapter-not-found/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-hybrid-router-adapter-not-found/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-hybrid-router-adapter-not-found/tests/Dockerfile b/nextjs-hybrid-router-adapter-not-found/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..11a4d33bf90566c1b2b3c902724222e8b7b0adb8
--- /dev/null
+++ b/nextjs-hybrid-router-adapter-not-found/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 && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile' \
+ && 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-hybrid-router-adapter-not-found/tests/test.patch b/nextjs-hybrid-router-adapter-not-found/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..3d692c93ba675caec05176fd461e3b7cc237cbbb
--- /dev/null
+++ b/nextjs-hybrid-router-adapter-not-found/tests/test.patch
@@ -0,0 +1,209 @@
+diff --git a/test/e2e/app-dir/pages-router-app-not-found/adapter-launcher.js b/test/e2e/app-dir/pages-router-app-not-found/adapter-launcher.js
+new file mode 100644
+index 00000000..068d62ae
+--- /dev/null
++++ b/test/e2e/app-dir/pages-router-app-not-found/adapter-launcher.js
+@@ -0,0 +1,46 @@
++// Mimics an adapter invoking a Pages output and handing its 404 render to the
++// separately compiled App Router not-found output.
++const http = require('http')
++const path = require('path')
++
++require('next/dist/build/adapter/setup-node-env.external')
++
++const dir = process.cwd()
++const port = Number(process.env.PORT)
++const pagesRoute = require(path.join(
++ dir,
++ '.next/server/pages/pages-route/[...slug].js'
++))
++const appNotFound = require(path.join(
++ dir,
++ '.next/server/app/_not-found/page.js'
++))
++
++http
++ .createServer((req, res) => {
++ const requestMeta = {
++ minimalMode: true,
++ relativeProjectDir: '.',
++ initURL: `https://localhost${req.url}`,
++ render404: async (notFoundReq, notFoundRes) => {
++ await appNotFound.handler(notFoundReq, notFoundRes, {
++ waitUntil: undefined,
++ requestMeta,
++ })
++ },
++ }
++
++ Promise.resolve(
++ pagesRoute.handler(req, res, {
++ waitUntil: undefined,
++ requestMeta,
++ })
++ ).catch((err) => {
++ console.error('handler error', err)
++ if (!res.writableEnded) {
++ res.statusCode = 500
++ res.end('internal error')
++ }
++ })
++ })
++ .listen(port, () => console.log('adapter launcher ready'))
+diff --git a/test/e2e/app-dir/pages-router-app-not-found/app/layout.tsx b/test/e2e/app-dir/pages-router-app-not-found/app/layout.tsx
+new file mode 100644
+index 00000000..888614de
+--- /dev/null
++++ b/test/e2e/app-dir/pages-router-app-not-found/app/layout.tsx
+@@ -0,0 +1,8 @@
++import { ReactNode } from 'react'
++export default function Root({ children }: { children: ReactNode }) {
++ return (
++
++ {children}
++
++ )
++}
+diff --git a/test/e2e/app-dir/pages-router-app-not-found/app/not-found.tsx b/test/e2e/app-dir/pages-router-app-not-found/app/not-found.tsx
+new file mode 100644
+index 00000000..5c587676
+--- /dev/null
++++ b/test/e2e/app-dir/pages-router-app-not-found/app/not-found.tsx
+@@ -0,0 +1,20 @@
++import { Suspense } from 'react'
++import { cookies } from 'next/headers'
++
++async function DynamicNotFound() {
++ const cookieStore = await cookies()
++ const marker = cookieStore.get('not-found-marker')?.value ?? 'missing'
++
++ return
++}
diff --git a/nextjs-hybrid-router-adapter-not-found/tests/test.sh b/nextjs-hybrid-router-adapter-not-found/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..66f3856ed93670a3425d4231bce7020b69b00be7
--- /dev/null
+++ b/nextjs-hybrid-router-adapter-not-found/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/pages-router-app-not-found/pages-router-app-not-found.test.ts' --exclude='test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.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/pages-router-app-not-found/pages-router-app-not-found.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.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/pages-router-app-not-found/pages-router-app-not-found.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-start-webpack '"'"'test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-start-webpack '"'"'test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.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 < {
+- runRemainingActions(actionQueue, setState)
++ runRemainingActions(actionQueue, action, setState)
+ action.reject(err)
+ })
+ } else {
+@@ -197,6 +202,10 @@ function dispatchAction(
+ // (Note that it can't contain any earlier navigations, because we always put those into `actionQueue.pending` by calling `runAction`)
+ newAction.next = actionQueue.pending.next
+
++ if (actionQueue.last === actionQueue.pending) {
++ actionQueue.last = newAction
++ }
++
+ runAction({
+ actionQueue,
+ action: newAction,
diff --git a/nextjs-navigation-server-action-in-flight/solution/solve.sh b/nextjs-navigation-server-action-in-flight/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-navigation-server-action-in-flight/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-navigation-server-action-in-flight/tests/Dockerfile b/nextjs-navigation-server-action-in-flight/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..641984cfd8a50c684b99549a3092fdcfd6ae3f49
--- /dev/null
+++ b/nextjs-navigation-server-action-in-flight/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 && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps --only-shell 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-navigation-server-action-in-flight/tests/test.patch b/nextjs-navigation-server-action-in-flight/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..47c9cc41d6154b86829a690791c9d61cfd5502bf
--- /dev/null
+++ b/nextjs-navigation-server-action-in-flight/tests/test.patch
@@ -0,0 +1,385 @@
+diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts b/test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts
+new file mode 100644
+index 00000000..bf1b09fa
+--- /dev/null
++++ b/test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts
+@@ -0,0 +1,167 @@
++import { nextTestSetup } from 'e2e-utils'
++import type * as Playwright from 'playwright'
++import { createRouterAct } from 'router-act'
++
++describe('discarded action settling while a navigation is pending (#86151)', () => {
++ const { next } = nextTestSetup({ files: __dirname })
++
++ // Navigating while a server action is in flight discards that action:
++ // its result is never applied. These tests cover the window where the
++ // discarded action's response arrives while the navigation is still
++ // ongoing. The navigation must not be reverted, and later actions must
++ // not run until it finishes — if one ran earlier, it would see the
++ // pre-navigation page and undo the navigation.
++ async function interleave(
++ dispatchButton: string,
++ options?: { allowErrorStatusCodes: number[] }
++ ) {
++ let page: Playwright.Page
++ const browser = await next.browser('/', {
++ beforePageLoad(p: Playwright.Page) {
++ page = p
++ },
++ })
++ const act = createRouterAct(page, options)
++
++ // data-render counts how many times the client received new data for
++ // the root layout. Navigations preserve the root layout, so it only
++ // changes when the router refreshes.
++ const initialRender = await browser
++ .elementById('stamp')
++ .getAttribute('data-render')
++
++ await act(
++ async () => {
++ // Start server action A. Its response is withheld, so it stays in
++ // flight throughout this scope.
++ await act(async () => {
++ await browser.elementById(dispatchButton).click()
++ }, 'block')
++
++ // Start server action B. Actions run one at a time, so B waits for
++ // A and no request is issued yet.
++ await act(async () => {
++ await browser.elementById('dispatch-b').click()
++ }, 'no-requests')
++
++ // Navigate before A or B finished. This discards A. The navigation
++ // response is withheld too, so the navigation is still ongoing when
++ // A's response arrives below.
++ await act(
++ async () => {
++ await browser.elementById('go-dest').click()
++ },
++ { includes: 'Destination page', block: true }
++ )
++
++ // Exiting this scope delivers the withheld responses in the same
++ // order: first A's, mid-navigation — the moment under test — then
++ // the navigation's. Only then may B run.
++ },
++ // B ran and completed.
++ { includes: 'b-result' }
++ )
++
++ // B completing means all three operations have settled.
++ await browser.waitForElementByCss('#status-b[data-status="b-result"]')
++
++ // If B ran too early, it saw the pre-navigation page — but that is not
++ // necessarily visible yet. Running one more action makes it visible:
++ // with the bug, the URL flips back to "/" here instead of staying
++ // on /dest.
++ await act(
++ async () => {
++ await browser.elementById('dispatch-c').click()
++ },
++ { includes: 'c-result' }
++ )
++ await browser.waitForElementByCss('#status-c[data-status="c-result"]')
++
++ expect(new URL(await browser.url()).pathname).toBe('/dest')
++ expect(await browser.elementById('dest').text()).toBe('Destination page')
++
++ return { browser, initialRender }
++ }
++
++ it('keeps the navigation when the discarded action resolves', async () => {
++ const { browser, initialRender } = await interleave('dispatch-resolve')
++
++ // The discarded action didn't revalidate anything, so there must be
++ // no refresh.
++ expect(await browser.elementById('stamp').getAttribute('data-render')).toBe(
++ initialRender
++ )
++ })
++
++ // Same scenario, but the discarded action fails. Failure is handled
++ // separately from success, so cover both.
++ it('keeps the navigation when the discarded action rejects', async () => {
++ const { browser, initialRender } = await interleave('dispatch-reject', {
++ // A server action that throws responds with a 500.
++ allowErrorStatusCodes: [500],
++ })
++
++ await browser.waitForElementByCss('#status-a[data-status="rejected"]')
++ expect(await browser.elementById('stamp').getAttribute('data-render')).toBe(
++ initialRender
++ )
++ })
++
++ // An action can also be dispatched *while* the navigation is ongoing.
++ // It must run once the navigation finishes. (At one point it never ran:
++ // its caller never settled, and the router stopped applying updates
++ // entirely — the URL never even changed to the navigation target.)
++ it('runs an action dispatched during the navigation once it finishes', async () => {
++ let page: Playwright.Page
++ const browser = await next.browser('/', {
++ beforePageLoad(p: Playwright.Page) {
++ page = p
++ },
++ })
++ const act = createRouterAct(page)
++
++ await act(
++ async () => {
++ // Start server action A. Its response is withheld, so it stays in
++ // flight throughout this scope.
++ await act(async () => {
++ await browser.elementById('dispatch-resolve').click()
++ }, 'block')
++
++ // Navigate before A finished. This discards A. The navigation
++ // response is withheld too, so the navigation is still ongoing
++ // when B is dispatched below.
++ await act(
++ async () => {
++ await browser.elementById('go-dest').click()
++ },
++ { includes: 'Destination page', block: true }
++ )
++
++ // Dispatch server action B while the navigation is ongoing. It
++ // must wait for the navigation, so no request is issued yet.
++ await act(async () => {
++ await browser.elementById('dispatch-b').click()
++ }, 'no-requests')
++ },
++ // B ran once the withheld responses were delivered.
++ { includes: 'b-result' }
++ )
++
++ await browser.waitForElementByCss('#status-b[data-status="b-result"]')
++ expect(new URL(await browser.url()).pathname).toBe('/dest')
++ expect(await browser.elementById('dest').text()).toBe('Destination page')
++ })
++
++ it('defers the refresh from a discarded revalidating action until the queue drains', async () => {
++ const { browser, initialRender } = await interleave('dispatch-revalidate')
++
++ // The discarded action revalidated, so a refresh must still happen —
++ // after everything else, and without undoing the navigation.
++ await browser.waitForElementByCss(
++ `#stamp:not([data-render="${initialRender}"])`
++ )
++ expect(new URL(await browser.url()).pathname).toBe('/dest')
++ expect(await browser.elementById('dest').text()).toBe('Destination page')
++ })
++})
+diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts b/test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts
+new file mode 100644
+index 00000000..eba7c318
+--- /dev/null
++++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts
+@@ -0,0 +1,16 @@
++'use server'
++
++import { revalidatePath } from 'next/cache'
++
++export async function echo(value: string) {
++ return value
++}
++
++export async function reject() {
++ throw new Error('intentional test error')
++}
++
++export async function revalidate() {
++ revalidatePath('/', 'layout')
++ return 'revalidated'
++}
+diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx
+new file mode 100644
+index 00000000..321086c5
+--- /dev/null
++++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx
+@@ -0,0 +1,91 @@
++'use client'
++
++import { useState } from 'react'
++import { useRouter } from 'next/navigation'
++import { echo, reject, revalidate } from './actions'
++
++// Rendered in the root layout so the statuses survive navigations.
++export function Controls() {
++ const router = useRouter()
++ const [a, setA] = useState('idle')
++ const [b, setB] = useState('idle')
++ const [c, setC] = useState('idle')
++
++ async function dispatchResolve() {
++ setA('pending')
++ try {
++ setA(await echo('a-result'))
++ } catch {
++ setA('rejected')
++ }
++ }
++
++ async function dispatchReject() {
++ setA('pending')
++ try {
++ await reject()
++ setA('resolved')
++ } catch {
++ setA('rejected')
++ }
++ }
++
++ async function dispatchRevalidate() {
++ setA('pending')
++ try {
++ setA(await revalidate())
++ } catch {
++ setA('rejected')
++ }
++ }
++
++ async function dispatchB() {
++ setB('pending')
++ try {
++ setB(await echo('b-result'))
++ } catch {
++ setB('rejected')
++ }
++ }
++
++ async function dispatchC() {
++ setC('pending')
++ try {
++ setC(await echo('c-result'))
++ } catch {
++ setC('rejected')
++ }
++ }
++
++ return (
++
++
++
++
++
++
++
++
++ a:{a}
++
++
++ b:{b}
++
++
++ c:{c}
++
++
++ )
++}
+diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx
+new file mode 100644
+index 00000000..f40f1e5e
+--- /dev/null
++++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx
+@@ -0,0 +1,17 @@
++import { Suspense } from 'react'
++import { connection } from 'next/server'
++
++// connection() makes the page dynamic in all modes, so navigating here
++// always produces a router request.
++async function Content() {
++ await connection()
++ return
Destination page
++}
++
++export default function DestPage() {
++ return (
++
++
++
++ )
++}
+diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx
+new file mode 100644
+index 00000000..f387ca61
+--- /dev/null
++++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx
+@@ -0,0 +1,29 @@
++import { Suspense } from 'react'
++import { connection } from 'next/server'
++import { Controls } from './controls'
++import { RenderCounter } from './render-counter'
++
++// The stamp only changes when the router refreshes: navigations preserve the
++// root layout, so a new stamp on the client means a refresh happened.
++async function Stamp() {
++ await connection()
++ return
++}
++
++export default function RootLayout({
++ children,
++}: {
++ children: React.ReactNode
++}) {
++ return (
++
++
++
++
++
++
++ {children}
++
++
++ )
++}
+diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx
+new file mode 100644
+index 00000000..3e134694
+--- /dev/null
++++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx
+@@ -0,0 +1,3 @@
++export default function Page() {
++ return
Origin page
++}
+diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx
+new file mode 100644
+index 00000000..7909f06b
+--- /dev/null
++++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx
+@@ -0,0 +1,20 @@
++'use client'
++
++import { useState } from 'react'
++
++// Counts how many times the client received new dynamic data for the root
++// layout. The count lives in client state: a server-side counter would break
++// in deploy tests, where the server is stateless.
++export function RenderCounter({ uuid }: { uuid: string }) {
++ const [count, setCount] = useState(0)
++ const [prevUuid, setPrevUuid] = useState(uuid)
++ if (prevUuid !== uuid) {
++ setPrevUuid(uuid)
++ setCount(count + 1)
++ }
++ return (
++
++ renders:{count}
++
++ )
++}
diff --git a/nextjs-navigation-server-action-in-flight/tests/test.sh b/nextjs-navigation-server-action-in-flight/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f28182fa2c3344c1dc00adb48871f8373501ead0
--- /dev/null
+++ b/nextjs-navigation-server-action-in-flight/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/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts/*' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts/*' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx/*' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx/*' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx/*' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx/*' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx' --exclude='test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx/*' --exclude='test/e2e/app-dir/navigation-with-queued-actions/index.test.ts' --exclude='test/e2e/app-dir/navigation-with-queued-actions/index.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/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx' 'test/e2e/app-dir/navigation-with-queued-actions/index.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx' 'test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx' 'test/e2e/app-dir/navigation-with-queued-actions/index.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/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts' '/app/test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts' '/app/test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx' '/app/test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx' '/app/test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx' '/app/test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx' '/app/test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx' '/app/test/e2e/app-dir/navigation-with-queued-actions/index.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 --filter next build && pnpm test-dev '"'"'test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm --filter next build && pnpm test-dev '"'"'test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.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 --filter next build && pnpm test-dev '"'"'test/e2e/app-dir/navigation-with-queued-actions/index.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 <(fn: () => T): T {
++ if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isTracingEnabled()) {
++ return fn()
++ }
++ return context.with(ROOT_CONTEXT, fn)
++ }
++
+ public withPropagatedContext(
+ carrier: C,
+ fn: () => T,
+diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts
+index 4b9eb7cb47..4ab6b5c088 100644
+--- a/packages/next/src/server/next-server.ts
++++ b/packages/next/src/server/next-server.ts
+@@ -1730,19 +1730,25 @@ export default class NextNodeServer extends BaseServer<
+ Boolean(requestData.body)
+
+ try {
+- result = await adapterFn({
+- handler:
+- middlewareModule.proxy ||
+- middlewareModule.middleware ||
+- middlewareModule,
+- request: {
+- ...requestData,
+- body: hasRequestBody
+- ? requestData.body.cloneBodyStream()
+- : undefined,
+- },
+- page: 'middleware',
+- })
++ // Node.js middleware runs in-process, inside the active
++ // `handleRequest` span. Detach that span so the middleware span
++ // becomes a sibling root (or parents to an incoming traceparent),
++ // matching edge middleware which runs in a detached sandbox.
++ result = await getTracer().runWithDetachedContext(() =>
++ adapterFn({
++ handler:
++ middlewareModule.proxy ||
++ middlewareModule.middleware ||
++ middlewareModule,
++ request: {
++ ...requestData,
++ body: hasRequestBody
++ ? requestData.body.cloneBodyStream()
++ : undefined,
++ },
++ page: 'middleware',
++ })
++ )
+ } finally {
+ if (hasRequestBody) {
+ await requestData.body.finalize()
diff --git a/nextjs-otel-node-middleware-parent/solution/solve.sh b/nextjs-otel-node-middleware-parent/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-otel-node-middleware-parent/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-otel-node-middleware-parent/tests/Dockerfile b/nextjs-otel-node-middleware-parent/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f4aa6426914064f3babcfe34faf873fc71881017
--- /dev/null
+++ b/nextjs-otel-node-middleware-parent/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' \
+ && 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-otel-node-middleware-parent/tests/test.patch b/nextjs-otel-node-middleware-parent/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..a0093ee3b1e1baa83874a7dbb7b1fa0439f1ab2d
--- /dev/null
+++ b/nextjs-otel-node-middleware-parent/tests/test.patch
@@ -0,0 +1,108 @@
+diff --git a/test/e2e/opentelemetry/instrumentation/middleware-parent.test.ts b/test/e2e/opentelemetry/instrumentation/middleware-parent.test.ts
+new file mode 100644
+index 0000000000..6631d2b0fd
+--- /dev/null
++++ b/test/e2e/opentelemetry/instrumentation/middleware-parent.test.ts
+@@ -0,0 +1,82 @@
++import { FileRef, nextTestSetup } from 'e2e-utils'
++import { retry } from 'next-test-utils'
++import path from 'path'
++
++import { type Collector, connectCollector } from './collector'
++
++const COLLECTOR_PORT = 9001
++const EXTERNAL_TRACE_ID = 'ee75cd9e534ff5e9ed78b4a0c706f0f2'
++const EXTERNAL_SPAN_ID = '0f6a325411bdc432'
++
++describe('Node.js middleware OpenTelemetry parent context', () => {
++ let collector: Collector
++
++ beforeEach(async () => {
++ collector = await connectCollector({ port: COLLECTOR_PORT })
++ })
++
++ afterEach(async () => {
++ await collector.shutdown()
++ })
++
++ const { next, skipped } = nextTestSetup({
++ files: __dirname,
++ skipDeployment: true,
++ dependencies: require('./package.json').dependencies,
++ env: {
++ TEST_OTEL_COLLECTOR_PORT: String(COLLECTOR_PORT),
++ NEXT_TELEMETRY_DISABLED: '1',
++ },
++ overrideFiles: {
++ 'middleware.ts': new FileRef(path.join(__dirname, 'middleware-node.ts')),
++ },
++ })
++
++ if (skipped) return
++
++ it.each([
++ {
++ context: 'without an incoming trace',
++ fetchInit: undefined,
++ expectedParentId: undefined,
++ expectedTraceId: undefined,
++ },
++ {
++ context: 'with an incoming trace',
++ fetchInit: {
++ headers: {
++ traceparent: `00-${EXTERNAL_TRACE_ID}-${EXTERNAL_SPAN_ID}-01`,
++ },
++ },
++ expectedParentId: EXTERNAL_SPAN_ID,
++ expectedTraceId: EXTERNAL_TRACE_ID,
++ },
++ ])('$context', async ({ fetchInit, expectedParentId, expectedTraceId }) => {
++ const response = await next.fetch('/behind-middleware', fetchInit)
++ expect(response.status).toBe(200)
++
++ await retry(() => {
++ const spans = collector.getSpans()
++ const requestSpan = spans.find(
++ (span) =>
++ span.attributes?.['next.span_type'] === 'BaseServer.handleRequest' &&
++ span.attributes?.['http.target'] === '/behind-middleware'
++ )
++ const middlewareSpan = spans.find(
++ (span) =>
++ span.attributes?.['next.span_type'] === 'Middleware.execute' &&
++ span.attributes?.['http.target'] === '/behind-middleware'
++ )
++
++ expect(requestSpan).toBeDefined()
++ expect(middlewareSpan).toBeDefined()
++ expect(requestSpan?.parentId).toBe(expectedParentId)
++ expect(middlewareSpan?.parentId).toBe(expectedParentId)
++ expect(middlewareSpan?.parentId).not.toBe(requestSpan?.id)
++ if (expectedTraceId) {
++ expect(requestSpan?.traceId).toBe(expectedTraceId)
++ expect(middlewareSpan?.traceId).toBe(expectedTraceId)
++ }
++ })
++ })
++})
+diff --git a/test/e2e/opentelemetry/instrumentation/middleware-node.ts b/test/e2e/opentelemetry/instrumentation/middleware-node.ts
+new file mode 100644
+index 0000000000..7c90ccaa2e
+--- /dev/null
++++ b/test/e2e/opentelemetry/instrumentation/middleware-node.ts
+@@ -0,0 +1,14 @@
++import type { NextRequest, NextFetchEvent } from 'next/server'
++import { NextResponse } from 'next/server'
++
++export const config = {
++ matcher: ['/behind-middleware', '/behind-middleware/:path*'],
++ runtime: 'nodejs',
++}
++
++export async function middleware(
++ request: NextRequest,
++ event?: NextFetchEvent
++): Promise {
++ return NextResponse.next()
++}
diff --git a/nextjs-otel-node-middleware-parent/tests/test.sh b/nextjs-otel-node-middleware-parent/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f06d780c23ace967cd9fdd46c8f5f4149759333b
--- /dev/null
+++ b/nextjs-otel-node-middleware-parent/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/opentelemetry/instrumentation/middleware-parent.test.ts' --exclude='test/e2e/opentelemetry/instrumentation/middleware-parent.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/opentelemetry/instrumentation/middleware-parent.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/e2e/opentelemetry/instrumentation/middleware-parent.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/opentelemetry/instrumentation/middleware-parent.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/opentelemetry/instrumentation/middleware-parent.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/opentelemetry/instrumentation/middleware-parent.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 <>>);
++#[allow(clippy::type_complexity)]
++/// For each reference, the targets it resolves to that were dropped as unused. One reference can
++/// resolve to several targets, which are dropped independently.
++pub struct UnusedReferences(
++ FxHashMap>, FxHashSet>>>,
++);
+
+ #[turbo_tasks::value(shared)]
+ #[derive(Debug, Clone, Default)]
+diff --git a/turbopack/crates/turbopack-core/src/module_graph/binding_usage_info.rs b/turbopack/crates/turbopack-core/src/module_graph/binding_usage_info.rs
+index b20f17f4fe..91d610c4bb 100644
+--- a/turbopack/crates/turbopack-core/src/module_graph/binding_usage_info.rs
++++ b/turbopack/crates/turbopack-core/src/module_graph/binding_usage_info.rs
+@@ -115,7 +115,8 @@ pub async fn compute_binding_usage_info(
+ ResolvedVc>,
+ )>::default();
+ let mut unused_references_edges = FxHashSet::default();
+- let mut unused_references = FxHashSet::default();
++ let mut unused_references =
++ FxHashMap::<_, FxHashSet>>>::default();
+
+ let graph = graph.connect();
+ let graph_ref = graph.await?;
+@@ -173,7 +174,10 @@ pub async fn compute_binding_usage_info(
+ target,
+ ));
+ unused_references_edges.insert(edge);
+- unused_references.insert(ref_data.reference);
++ unused_references
++ .entry(ref_data.reference)
++ .or_default()
++ .insert(target);
+ return Ok(GraphTraversalAction::Skip);
+ }
+ // If the current edge is an unused import, skip it
+@@ -194,7 +198,10 @@ pub async fn compute_binding_usage_info(
+ target,
+ ));
+ unused_references_edges.insert(edge);
+- unused_references.insert(ref_data.reference);
++ unused_references
++ .entry(ref_data.reference)
++ .or_default()
++ .insert(target);
+
+ return Ok(GraphTraversalAction::Skip);
+ } else {
+@@ -205,7 +212,14 @@ pub async fn compute_binding_usage_info(
+ target,
+ ));
+ unused_references_edges.remove(&edge);
+- unused_references.remove(&ref_data.reference);
++ if let Entry::Occupied(mut e) =
++ unused_references.entry(ref_data.reference)
++ {
++ e.get_mut().remove(&target);
++ if e.get().is_empty() {
++ e.remove();
++ }
++ }
+ // Continue, add export
+ }
+ }
+@@ -217,7 +231,14 @@ pub async fn compute_binding_usage_info(
+ target,
+ ));
+ unused_references_edges.remove(&edge);
+- unused_references.remove(&ref_data.reference);
++ if let Entry::Occupied(mut e) =
++ unused_references.entry(ref_data.reference)
++ {
++ e.get_mut().remove(&target);
++ if e.get().is_empty() {
++ e.remove();
++ }
++ }
+ // Continue, has to always be included
+ }
+ }
+@@ -252,7 +273,7 @@ pub async fn compute_binding_usage_info(
+
+ graph_ref.traverse_cycles(
+ // No need to traverse edges that are unused.
+- |e| e.chunking_type.is_parallel() && !unused_references.contains(&e.reference),
++ |e| e.chunking_type.is_parallel() && !unused_references.contains_key(&e.reference),
+ |cycle| {
+ // We could compute this based on the module graph via a DFS from each entry point
+ // to the cycle. Whatever node is hit first is an entry point to the cycle.
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/amd.rs b/turbopack/crates/turbopack-ecmascript/src/references/amd.rs
+index d9499c5565..4b2c1e2174 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/amd.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/amd.rs
+@@ -176,6 +176,7 @@ impl AmdDefineWithDependenciesCodeGen {
+ self.error_mode,
+ ),
+ ResolveType::ChunkItem,
++ None,
+ )
+ .await?,
+ request_str: request_str.to_string(),
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/cjs.rs b/turbopack/crates/turbopack-ecmascript/src/references/cjs.rs
+index 21c0d29b3a..b574797e0a 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/cjs.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/cjs.rs
+@@ -204,28 +204,13 @@ impl CjsRequireAssetReferenceCodeGen {
+ ) -> Result {
+ let reference = self.reference.await?;
+
+- // This `require()` is in `unused_references`: its result is unused and
+- // the target is side-effect free. Replace the call with a placeholder
+- // at the expression level.
+- if reference.cjs_tree_shaking
+- && chunking_context
+- .unused_references()
+- .contains_key(&ResolvedVc::upcast(self.reference))
+- .await?
+- {
+- let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
+- // `const {a,b} = 0;` is a clever way to assign undefined to all the variables
+- *expr = quote!("0" as Expr);
+- });
+- return Ok(CodeGeneration::visitors(vec![visitor]));
+- }
+-
+ let pm = PatternMapping::resolve_request(
+ *reference.request,
+ *reference.origin,
+ chunking_context,
+ self.reference.resolve_reference(),
+ ResolveType::ChunkItem,
++ Some(Vc::upcast(*self.reference)),
+ )
+ .await?;
+ let mut visitors = Vec::new();
+@@ -366,6 +351,7 @@ impl CjsRequireResolveAssetReferenceCodeGen {
+ chunking_context,
+ self.reference.resolve_reference(),
+ ResolveType::ChunkItem,
++ Some(Vc::upcast(*self.reference)),
+ )
+ .await?;
+ let mut visitors = Vec::new();
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/esm/dynamic.rs b/turbopack/crates/turbopack-ecmascript/src/references/esm/dynamic.rs
+index 8d2ea4018a..7ed73eb04f 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/esm/dynamic.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/esm/dynamic.rs
+@@ -158,6 +158,7 @@ impl EsmAsyncAssetReferenceCodeGen {
+ } else {
+ ResolveType::ChunkItem
+ },
++ Some(Vc::upcast(*self.reference)),
+ )
+ .await?;
+
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/hot_module.rs b/turbopack/crates/turbopack-ecmascript/src/references/hot_module.rs
+index fb739c7eea..9c23c1555f 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/hot_module.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/hot_module.rs
+@@ -144,6 +144,7 @@ impl ModuleHotReferenceCodeGen {
+ chunking_context,
+ resolve_result,
+ ResolveType::ChunkItem,
++ None,
+ )
+ .await
+ })
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/import_meta_glob.rs b/turbopack/crates/turbopack-ecmascript/src/references/import_meta_glob.rs
+index 727407ac1e..170274cf99 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/import_meta_glob.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/import_meta_glob.rs
+@@ -789,6 +789,7 @@ impl EcmascriptChunkPlaceable for ImportMetaGlobAsset {
+ chunking_context,
+ *entry.result,
+ ResolveType::ChunkItem,
++ None,
+ )
+ .await?;
+
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/pattern_mapping.rs b/turbopack/crates/turbopack-ecmascript/src/references/pattern_mapping.rs
+index 8d1d43fe8d..7bb14bfc3c 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/pattern_mapping.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/pattern_mapping.rs
+@@ -2,6 +2,7 @@ use std::{borrow::Cow, collections::HashSet};
+
+ use anyhow::Result;
+ use bincode::{Decode, Encode};
++use rustc_hash::FxHashSet;
+ use swc_core::{
+ common::DUMMY_SP,
+ ecma::ast::{
+@@ -21,6 +22,8 @@ use turbopack_core::{
+ IssueExt, IssueSeverity, StyledString, code_gen::CodeGenerationIssue,
+ module::emit_unknown_module_type_error,
+ },
++ module::Module,
++ reference::ModuleReference,
+ resolve::{
+ ExternalType, ModuleResolveResult, ModuleResolveResultItem, origin::ResolveOrigin,
+ parse::Request,
+@@ -65,6 +68,8 @@ pub(crate) enum SinglePatternMapping {
+ ModuleLoader(ModuleId),
+ /// External reference with request and type
+ External(RcStr, ExternalType),
++ /// The target was unused and dropped from the module graph, so nothing is loaded for it.
++ Dropped,
+ }
+
+ /// A mapping from a request pattern (e.g. "./module", `./images/${name}.png`)
+@@ -105,7 +110,7 @@ impl SinglePatternMapping {
+ )
+ }
+ Self::Unresolvable(request) => throw_module_not_found_expr(request),
+- Self::Ignored => {
++ Self::Ignored | Self::Dropped => {
+ quote!("undefined" as Expr)
+ }
+ Self::Module(module_id) | Self::ModuleLoader(module_id) => module_id_to_lit(module_id),
+@@ -118,6 +123,7 @@ impl SinglePatternMapping {
+ Self::Invalid => self.create_id(key_expr),
+ Self::Unresolvable(request) => throw_module_not_found_expr(request),
+ Self::Ignored => quote!("{}" as Expr),
++ Self::Dropped => quote!("0" as Expr),
+ Self::Module(_) | Self::ModuleLoader(_) => quote!(
+ "$turbopack_require($arg)" as Expr,
+ turbopack_require: Expr = TURBOPACK_REQUIRE.into(),
+@@ -204,7 +210,7 @@ impl SinglePatternMapping {
+ id: Expr = module_id_to_lit(module_id)
+ )
+ }
+- Self::Ignored => {
++ Self::Ignored | Self::Dropped => {
+ quote!("Promise.resolve({})" as Expr)
+ }
+ Self::Module(_) => Expr::Call(CallExpr {
+@@ -305,6 +311,7 @@ async fn to_single_pattern_mapping(
+ resolve_item: &ModuleResolveResultItem,
+ primary: &[(turbopack_core::resolve::RequestKey, ModuleResolveResultItem)],
+ resolve_type: ResolveType,
++ dropped_targets: Option<&FxHashSet>>>,
+ ) -> Result {
+ let module = match resolve_item {
+ ModuleResolveResultItem::Module(module) => *module,
+@@ -335,6 +342,7 @@ async fn to_single_pattern_mapping(
+ &primary[*first].1,
+ primary,
+ resolve_type,
++ dropped_targets,
+ ))
+ .await;
+ }
+@@ -362,6 +370,10 @@ async fn to_single_pattern_mapping(
+ return Ok(SinglePatternMapping::Invalid);
+ }
+ };
++ // The module graph dropped the edge to this target, so it has no chunk item to point at.
++ if dropped_targets.is_some_and(|dropped| dropped.contains(&module)) {
++ return Ok(SinglePatternMapping::Dropped);
++ }
+ if let Some(chunkable) = ResolvedVc::try_downcast::>(module) {
+ match resolve_type {
+ ResolveType::AsyncChunkLoader => {
+@@ -406,8 +418,18 @@ impl PatternMapping {
+ chunking_context: Vc>,
+ resolve_result: Vc,
+ resolve_type: ResolveType,
++ reference: Option>>,
+ ) -> Result> {
+ let result = resolve_result.await?;
++ // Targets of this reference that were dropped from the module graph as unused.
++ let unused_references;
++ let dropped_targets = match reference {
++ Some(reference) => {
++ unused_references = chunking_context.unused_references().await?;
++ unused_references.get(&reference)
++ }
++ None => None,
++ };
+ match result.primary.len() {
+ 0 => Ok(PatternMapping::Single(SinglePatternMapping::Unresolvable(
+ request_to_string(request).await?.to_string(),
+@@ -421,6 +443,7 @@ impl PatternMapping {
+ resolve_item,
+ &result.primary,
+ resolve_type,
++ dropped_targets,
+ )
+ .await?;
+ Ok(PatternMapping::Single(single_pattern_mapping).cell())
+@@ -444,6 +467,7 @@ impl PatternMapping {
+ v,
+ primary,
+ resolve_type,
++ dropped_targets,
+ )
+ .await?;
+ Ok((k, single_pattern_mapping))
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/require_context.rs b/turbopack/crates/turbopack-ecmascript/src/references/require_context.rs
+index 772a4e48c7..c0c415a749 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/require_context.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/require_context.rs
+@@ -488,6 +488,7 @@ impl EcmascriptChunkPlaceable for RequireContextAsset {
+ chunking_context,
+ *entry.result,
+ ResolveType::ChunkItem,
++ None,
+ )
+ .await?;
+
+diff --git a/turbopack/crates/turbopack-ecmascript/src/references/worker.rs b/turbopack/crates/turbopack-ecmascript/src/references/worker.rs
+index a3d6d23b4b..b4972941e0 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/references/worker.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/references/worker.rs
+@@ -348,6 +348,7 @@ impl WorkerAssetReferenceCodeGen {
+ chunking_context,
+ self.reference.resolve_reference(),
+ ResolveType::ChunkItem,
++ None,
+ )
+ .await?;
+
diff --git a/nextjs-pr-96284/solution/solve.sh b/nextjs-pr-96284/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-pr-96284/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-pr-96284/tests/Dockerfile b/nextjs-pr-96284/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..508efa9ba7e7d80b600a9e633c880e75f14af3bb
--- /dev/null
+++ b/nextjs-pr-96284/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 && NEXT_SKIP_NATIVE_POSTINSTALL=1 pnpm install --frozen-lockfile && pnpm --filter @next/swc build-native && 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-pr-96284/tests/test.patch b/nextjs-pr-96284/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..e1e153805ae6f606d06fdb3f46743a8124fe17ff
--- /dev/null
+++ b/nextjs-pr-96284/tests/test.patch
@@ -0,0 +1,113 @@
+diff --git a/test/production/app-dir/dynamic-import-evaluation-only/app/layout.tsx b/test/production/app-dir/dynamic-import-evaluation-only/app/layout.tsx
+new file mode 100644
+index 00000000..888614de
+--- /dev/null
++++ b/test/production/app-dir/dynamic-import-evaluation-only/app/layout.tsx
+@@ -0,0 +1,8 @@
++import { ReactNode } from 'react'
++export default function Root({ children }: { children: ReactNode }) {
++ return (
++
++ {children}
++
++ )
++}
+diff --git a/test/production/app-dir/dynamic-import-evaluation-only/app/page.tsx b/test/production/app-dir/dynamic-import-evaluation-only/app/page.tsx
+new file mode 100644
+index 00000000..f2ae521c
+--- /dev/null
++++ b/test/production/app-dir/dynamic-import-evaluation-only/app/page.tsx
+@@ -0,0 +1,20 @@
++// Keep this helper opaque enough that Turbopack must retain a request pattern rather than
++// folding it to the locale used while prerendering.
++async function loadLocale(locale: string) {
++ // Nothing is consumed, so every target of this request is evaluation-only. The targets still
++ // need separate side-effect decisions because the pattern resolves to both locale modules.
++ // eslint-disable-next-line no-empty-pattern
++ const {} = await import(`../locales/${locale}`)
++}
++
++export default async function Page() {
++ // This side-effect-free, evaluation-only target should disappear completely.
++ // eslint-disable-next-line no-empty-pattern
++ const {} = await import('../simple')
++ await loadLocale((globalThis as { __locale?: string }).__locale ?? 'pure')
++
++ // Consuming an export from a dynamic import must retain its normal loading semantics.
++ const { basename } = await import('node:path')
++
++ return
{basename('/dynamic-import/works')}
++}
+diff --git a/test/production/app-dir/dynamic-import-evaluation-only/dynamic-import-evaluation-only.test.ts b/test/production/app-dir/dynamic-import-evaluation-only/dynamic-import-evaluation-only.test.ts
+new file mode 100644
+index 00000000..87a146ec
+--- /dev/null
++++ b/test/production/app-dir/dynamic-import-evaluation-only/dynamic-import-evaluation-only.test.ts
+@@ -0,0 +1,34 @@
++import { nextTestSetup } from 'e2e-utils'
++import fs from 'fs'
++import path from 'path'
++
++describe('dynamic-import-evaluation-only', () => {
++ const { next, skipped } = nextTestSetup({
++ files: __dirname,
++ skipDeployment: true,
++ skipStart: true,
++ })
++ if (skipped) return
++
++ it('handles every dynamic import target according to its usage and side effects', async () => {
++ const { exitCode } = await next.build()
++ expect(exitCode).toBe(0)
++
++ const dir = path.join(next.testDir, '.next/server')
++ const output = fs
++ .readdirSync(dir, { recursive: true, encoding: 'utf8' })
++ .filter((file) => file.endsWith('.js'))
++ .map((file) => fs.readFileSync(path.join(dir, file), 'utf8'))
++ .join('\n')
++
++ // Both the direct and pattern-resolved evaluation-only pure targets are omitted.
++ expect(output).not.toContain('DROPPED_SIMPLE')
++ expect(output).not.toContain('DROPPED_PATTERN')
++ // The effectful target of that same pattern must remain.
++ expect(output).toContain('__kept')
++
++ // A dynamic import whose export is consumed must still execute normally.
++ await next.start()
++ expect(await next.render('/')).toContain('works')
++ })
++})
+diff --git a/test/production/app-dir/dynamic-import-evaluation-only/locales/effectful.js b/test/production/app-dir/dynamic-import-evaluation-only/locales/effectful.js
+new file mode 100644
+index 00000000..35fad446
+--- /dev/null
++++ b/test/production/app-dir/dynamic-import-evaluation-only/locales/effectful.js
+@@ -0,0 +1 @@
++globalThis.__kept = true
+diff --git a/test/production/app-dir/dynamic-import-evaluation-only/locales/pure.js b/test/production/app-dir/dynamic-import-evaluation-only/locales/pure.js
+new file mode 100644
+index 00000000..339226ef
+--- /dev/null
++++ b/test/production/app-dir/dynamic-import-evaluation-only/locales/pure.js
+@@ -0,0 +1 @@
++export const value = 'DROPPED_PATTERN'
+diff --git a/test/production/app-dir/dynamic-import-evaluation-only/next.config.js b/test/production/app-dir/dynamic-import-evaluation-only/next.config.js
+new file mode 100644
+index 00000000..807126e4
+--- /dev/null
++++ b/test/production/app-dir/dynamic-import-evaluation-only/next.config.js
+@@ -0,0 +1,6 @@
++/**
++ * @type {import('next').NextConfig}
++ */
++const nextConfig = {}
++
++module.exports = nextConfig
+diff --git a/test/production/app-dir/dynamic-import-evaluation-only/simple.js b/test/production/app-dir/dynamic-import-evaluation-only/simple.js
+new file mode 100644
+index 00000000..8c339c2d
+--- /dev/null
++++ b/test/production/app-dir/dynamic-import-evaluation-only/simple.js
+@@ -0,0 +1 @@
++export const value = 'DROPPED_SIMPLE'
diff --git a/nextjs-pr-96284/tests/test.sh b/nextjs-pr-96284/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c0c09abad5d892506487a01a723a24657b0276de
--- /dev/null
+++ b/nextjs-pr-96284/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/dynamic-import-evaluation-only/dynamic-import-evaluation-only.test.ts' --exclude='test/production/app-dir/dynamic-import-evaluation-only/dynamic-import-evaluation-only.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/dynamic-import-evaluation-only/dynamic-import-evaluation-only.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/production/app-dir/dynamic-import-evaluation-only/dynamic-import-evaluation-only.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/dynamic-import-evaluation-only/dynamic-import-evaluation-only.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 --filter @next/swc build-native && TURBOPACK_BUILD=1 NEXT_TELEMETRY_DISABLED=1 pnpm test-start-turbo '"'"'test/production/app-dir/dynamic-import-evaluation-only/dynamic-import-evaluation-only.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm --filter @next/swc build-native && TURBOPACK_BUILD=1 NEXT_TELEMETRY_DISABLED=1 pnpm test-start-turbo '"'"'test/production/app-dir/dynamic-import-evaluation-only/dynamic-import-evaluation-only.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 --filter @next/swc build-native && TURBOPACK_BUILD=1 NEXT_TELEMETRY_DISABLED=1 pnpm test-start-turbo '"'"'test/production/typeof-window-replace/typeof-window-replace.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 actionId = actionDescriptor.slice(from, to)
+- if (
+- actionId.length !== ACTION_ID_EXPECTED_LENGTH ||
+- actionDescriptor[to] !== '"'
+- ) {
++ if (!mightBeServerReferenceId(actionId)) {
+ return true
+ }
+
+@@ -1473,15 +1484,13 @@ function isInvalidActionIdFieldName(
+ // The field name must always start with $ACTION_ID_ but since it is
+ // the id is extracted from the key of the field we have already validated
+ // this before entering this function
+- if (
+- actionIdFieldName.length !==
+- $ACTION_ID_.length + ACTION_ID_EXPECTED_LENGTH
+- ) {
++ const actionId = actionIdFieldName.slice($ACTION_ID_.length)
++ if (!mightBeServerReferenceId(actionId)) {
+ // this field name has too few or too many characters
++ // or it is otherwise in the wrong format
+ return true
+ }
+
+- const actionId = actionIdFieldName.slice($ACTION_ID_.length)
+ const entry = serverModuleMap[actionId]
+
+ if (entry == null) {
+diff --git a/packages/next/src/server/app-render/manifests-singleton.ts b/packages/next/src/server/app-render/manifests-singleton.ts
+index 5df89c9881..e58e85aa70 100644
+--- a/packages/next/src/server/app-render/manifests-singleton.ts
++++ b/packages/next/src/server/app-render/manifests-singleton.ts
+@@ -5,6 +5,8 @@ import { InvariantError } from '../../shared/lib/invariant-error'
+ import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
+ import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
+ import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'
++import { mightBeServerReferenceId } from '../../shared/lib/server-reference-info'
++import { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'
+ import { workAsyncStorage } from './work-async-storage.external'
+
+ export interface ServerModuleMap {
+@@ -16,6 +18,37 @@ export interface ServerModuleMap {
+ }
+ }
+
++export function getActionNotFoundError(actionId: string | null): Error {
++ return new Error(
++ `Failed to find Server Action${actionId ? ` "${actionId}"` : ''}. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
++ )
++}
++
++export function getInvalidServerReferenceIdError(id: string): Error {
++ // `id` is arbitrary client-provided input. Unlike the not-found case, it has
++ // not passed the length gate and can reach this error via a malformed server
++ // reference in an action payload, so it may be of any length and contain
++ // control characters. `JSON.stringify` escapes newlines and quotes so it
++ // can't forge log lines, and truncating overly long ids prevents log
++ // flooding. Ids at or below the cap are logged in full so that we only add an
++ // ellipsis to ids that are meaningfully longer than the truncated length.
++ const encoded = JSON.stringify(
++ id.length > MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH
++ ? id.slice(0, TRUNCATED_SERVER_REFERENCE_ID_LENGTH) + '…'
++ : id
++ )
++
++ return new Error(
++ `The Server Reference ID did not match the expected format. Received ${encoded}.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
++ )
++}
++
++// Ids at or below the cap are logged in full. Longer ids are truncated to the
++// shorter length and marked with an ellipsis, so the cap leaves headroom over
++// the truncated length rather than ellipsizing ids that are barely too long.
++const MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH = 100
++const TRUNCATED_SERVER_REFERENCE_ID_LENGTH = 90
++
+ // This is a global singleton that is, among other things, also used to
+ // encode/decode bound args of server function closures. This can't be using a
+ // AsyncLocalStorage as it might happen at the module level.
+@@ -179,48 +212,57 @@ function createProxiedClientReferenceManifest(
+ * runtime, workers, etc. that React doesn't need to know.
+ */
+ function createServerModuleMap(): ServerModuleMap {
+- return new Proxy(
+- {},
+- {
+- get: (_, id: string) => {
+- const workers =
+- getServerActionsManifest()[
+- process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'
+- ]?.[id]?.workers
++ return new Proxy(Object.create(null) as ServerModuleMap, {
++ get: (target, id: string | symbol, receiver) => {
++ // React's debug serialization can probe the module map like a plain object.
++ // These probes are not server reference lookups.
++ if (typeof id !== 'string') {
++ return Reflect.get(target, id, receiver)
++ }
+
+- if (!workers) {
+- return undefined
+- }
++ if (wellKnownProperties.has(id)) {
++ return Reflect.get(target, id, receiver)
++ }
+
+- const workStore = workAsyncStorage.getStore()
++ if (!mightBeServerReferenceId(id)) {
++ throw getInvalidServerReferenceIdError(id)
++ }
+
+- let workerEntry:
+- | { moduleId: string | number; async: boolean }
+- | undefined
+-
+- if (workStore) {
+- workerEntry = workers[normalizeWorkerPageName(workStore.page)]
+- } else {
+- // If there's no work store defined, we can assume that a server
+- // module map is needed during module evaluation, e.g. to create a
+- // server action using a higher-order function. Therefore it should be
+- // safe to return any entry from the manifest that matches the action
+- // ID. They all refer to the same module ID, which must also exist in
+- // the current page bundle. TODO: This is currently not guaranteed in
+- // Turbopack, and needs to be fixed.
+- workerEntry = Object.values(workers).at(0)
+- }
++ const workers =
++ getServerActionsManifest()[
++ process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'
++ ]?.[id]?.workers
+
+- if (!workerEntry) {
+- return undefined
+- }
++ if (!workers) {
++ throw getActionNotFoundError(id)
++ }
+
+- const { moduleId, async } = workerEntry
++ const workStore = workAsyncStorage.getStore()
++
++ let workerEntry: { moduleId: string | number; async: boolean } | undefined
++
++ if (workStore) {
++ workerEntry = workers[normalizeWorkerPageName(workStore.page)]
++ } else {
++ // If there's no work store defined, we can assume that a server
++ // module map is needed during module evaluation, e.g. to create a
++ // server action using a higher-order function. Therefore it should be
++ // safe to return any entry from the manifest that matches the action
++ // ID. They all refer to the same module ID, which must also exist in
++ // the current page bundle. TODO: This is currently not guaranteed in
++ // Turbopack, and needs to be fixed.
++ workerEntry = Object.values(workers).at(0)
++ }
+
+- return { id: moduleId, name: id, chunks: [], async }
+- },
+- }
+- )
++ if (!workerEntry) {
++ throw getActionNotFoundError(id)
++ }
++
++ const { moduleId, async } = workerEntry
++
++ return { id: moduleId, name: id, chunks: [], async }
++ },
++ })
+ }
+
+ /**
+diff --git a/packages/next/src/shared/lib/server-reference-info.ts b/packages/next/src/shared/lib/server-reference-info.ts
+index b8d27b08f7..6dd8687957 100644
+--- a/packages/next/src/shared/lib/server-reference-info.ts
++++ b/packages/next/src/shared/lib/server-reference-info.ts
+@@ -4,6 +4,12 @@ export interface ServerReferenceInfo {
+ hasRestArgs: boolean
+ }
+
++export const SERVER_REFERENCE_ID_LENGTH = 42
++
++export function mightBeServerReferenceId(id: string): boolean {
++ return id.length === SERVER_REFERENCE_ID_LENGTH
++}
++
+ /**
+ * Extracts info about the server reference for the given server reference ID by
+ * parsing the first byte of the hex-encoded ID.
diff --git a/nextjs-server-reference-validation/solution/solve.sh b/nextjs-server-reference-validation/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-server-reference-validation/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-server-reference-validation/tests/Dockerfile b/nextjs-server-reference-validation/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..a99118f80f6a0e58fff53a7161d491969bf346df
--- /dev/null
+++ b/nextjs-server-reference-validation/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 'npm install --global corepack@0.31.0 && corepack enable && pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium && 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-server-reference-validation/tests/test.patch b/nextjs-server-reference-validation/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..68a4fff667ae4a4724032ccf5b3091796dfda308
--- /dev/null
+++ b/nextjs-server-reference-validation/tests/test.patch
@@ -0,0 +1,252 @@
+diff --git a/test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts b/test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts
+index be01f7f9a6..853fcd0d1b 100644
+--- a/test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts
++++ b/test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts
+@@ -1,9 +1,10 @@
+ import { nextTestSetup } from 'e2e-utils'
+ import { createRequestTracker } from 'e2e-utils/request-tracker'
+ import { retry } from 'next-test-utils'
+-import { outdent } from 'outdent'
+
+ describe('unrecognized server actions', () => {
++ const unrecognizedActionId = '0'.repeat(42)
++
+ const { next, isNextDeploy, isNextDev } = nextTestSetup({
+ files: __dirname,
+ })
+@@ -36,50 +37,72 @@ describe('unrecognized server actions', () => {
+ expect(res.status).toBe(404)
+ })
+
+- it.each([
++ describe.each([
+ {
+- // encodeReply encodes simple args as plaintext.
+- name: 'plaintext',
+- request: {
+- contentType: 'text/plain;charset=UTF-8',
+- body: '{}',
+- },
++ idType: 'malformed',
++ actionId: '123',
++ expectedClassification: 'invalid',
+ },
+ {
+- // encodeReply encodes complex args as FormData.
+- // this body is empty and wouldn't match how react encodes an action, but it should be rejected
+- // before we even get to parsing the FormData, so it doesn't really matter.
+- name: 'form-data/multipart',
+- request: {
+- body: new FormData(),
+- },
++ idType: 'plausible but missing',
++ actionId: unrecognizedActionId,
++ expectedClassification: 'missing',
+ },
+- ])(
+- 'should 404 when POSTing a server action with an unrecognized id to a nonexistent page: $name',
+- async ({ request: { contentType, body } }) => {
+- const res = await next.fetch('/non-existent-route', {
+- method: 'POST',
+- headers: {
+- 'next-action': '123',
+- ...(contentType ? { 'content-type': contentType } : undefined),
++ {
++ // Object reflection names must be handled as malformed client input,
++ // rather than being resolved through Object.prototype.
++ idType: 'object reflection property name',
++ actionId: 'toString',
++ expectedClassification: 'invalid',
++ },
++ ])('with a $idType id', ({ actionId, expectedClassification }) => {
++ it.each([
++ {
++ // encodeReply encodes simple args as plaintext.
++ name: 'plaintext',
++ request: {
++ contentType: 'text/plain;charset=UTF-8',
++ body: '{}',
+ },
+- // @ts-expect-error: node-fetch types don't seem to like FormData
+- body,
+- })
++ },
++ {
++ // Complex args are encoded as FormData. Validation should happen
++ // before decoding this intentionally empty payload.
++ name: 'form-data/multipart',
++ request: {
++ body: new FormData(),
++ },
++ },
++ ])(
++ 'should reject a server action request to a nonexistent page: $name',
++ async ({ request: { contentType, body } }) => {
++ const res = await next.fetch('/non-existent-route', {
++ method: 'POST',
++ headers: {
++ 'next-action': actionId,
++ ...(contentType ? { 'content-type': contentType } : undefined),
++ },
++ // @ts-expect-error: node-fetch types don't seem to like FormData
++ body,
++ })
+
+- expect(res.status).toBe(404)
++ expect(res.status).toBe(404)
+
+- const cliOutput = getLogs()
+- expect(cliOutput).not.toContain('TypeError')
+- expect(cliOutput).not.toContain(
+- 'Missing `origin` header from a forwarded Server Actions request'
+- )
+- expect(cliOutput).toInclude(outdent`
+- Failed to find Server Action "123". This request might be from an older or newer deployment.
+- Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
+- `)
+- }
+- )
++ const cliOutput = getLogs()
++ expect(cliOutput).not.toContain('TypeError')
++ if (expectedClassification === 'invalid') {
++ expect(cliOutput).toMatch(/server reference id/i)
++ expect(cliOutput).toMatch(/invalid|malformed|format/i)
++ } else {
++ expect(cliOutput).toMatch(/server action/i)
++ expect(cliOutput).toMatch(/not found|missing|failed to find/i)
++ expect(cliOutput).not.toMatch(
++ /server reference id.{0,100}(invalid|malformed|format)/i
++ )
++ }
++ }
++ )
++ })
+ }
+
+ it('should error when POSTing a urlencoded action to a nonexistent page', async () => {
+@@ -144,12 +167,14 @@ describe('unrecognized server actions', () => {
+ )
+
+ if (!isNextDeploy) {
+- await retry(async () =>
+- expect(getLogs()).toInclude(outdent`
+- Failed to find Server Action "decafc0ffeebad01". This request might be from an older or newer deployment.
+- Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
+- `)
+- )
++ await retry(async () => {
++ const output = getLogs()
++ expect(output).toMatch(/server action/i)
++ expect(output).toMatch(/not found|missing|failed to find/i)
++ expect(output).not.toMatch(
++ /server reference id.{0,100}(invalid|malformed|format)/i
++ )
++ })
+ }
+ } else {
+ // An MPA action, sent without JS.
+@@ -180,11 +205,14 @@ describe('unrecognized server actions', () => {
+ }
+
+ if (!isNextDeploy) {
+- await retry(async () =>
+- expect(getLogs()).toInclude(
+- `Error: Failed to find Server Action. This request might be from an older or newer deployment`
++ await retry(async () => {
++ const output = getLogs()
++ expect(output).toMatch(/server action/i)
++ expect(output).toMatch(/not found|missing|failed to find/i)
++ expect(output).not.toMatch(
++ /server reference id.{0,100}(invalid|malformed|format)/i
+ )
+- )
++ })
+ }
+ }
+ }
+diff --git a/test/e2e/app-dir/actions-unrecognized/app/nodejs/unrecognized-action/page.tsx b/test/e2e/app-dir/actions-unrecognized/app/nodejs/unrecognized-action/page.tsx
+index 5924ba4d09..bb0ed25389 100644
+--- a/test/e2e/app-dir/actions-unrecognized/app/nodejs/unrecognized-action/page.tsx
++++ b/test/e2e/app-dir/actions-unrecognized/app/nodejs/unrecognized-action/page.tsx
+@@ -8,7 +8,7 @@ const action = async (...args: any[]) => {
+ }
+
+ // simulate client-side version skew by changing the action ID to something the server won't recognize
+-setServerActionId(action, 'decafc0ffeebad01')
++setServerActionId(action, '0'.repeat(42))
+
+ export default function Page() {
+ return (
+diff --git a/test/e2e/app-dir/no-server-actions/no-server-actions.test.ts b/test/e2e/app-dir/no-server-actions/no-server-actions.test.ts
+index f384c9dc5c..e7e4285eaf 100644
+--- a/test/e2e/app-dir/no-server-actions/no-server-actions.test.ts
++++ b/test/e2e/app-dir/no-server-actions/no-server-actions.test.ts
+@@ -1,28 +1,53 @@
+ import { nextTestSetup } from 'e2e-utils'
+
+ describe('app-dir - no server actions', () => {
++ const missingActionId = '0'.repeat(42)
++
+ const { next, isNextDeploy } = nextTestSetup({
+ files: __dirname,
+ })
+
+- it('should error when triggering a fetch action on an app with no server actions', async () => {
+- const res = await next.fetch('/', {
+- method: 'POST',
+- headers: {
+- 'Next-Action': 'abc123',
+- },
+- })
++ it.each([
++ {
++ description: 'a malformed id',
++ actionId: 'abc123',
++ expectedClassification: 'invalid',
++ },
++ {
++ description: 'a plausible but missing id',
++ actionId: missingActionId,
++ expectedClassification: 'missing',
++ },
++ ])(
++ 'should reject a fetch action with $description on an app with no server actions',
++ async ({ actionId, expectedClassification }) => {
++ const outputPosition = next.cliOutput.length
++ const res = await next.fetch('/', {
++ method: 'POST',
++ headers: {
++ 'Next-Action': actionId,
++ },
++ })
+
+- expect(res.status).toBe(404)
+- expect(res.headers.get('x-nextjs-action-not-found')).toBe('1')
++ expect(res.status).toBe(404)
++ expect(res.headers.get('x-nextjs-action-not-found')).toBe('1')
+
+- // Runtime logs and custom headers are not forwarded to the client when deployed.
+- if (!isNextDeploy) {
+- expect(next.cliOutput).toContain(
+- 'Failed to find Server Action "abc123". This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action'
+- )
++ // Runtime logs are not available when deployed.
++ if (!isNextDeploy) {
++ const output = next.cliOutput.slice(outputPosition)
++ if (expectedClassification === 'invalid') {
++ expect(output).toMatch(/server reference id/i)
++ expect(output).toMatch(/invalid|malformed|format/i)
++ } else {
++ expect(output).toMatch(/server action/i)
++ expect(output).toMatch(/not found|missing|failed to find/i)
++ expect(output).not.toMatch(
++ /server reference id.{0,100}(invalid|malformed|format)/i
++ )
++ }
++ }
+ }
+- })
++ )
+
+ it('should error when triggering an MPA action on an app with no server actions', async () => {
+ const formData = new FormData()
diff --git a/nextjs-server-reference-validation/tests/test.sh b/nextjs-server-reference-validation/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8541a1f0e5db9ada48bb85e10b1dd164ef40882d
--- /dev/null
+++ b/nextjs-server-reference-validation/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/actions-unrecognized/actions-unrecognized.test.ts' --exclude='test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts/*' --exclude='test/e2e/app-dir/no-server-actions/no-server-actions.test.ts' --exclude='test/e2e/app-dir/no-server-actions/no-server-actions.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/actions-unrecognized/actions-unrecognized.test.ts' 'test/e2e/app-dir/no-server-actions/no-server-actions.test.ts' 2>/dev/null || true
+ git -C /app clean -fd -- 'test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts' 'test/e2e/app-dir/no-server-actions/no-server-actions.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/actions-unrecognized/actions-unrecognized.test.ts' '/app/test/e2e/app-dir/no-server-actions/no-server-actions.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 --filter next build >/dev/null && pnpm test-dev '"'"'test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts'"'"' '"'"'test/e2e/app-dir/no-server-actions/no-server-actions.test.ts'"'"''; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'pnpm --filter next build >/dev/null && pnpm test-dev '"'"'test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts'"'"' '"'"'test/e2e/app-dir/no-server-actions/no-server-actions.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 --filter next build >/dev/null && pnpm test-dev '"'"'test/e2e/app-dir/prerender-encoding/prerender-encoding.test.ts'"'"' '"'"'test/e2e/app-dir/metadata-svg-icon/metadata-svg-icon.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 < turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js; generated_fixture=1; fi; cargo test --locked -p turbopack-tests --test execution --no-run; status=$?; if [ "$generated_fixture" -eq 1 ]; then rm -f turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js; fi; exit "$status"; }' \
+ && chmod -R a+rwX /opt/uv-cache
+RUN git -C /app reset --hard -q HEAD \
+ && git -C /app clean -fdq \
+ && mkdir -p /opt/selfbench \
+ && cp -a /app/.git /opt/selfbench/base.git \
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
+ && chown -R root:root /opt/selfbench \
+ && chmod 700 /opt/selfbench \
+ && mkdir -p /home/agent/.cache/uv \
+ && chown -R agent:agent /home/agent/.cache
+ENV UV_CACHE_DIR=/home/agent/.cache/uv \
+ UV_NO_BUILD_ISOLATION=1
+USER agent
+WORKDIR /app
diff --git a/nextjs-turbopack-hoisted-registration-96697/solution/gold.patch b/nextjs-turbopack-hoisted-registration-96697/solution/gold.patch
new file mode 100644
index 0000000000000000000000000000000000000000..8b1fce3de141510e785533053879fe3ad872fbbd
--- /dev/null
+++ b/nextjs-turbopack-hoisted-registration-96697/solution/gold.patch
@@ -0,0 +1,208 @@
+diff --git a/turbopack/crates/turbopack-ecmascript/src/lib.rs b/turbopack/crates/turbopack-ecmascript/src/lib.rs
+index 8c92ce033c..8caa30535a 100644
+--- a/turbopack/crates/turbopack-ecmascript/src/lib.rs
++++ b/turbopack/crates/turbopack-ecmascript/src/lib.rs
+@@ -61,7 +61,7 @@ use swc_core::{
+ base::SwcComments,
+ common::{
+ BytePos, DUMMY_SP, FileName, GLOBALS, Globals, Loc, Mark, SourceFile, SourceMap,
+- SourceMapper, Span, SpanSnippetError, SyntaxContext,
++ SourceMapper, Span, SpanSnippetError, Spanned, SyntaxContext,
+ comments::{Comment, CommentKind, Comments},
+ source_map::{FileLinesResult, Files, SourceMapLookupError},
+ util::take::Take,
+@@ -1235,6 +1235,41 @@ impl EcmascriptModuleContent {
+ }
+ }
+
++/// Comments delimiting the early hoisted statements, which [`merge_modules`] moves in front of the
++/// merged module so that a cyclic importer can't re-enter it before they ran.
++const EARLY_HOIST_START: &str = " TURBOPACK EARLY HOIST START";
++const EARLY_HOIST_END: &str = " TURBOPACK EARLY HOIST END";
++
++fn early_hoist_comment(text: &str) -> Comment {
++ Comment {
++ kind: CommentKind::Line,
++ span: DUMMY_SP,
++ text: text.into(),
++ }
++}
++
++/// Finds the statements delimited by [`EARLY_HOIST_START`] and [`EARLY_HOIST_END`], as an inclusive
++/// index range over `body` covering both delimiters. Must run before the spans are rewritten.
++fn early_hoist_range(
++ comments: &SwcComments,
++ body: impl Iterator,
++) -> Option<(usize, usize)> {
++ let (mut start, mut end) = (None, None);
++ for (i, span) in body.enumerate() {
++ let Some(leading) = comments.get_leading(span.lo) else {
++ continue;
++ };
++ for comment in leading {
++ if comment.text == EARLY_HOIST_START {
++ start = Some(i);
++ } else if comment.text == EARLY_HOIST_END {
++ end = Some(i);
++ }
++ }
++ }
++ Some((start?, end?))
++}
++
+ /// Merges multiple Ecmascript modules into a single AST, setting the syntax contexts correctly so
+ /// that imports work.
+ ///
+@@ -1404,18 +1439,32 @@ async fn merge_modules(
+ let mut unique_contexts_cache =
+ FxHashMap::with_capacity_and_hasher(contents.len() * 5, Default::default());
+
++ let mut merged_prelude = Vec::new();
+ let mut prepare_module =
+ |module_count: usize,
+ current_module_idx: usize,
+ (module, content): &(ResolvedVc>, CodeGenResult),
+ program: &mut Program,
++ merged_prelude: &mut Vec,
+ lookup_table: &mut Vec| {
+ let _ = tracing::trace_span!("prepare module").entered();
+ if let CodeGenResult {
+ scope_hoisting_syntax_contexts: Some((module_contexts, _)),
++ comments: CodeGenResultComments::Single { extra_comments, .. },
+ ..
+ } = content
+ {
++ // The delimiter comments are keyed by the original spans, so this has to happen
++ // before the visitor below rewrites them.
++ let early_hoisted = match &*program {
++ Program::Module(module) => {
++ early_hoist_range(extra_comments, module.body.iter().map(|i| i.span()))
++ }
++ Program::Script(script) => {
++ early_hoist_range(extra_comments, script.body.iter().map(|s| s.span()))
++ }
++ };
++
+ let modules_header_width = module_count.next_power_of_two().trailing_zeros();
+ GLOBALS.set(globals_merged, || {
+ let mut visitor = SetSyntaxContextVisitor {
+@@ -1435,6 +1484,21 @@ async fn merge_modules(
+ visitor.error
+ })?;
+
++ // Move the delimited statements out, dropping the two delimiters themselves.
++ if let Some((start, end)) = early_hoisted {
++ let mut hoisted: Vec = match program {
++ Program::Module(module) => module.body.drain(start..=end).collect(),
++ Program::Script(script) => script
++ .body
++ .drain(start..=end)
++ .map(ModuleItem::Stmt)
++ .collect(),
++ };
++ hoisted.pop();
++ hoisted.remove(0);
++ merged_prelude.extend(hoisted);
++ }
++
+ Ok(match program.take() {
+ Program::Module(module) => Either::Left(module.body.into_iter()),
+ // A module without any ModuleItem::ModuleDecl but a
+@@ -1465,6 +1529,7 @@ async fn merge_modules(
+ i,
+ &contents[i],
+ &mut programs[i],
++ &mut merged_prelude,
+ &mut lookup_table,
+ )
+ .map_err(|err| (i, err))
+@@ -1495,6 +1560,7 @@ async fn merge_modules(
+ index,
+ &contents[index],
+ &mut programs[index],
++ &mut merged_prelude,
+ &mut lookup_table,
+ )
+ .map_err(|err| (index, err))?
+@@ -1547,7 +1613,7 @@ async fn merge_modules(
+
+ let span = tracing::trace_span!("hygiene").entered();
+ let mut merged_ast = Program::Module(swc_core::ecma::ast::Module {
+- body: result,
++ body: merged_prelude.into_iter().chain(result).collect(),
+ span: DUMMY_SP,
+ shebang: None,
+ });
+@@ -1844,7 +1910,8 @@ async fn process_parse_result(
+ trailing: Default::default(),
+ };
+
+- process_content_with_code_gens(&mut program, globals, &mut code_gens);
++ let early_hoisted_count =
++ process_content_with_code_gens(&mut program, globals, &mut code_gens);
+
+ for comments in code_gens.iter_mut().flat_map(|cg| cg.comments.as_mut()) {
+ let leading = Arc::unwrap_or_clone(take(&mut comments.leading));
+@@ -1860,6 +1927,31 @@ async fn process_parse_result(
+ }
+
+ GLOBALS.set(globals, || {
++ // Delimit the early hoisted statements, which `merge_modules` moves in front of
++ // the merged module this module is part of.
++ if retain_syntax_context.is_some() && early_hoisted_count > 0 {
++ let end = Span::dummy_with_cmt();
++ extra_comments.add_leading(end.lo, early_hoist_comment(EARLY_HOIST_END));
++ let start = Span::dummy_with_cmt();
++ extra_comments.add_leading(start.lo, early_hoist_comment(EARLY_HOIST_START));
++ let (end, start) = (
++ Stmt::Empty(EmptyStmt { span: end }),
++ Stmt::Empty(EmptyStmt { span: start }),
++ );
++ match &mut program {
++ Program::Module(module) => {
++ module
++ .body
++ .insert(early_hoisted_count, ModuleItem::Stmt(end));
++ module.body.insert(0, ModuleItem::Stmt(start));
++ }
++ Program::Script(script) => {
++ script.body.insert(early_hoisted_count, end);
++ script.body.insert(0, start);
++ }
++ }
++ }
++
+ if let Some(prepend_ident_comment) = prepend_ident_comment {
+ let span = Span::dummy_with_cmt();
+ extra_comments.add_leading(span.lo, prepend_ident_comment);
+@@ -2178,12 +2270,13 @@ async fn emit_content(
+ .cell())
+ }
+
++/// Applies the code generations, returning the number of early hoisted statements it prepended.
+ #[instrument(level = Level::TRACE, skip_all, name = "apply code generation")]
+ fn process_content_with_code_gens(
+ program: &mut Program,
+ globals: &Globals,
+ code_gens: &mut Vec,
+-) {
++) -> usize {
+ let mut visitors = Vec::new();
+ let mut root_visitors = Vec::new();
+ let mut early_hoisted_stmts = FxIndexMap::default();
+@@ -2224,6 +2317,7 @@ fn process_content_with_code_gens(
+ }
+ });
+
++ let early_hoisted_count = early_hoisted_stmts.len();
+ match program {
+ Program::Module(ast::Module { body, .. }) => {
+ body.splice(
+@@ -2254,6 +2348,7 @@ fn process_content_with_code_gens(
+ );
+ }
+ };
++ early_hoisted_count
+ }
+
+ /// Like `hygiene`, but only renames the Atoms without clearing all SyntaxContexts
diff --git a/nextjs-turbopack-hoisted-registration-96697/solution/solve.sh b/nextjs-turbopack-hoisted-registration-96697/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2
--- /dev/null
+++ b/nextjs-turbopack-hoisted-registration-96697/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-turbopack-hoisted-registration-96697/tests/Dockerfile b/nextjs-turbopack-hoisted-registration-96697/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..0b83b995498ac716cc7a6bb6b522c5d6565f60d8
--- /dev/null
+++ b/nextjs-turbopack-hoisted-registration-96697/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 && pnpm install --frozen-lockfile --filter execution-test && install -d -m 0775 turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input && { generated_fixture=0; if [ ! -e turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js ]; then : > turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js; generated_fixture=1; fi; cargo test --locked -p turbopack-tests --test execution --no-run; status=$?; if [ "$generated_fixture" -eq 1 ]; then rm -f turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js; fi; exit "$status"; }' \
+ && 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-turbopack-hoisted-registration-96697/tests/test.patch b/nextjs-turbopack-hoisted-registration-96697/tests/test.patch
new file mode 100644
index 0000000000000000000000000000000000000000..e3984c4f6e12c6f684a60b67465eb5f5eab51e07
--- /dev/null
+++ b/nextjs-turbopack-hoisted-registration-96697/tests/test.patch
@@ -0,0 +1,112 @@
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js
+new file mode 100644
+index 00000000..8c60fc84
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js
+@@ -0,0 +1,3 @@
++import './shared.js'
++
++export { instance, instanceFromClosure } from './library/index.js'
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js
+new file mode 100644
+index 00000000..54568125
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js
+@@ -0,0 +1,5 @@
++import { z } from './library/index.js'
++
++import './shared.js'
++
++z.any()
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js
+new file mode 100644
+index 00000000..5c03caf1
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js
+@@ -0,0 +1,8 @@
++it('should evaluate a merged module group only once', async () => {
++ const { instance, instanceFromClosure } = await import('./entry1.js')
++ await import('./entry2.js')
++
++ expect(globalThis.__evaluations).toBe(1)
++ expect(instance).toEqual({ evaluation: 1 })
++ expect(instanceFromClosure()).toBe(instance)
++})
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js
+new file mode 100644
+index 00000000..8910d214
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js
+@@ -0,0 +1,3 @@
++import * as z from './src/index.js'
++export { RealError, instance, instanceFromClosure } from './src/index.js'
++export { z }
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json
+new file mode 100644
+index 00000000..7f1fc33d
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json
+@@ -0,0 +1,4 @@
++{
++ "type": "module",
++ "sideEffects": false
++}
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js
+new file mode 100644
+index 00000000..0a949626
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js
+@@ -0,0 +1 @@
++export const RealError = 'RealError'
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js
+new file mode 100644
+index 00000000..4f206cdc
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js
+@@ -0,0 +1,2 @@
++export { any, instance, instanceFromClosure } from './schemas.js'
++export { RealError } from './errors.js'
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js
+new file mode 100644
+index 00000000..88c90476
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js
+@@ -0,0 +1,5 @@
++import * as schemas from './schemas.js'
++
++export function datetime() {
++ return schemas
++}
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js
+new file mode 100644
+index 00000000..9b8a8d6c
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js
+@@ -0,0 +1,16 @@
++import * as iso from './iso.js'
++import { RealError } from './errors.js'
++
++globalThis.__evaluations = (globalThis.__evaluations ?? 0) + 1
++export const instance = { evaluation: globalThis.__evaluations }
++export function instanceFromClosure() {
++ return instance
++}
++
++RealError
++iso.datetime()
++
++export const anyBase = 1234
++export function any() {
++ return anyBase
++}
+diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js
+new file mode 100644
+index 00000000..ec068856
+--- /dev/null
++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js
+@@ -0,0 +1,5 @@
++import { RealError } from './library/index.js'
++import { z } from './library/index.js'
++
++z.any()
++RealError
diff --git a/nextjs-turbopack-hoisted-registration-96697/tests/test.sh b/nextjs-turbopack-hoisted-registration-96697/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..eb891d018adb9b77859a221e8dec4f45913be2b9
--- /dev/null
+++ b/nextjs-turbopack-hoisted-registration-96697/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='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js/*' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js/*' /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 -- 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js' 2>/dev/null || true
+ git -C /app clean -fd -- 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js' 'turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js' >/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/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry1.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/entry2.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/index.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/index.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/package.json' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/errors.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/index.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/iso.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/library/src/schemas.js' '/app/turbopack/crates/turbopack-tests/tests/execution/turbopack/scope-hoisting/reentrant-group/input/shared.js'; 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 'cargo test --locked -p turbopack-tests --test execution '"'"'test_tests__execution__turbopack__scope_hoisting__reentrant_group__input__index_js'"'"' -- --exact'; then
+ fail_to_pass_exit_code=0
+ fail_to_pass=1
+ if run_verifier_command 'cargo test --locked -p turbopack-tests --test execution '"'"'test_tests__execution__turbopack__scope_hoisting__reentrant_group__input__index_js'"'"' -- --exact'; 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 'cargo test --locked -p turbopack-tests --test execution '"'"'test_tests__execution__turbopack__scope_hoisting__circular_import__input__index_js'"'"' -- --exact'; 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 <