diff --git a/nextjs-95738-assets-hash-salt/environment/Dockerfile b/nextjs-95738-assets-hash-salt/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9e1be30abe5e17c24b3ef3901d373aa45194efba --- /dev/null +++ b/nextjs-95738-assets-hash-salt/environment/Dockerfile @@ -0,0 +1,45 @@ +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 +RUN useradd --create-home --shell /bin/bash agent +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 && PATH="$HOME/.cargo/bin:$PATH" pnpm swc-build-native && pnpm build' \ + && 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-95738-assets-hash-salt/solution/gold.patch b/nextjs-95738-assets-hash-salt/solution/gold.patch new file mode 100644 index 0000000000000000000000000000000000000000..96bbb7f324ccf6c0d9114786f14475f455fd08c1 --- /dev/null +++ b/nextjs-95738-assets-hash-salt/solution/gold.patch @@ -0,0 +1,494 @@ +diff --git a/crates/next-api/src/next_server_nft.rs b/crates/next-api/src/next_server_nft.rs +index 56d1b83ac6cb085133a6c20068764d7df26e8859..972cd0ad6597cdcc3812cbe158fb396604dd5af8 100644 +--- a/crates/next-api/src/next_server_nft.rs ++++ b/crates/next-api/src/next_server_nft.rs +@@ -115,12 +115,15 @@ impl Asset for ServerNftJsonAsset { + ) + .connect(); + ++ let hash_salt = this.project.next_config().output_hash_salt(); ++ + let mut server_output_assets = traced_modules_for_entries( + module_graph, + Modules::empty(), + self.entries(), + Some(self.ignores()), + None, ++ hash_salt, + ) + .await? + .iter() +@@ -133,7 +136,7 @@ impl Asset for ServerNftJsonAsset { + .await? + .context("NFT module has no content")? + .content() +- .hash(HashAlgorithm::Xxh3Hash128Hex) ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) + .await?, + )) + }) +@@ -150,7 +153,7 @@ impl Asset for ServerNftJsonAsset { + .context("failed to compute relative path for server NFT JSON")?, + module_path + .read() +- .hash(HashAlgorithm::Xxh3Hash128Hex) ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) + .await?, + )); + +@@ -170,7 +173,9 @@ impl Asset for ServerNftJsonAsset { + base_dir + .get_relative_path_to(file) + .context("failed to compute relative path for server NFT JSON")?, +- file.read().hash(HashAlgorithm::Xxh3Hash128Hex).await?, ++ file.read() ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) ++ .await?, + )) + } + } +diff --git a/crates/next-api/src/nft.rs b/crates/next-api/src/nft.rs +index ef8162bd3984eb2e1d010ed904a8ee017d994399..f09e23c000afe2a8186b131dac85d677f66b925a 100644 +--- a/crates/next-api/src/nft.rs ++++ b/crates/next-api/src/nft.rs +@@ -67,6 +67,7 @@ pub async fn trace_endpoint( + async { + let project_path = project.project_path().owned().await?; + let next_config = project.next_config(); ++ let hash_salt = next_config.output_hash_salt(); + + let output_file_tracing_includes = next_config + .output_file_tracing_includes(project_path.clone()) +@@ -83,10 +84,11 @@ pub async fn trace_endpoint( + .await? + .map(|v| *v), + Some(next_config.config_file_path(project_path.clone())), ++ hash_salt, + ) + .await?; + +- let module_data = traced_module_data_for_graph(*module_graph, traced_entries) ++ let module_data = traced_module_data_for_graph(*module_graph, traced_entries, hash_salt) + .to_resolved() + .await?; + let module_paths = module_data.await?.idents; +@@ -271,10 +273,11 @@ pub async fn traced_modules_for_entries( + traced_entries: Vc, + exclude_glob: Option>, + forbidden_path: Option>, ++ hash_salt: Vc, + ) -> Result> { + let exclude_glob_and_module_idents = if let Some(exclude_glob) = exclude_glob { + let exclude_glob = exclude_glob.await?; +- let data = traced_module_data_for_graph(module_graph, traced_entries).await?; ++ let data = traced_module_data_for_graph(module_graph, traced_entries, hash_salt).await?; + Some((exclude_glob, data.idents.await?)) + } else { + None +@@ -379,6 +382,7 @@ pub struct TracedModuleData { + pub async fn traced_module_data_for_graph( + module_graph: Vc, + traced_entries: Vc, ++ hash_salt: Vc, + ) -> Result> { + // This function is very similar to traced_modules_for_entries, but doesn't apply the glob and + // is executed only once for the whole graph. +@@ -420,7 +424,7 @@ pub async fn traced_module_data_for_graph( + .await? + .context("NFT module has no content")? + .content() +- .hash(HashAlgorithm::Xxh3Hash128Hex) ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) + .await?, + ), + )) +diff --git a/crates/next-api/src/nft_json.rs b/crates/next-api/src/nft_json.rs +index 957b3c834621bf201f20a967e0774edfe3df0138..6d003c8adcf509a0549ee5db542a4311be7742fc 100644 +--- a/crates/next-api/src/nft_json.rs ++++ b/crates/next-api/src/nft_json.rs +@@ -119,6 +119,7 @@ impl Asset for NftJsonAsset { + let output_root_ref = this.project.output_fs().root().await?; + let project_root_ref = this.project.project_fs().root().await?; + let next_config = this.project.next_config(); ++ let hash_salt = next_config.output_hash_salt(); + + let client_root = this.project.client_fs().root(); + let client_root = client_root.owned().await?; +@@ -173,7 +174,11 @@ impl Asset for NftJsonAsset { + let (referenced_chunk_path, hash) = match referenced { + AssetOrModule::Asset(v) => ( + Either::Left(v.path().await?), +- Either::Left(v.content().hash(HashAlgorithm::Xxh3Hash128Hex).await?), ++ Either::Left( ++ v.content() ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) ++ .await?, ++ ), + ), + AssetOrModule::Module(v) => { + let ident = module_data +@@ -235,7 +240,10 @@ impl Asset for NftJsonAsset { + Ok(( + relative_path, + Either::Left( +- file_path.read().hash(HashAlgorithm::Xxh3Hash128Hex).await?, ++ file_path ++ .read() ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) ++ .await?, + ), + )) + }) +@@ -266,7 +274,10 @@ impl Asset for NftJsonAsset { + // non-adapter consumers (which includes output:standalone) don't experience a breaking + // change, but instead we just add it as a separate field that only build-complete + // reads. +- let entry_hash = chunk.content().hash(HashAlgorithm::Xxh3Hash128Hex).await?; ++ let entry_hash = chunk ++ .content() ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) ++ .await?; + let json = json!({ + "version": 1, + "files": files, +diff --git a/crates/next-api/src/paths.rs b/crates/next-api/src/paths.rs +index 3898419e8425863bb31e9895c915fc91ec21db08..b21dc5b98ea3f153e8120a7685a481799f5c793b 100644 +--- a/crates/next-api/src/paths.rs ++++ b/crates/next-api/src/paths.rs +@@ -46,7 +46,7 @@ async fn asset_path( + } else { + asset + .content() +- .hash(HashAlgorithm::Xxh3Hash128Hex) ++ .hash(no_hash_salt(), HashAlgorithm::Xxh3Hash128Hex) + .owned() + .await? + }; +diff --git a/crates/next-api/src/routes_hashes_manifest.rs b/crates/next-api/src/routes_hashes_manifest.rs +index 4fa51d728cc36039370e500053cfe505ff0a25e0..00cd2feaafeeaac8523673448fd147d32113c1f5 100644 +--- a/crates/next-api/src/routes_hashes_manifest.rs ++++ b/crates/next-api/src/routes_hashes_manifest.rs +@@ -5,7 +5,7 @@ use turbo_tasks::{FxIndexMap, FxIndexSet, ResolvedVc, TryFlatJoinIterExt, TryJoi + use turbo_tasks_fs::{FileContent, FileSystemPath}; + use turbo_tasks_hash::{DeterministicHash, HashAlgorithm, Xxh3Hash64Hasher, hash_xxh3_hash64}; + use turbopack_core::{ +- asset::{Asset, AssetContent}, ++ asset::{Asset, AssetContent, no_hash_salt}, + module::{Module, Modules}, + module_graph::{GraphTraversalAction, ModuleGraph}, + output::{ +@@ -62,7 +62,7 @@ pub async fn endpoints_outputs(endpoints: Vc) -> Result) -> Result> { ++pub async fn outputs_hash(outputs: Vc, hash_salt: Vc) -> Result> { + let output_assets = expand_output_assets( + outputs + .await? +@@ -73,7 +73,11 @@ pub async fn outputs_hash(outputs: Vc) -> Result> { + .await?; + let outputs_hashes = output_assets + .iter() +- .map(|asset| asset.content().hash(HashAlgorithm::Xxh3Hash128Hex)) ++ .map(|asset| { ++ asset ++ .content() ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) ++ }) + .try_join() + .await?; + +@@ -121,7 +125,11 @@ pub async fn endpoints_entry_modules( + } + + #[turbo_tasks::function] +-pub async fn sources_hash(module_graph: Vc, modules: Vc) -> Result> { ++pub async fn sources_hash( ++ module_graph: Vc, ++ modules: Vc, ++ hash_salt: Vc, ++) -> Result> { + let modules = modules.await?; + + let mut all_modules = FxIndexSet::default(); +@@ -144,7 +152,11 @@ pub async fn sources_hash(module_graph: Vc, modules: Vc) - + .try_flat_join() + .await? + .into_iter() +- .map(|source| source.content().hash(HashAlgorithm::Xxh3Hash128Hex)) ++ .map(|source| { ++ source ++ .content() ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) ++ }) + .try_join() + .await?; + +@@ -181,6 +193,7 @@ impl RoutesHashesManifestAsset { + impl Asset for RoutesHashesManifestAsset { + #[turbo_tasks::function] + async fn content(&self) -> Result> { ++ let hash_salt = no_hash_salt(); + let module_graphs = self.project.whole_app_module_graphs().await?; + let base_module_graph = *module_graphs.base; + let full_module_graph = *module_graphs.full; +@@ -195,8 +208,9 @@ impl Asset for RoutesHashesManifestAsset { + sources_hash( + full_module_graph, + endpoint_entry_modules(base_module_graph, *entry.endpoint), ++ hash_salt, + ), +- outputs_hash(endpoint_outputs(*entry.endpoint)), ++ outputs_hash(endpoint_outputs(*entry.endpoint), hash_salt), + ) + } else { + let endpoints = Vc::cell(primary.iter().map(|entry| entry.endpoint).collect()); +@@ -204,8 +218,9 @@ impl Asset for RoutesHashesManifestAsset { + sources_hash( + full_module_graph, + endpoints_entry_modules(base_module_graph, endpoints), ++ hash_salt, + ), +- outputs_hash(endpoints_outputs(endpoints)), ++ outputs_hash(endpoints_outputs(endpoints), hash_salt), + ) + }; + entrypoint_hashes.insert(key.as_str(), entry); +diff --git a/crates/next-api/src/server_actions.rs b/crates/next-api/src/server_actions.rs +index 050b35070e15c736eae4302a83b8d6411b89361d..7e666eefdfba1618c92bc4a95281e3b297b6a8b0 100644 +--- a/crates/next-api/src/server_actions.rs ++++ b/crates/next-api/src/server_actions.rs +@@ -231,11 +231,11 @@ impl Asset for ServerActionManifestAsset { + + let actions_value = self.actions.await?; + let async_module_info = self.module_graph.async_module_info(); +- let durable_use_cache_entries = *self +- .project +- .next_config() ++ let next_config = self.project.next_config(); ++ let durable_use_cache_entries = *next_config + .enable_durable_use_cache_entries(self.project.next_mode()) + .await?; ++ let hash_salt = next_config.output_hash_salt(); + + let loader_id = self.chunk_item.id().await?; + let loader_id = match &loader_id { +@@ -279,6 +279,7 @@ impl Asset for ServerActionManifestAsset { + *self.module_graph, + **module, + *self.chunking_context, ++ hash_salt, + ) + .await?, + ) +@@ -361,6 +362,7 @@ async fn compute_subtree_content_hash( + module_graph: ResolvedVc, + entry: ResolvedVc>, + chunking_context: Vc>, ++ hash_salt: Vc, + ) -> Result> { + let span = tracing::info_span!( + "compute use-cache code hash", +@@ -408,8 +410,14 @@ async fn compute_subtree_content_hash( + .map(async |m| Ok(format!( + " '{}': {}", + m.ident_string().await?, +- module_hash(*module_graph, chunking_context, async_module_info, **m) +- .await? ++ module_hash( ++ *module_graph, ++ chunking_context, ++ async_module_info, ++ **m, ++ hash_salt ++ ) ++ .await? + ))) + .try_join() + .await? +@@ -419,7 +427,15 @@ async fn compute_subtree_content_hash( + + let hashes = modules + .into_iter() +- .map(|m| module_hash(*module_graph, chunking_context, async_module_info, *m)) ++ .map(|m| { ++ module_hash( ++ *module_graph, ++ chunking_context, ++ async_module_info, ++ *m, ++ hash_salt, ++ ) ++ }) + .try_join() + .await?; + +@@ -448,6 +464,7 @@ async fn module_hash( + chunking_context: ResolvedVc>, + async_module_info: ResolvedVc, + m: ResolvedVc>, ++ hash_salt: Vc, + ) -> Result> { + let ident = m.ident(); + let ident_value = ident.await?; +@@ -484,7 +501,7 @@ async fn module_hash( + .await? + .with_context(|| format!("failed to get source for module {ident_str}"))? + .content() +- .hash(HashAlgorithm::Xxh3Hash128Hex) ++ .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex) + .await?; + Ok(Vc::cell(RcStr::from(deterministic_hash( + "", +diff --git a/packages/next/src/build/adapter/build-complete.ts b/packages/next/src/build/adapter/build-complete.ts +index f38163fba9b2e14c170321155ee2300b071ea428..06b283db29ff09ffd8bec8e4d1fb3da6d7d03a89 100644 +--- a/packages/next/src/build/adapter/build-complete.ts ++++ b/packages/next/src/build/adapter/build-complete.ts +@@ -1046,7 +1046,8 @@ export async function handleBuildComplete({ + existingOutput.assetsHashes, + path.relative(repoRoot, pageFile), + pageFile, +- bundler ++ bundler, ++ config.experimental.outputHashSalt || '' + ) + continue + } +@@ -2170,6 +2171,7 @@ async function getSharedNodeAssets({ + const pagesSharedNodeAssetsHashes: Record = {} + const appPagesSharedNodeAssets: Record = {} + const appPagesSharedNodeAssetsHashes: Record = {} ++ const salt = config.experimental.outputHashSalt || '' + + const moduleTypes = ['app-page', 'pages'] as const + +@@ -2201,7 +2203,8 @@ async function getSharedNodeAssets({ + pagesSharedNodeAssetsHashes, + rootRelativeFilePath, + path.join(repoRoot, rootRelativeFilePath), +- bundler ++ bundler, ++ salt + ) + } else { + await pushAsset( +@@ -2209,7 +2212,8 @@ async function getSharedNodeAssets({ + appPagesSharedNodeAssetsHashes, + rootRelativeFilePath, + path.join(repoRoot, rootRelativeFilePath), +- bundler ++ bundler, ++ salt + ) + } + } +@@ -2226,7 +2230,8 @@ async function getSharedNodeAssets({ + sharedNodeAssetsHashes, + path.relative(repoRoot, setupNodeStubPath), + require.resolve('next/dist/build/adapter/setup-node-env.external'), +- bundler ++ bundler, ++ salt + ) + + // Turbopack handles this automatically and these files are listed in the nft.json files. +@@ -2315,7 +2320,8 @@ async function getSharedNodeAssets({ + sharedNodeAssetsHashes, + path.relative(repoRoot, absoluteFilePath), + absoluteFilePath, +- bundler ++ bundler, ++ salt + ) + } + } +@@ -2338,6 +2344,7 @@ async function getSharedNodeAssets({ + fileOutputPath, + path.join(distDir, 'server', 'instrumentation.js'), + bundler, ++ salt, + instrumentationEntryHash + ) + } +@@ -2352,7 +2359,8 @@ async function getSharedNodeAssets({ + sharedNodeAssetsHashes, + fileOutputPath, + filePath, +- bundler ++ bundler, ++ salt + ) + } + +@@ -2372,13 +2380,14 @@ async function pushAsset( + targetFilePath: string, + sourceFilePath: string, + bundler: Bundler, ++ salt: string, + hashOverride?: string + ) { + if (!(targetFilePath in assets)) { + assets[targetFilePath] = sourceFilePath + if (bundler === Bundler.Turbopack) { + assetsHashes[targetFilePath] = +- hashOverride ?? (await hashFile(sourceFilePath)) ++ hashOverride ?? (await hashFile(salt, sourceFilePath)) + } + } + } +@@ -2411,8 +2420,9 @@ async function loadNFT( + return { entryHash } + } + +-async function hashFile(filePath: string): Promise { ++async function hashFile(salt: string, filePath: string): Promise { + const hash = crypto.createHash('sha256') ++ hash.update(salt) + try { + // Try symlink first, since readFile just transparently resolves those (or fails if it's a + // directory symlink). +diff --git a/turbopack/crates/turbo-tasks-fs/src/lib.rs b/turbopack/crates/turbo-tasks-fs/src/lib.rs +index 5546fc1001e90e436b64a529388c67ec86457933..d99202da6518e2f28e852554fdcb881bb75a1912 100644 +--- a/turbopack/crates/turbo-tasks-fs/src/lib.rs ++++ b/turbopack/crates/turbo-tasks-fs/src/lib.rs +@@ -2531,9 +2531,12 @@ impl FileContent { + } + + #[turbo_tasks::function] +- pub fn hash(&self, algorithm: HashAlgorithm) -> Vc { +- // no_hash_salt +- Vc::cell(RcStr::from(deterministic_hash("", self, algorithm))) ++ pub async fn hash(&self, salt: Vc, algorithm: HashAlgorithm) -> Result> { ++ Ok(Vc::cell(RcStr::from(deterministic_hash( ++ &salt.await?, ++ self, ++ algorithm, ++ )))) + } + + /// Converts this [`FileContent`] into a [`PersistedFileContent`] by cloning. +diff --git a/turbopack/crates/turbopack-core/src/asset.rs b/turbopack/crates/turbopack-core/src/asset.rs +index 65cf0e7ecb3f1721ed80cfc7b99a825220a6ab65..860dd6bf169a58a817467dea8dd8e9d0607751b3 100644 +--- a/turbopack/crates/turbopack-core/src/asset.rs ++++ b/turbopack/crates/turbopack-core/src/asset.rs +@@ -131,14 +131,14 @@ impl AssetContent { + } + + #[turbo_tasks::function] +- pub fn hash(&self, algorithm: HashAlgorithm) -> Vc { +- match self { +- AssetContent::File(content) => content.hash(algorithm), ++ pub async fn hash(&self, salt: Vc, algorithm: HashAlgorithm) -> Result> { ++ Ok(match self { ++ AssetContent::File(content) => content.hash(salt, algorithm), + AssetContent::Redirect { target, link_type } => Vc::cell(RcStr::from( + // no_hash_salt +- deterministic_hash("", (target, link_type), algorithm), ++ deterministic_hash(&salt.await?, (target, link_type), algorithm), + )), +- } ++ }) + } + + /// Compared to [AssetContent::hash], this hashes only the bytes of the file content and diff --git a/nextjs-95738-assets-hash-salt/solution/solve.sh b/nextjs-95738-assets-hash-salt/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-95738-assets-hash-salt/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-95738-assets-hash-salt/tests/Dockerfile b/nextjs-95738-assets-hash-salt/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d9ba7d52841f495a233a6a3cef77befcd2c4e429 --- /dev/null +++ b/nextjs-95738-assets-hash-salt/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 && PATH="$HOME/.cargo/bin:$PATH" 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-95738-assets-hash-salt/tests/test.patch b/nextjs-95738-assets-hash-salt/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..3c90ee37ab6b77dd63f58528736df689477b931b --- /dev/null +++ b/nextjs-95738-assets-hash-salt/tests/test.patch @@ -0,0 +1,61 @@ +diff --git a/test/production/deterministic-build/adapter-content-hashes.test.ts b/test/production/deterministic-build/adapter-content-hashes.test.ts +index ece2fe51b9893389cecc4b03b59a781c0a80f552..d14d53680c89ed9e23da1fb3eed1db5e2b9c72ec 100644 +--- a/test/production/deterministic-build/adapter-content-hashes.test.ts ++++ b/test/production/deterministic-build/adapter-content-hashes.test.ts +@@ -61,6 +61,56 @@ import { FILES } from './files' + outputs.pagesApi.forEach(validateOutput) + outputs.appRoutes.forEach(validateOutput) + }) ++ ++ it('hashes respect NEXT_HASH_SALT', async () => { ++ const { ++ outputs: outputs1, ++ }: Parameters[0] = await next.readJSON( ++ 'build-complete.json' ++ ) ++ ++ await next.stop() ++ next.env.NEXT_HASH_SALT = 'something-else' ++ await next.build() ++ ++ const { ++ outputs: outputs2, ++ }: Parameters[0] = await next.readJSON( ++ 'build-complete.json' ++ ) ++ ++ let functions1 = Object.fromEntries( ++ [ ++ ...outputs1.pages, ++ ...outputs1.pagesApi, ++ ...outputs1.appPages, ++ ...outputs1.appRoutes, ++ ].map((output) => [output.pathname, output.assetsHashes]) ++ ) ++ let functions2 = Object.fromEntries( ++ [ ++ ...outputs2.pages, ++ ...outputs2.pagesApi, ++ ...outputs2.appPages, ++ ...outputs2.appRoutes, ++ ].map((output) => [output.pathname, output.assetsHashes]) ++ ) ++ ++ for (const pathname in functions1) { ++ const function1 = functions1[pathname] ++ const function2 = functions2[pathname] ++ for (const file in function1) { ++ const hash1 = function1[file] ++ const hash2 = function2[file] ++ expect(hash1).toBeString() ++ if (hash1 === hash2) { ++ throw new Error( ++ `Hash for ${pathname} file ${file} did not change with NEXT_HASH_SALT: ${hash1}` ++ ) ++ } ++ } ++ } ++ }) + }) + } + ) diff --git a/nextjs-95738-assets-hash-salt/tests/test.sh b/nextjs-95738-assets-hash-salt/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5bc913fe24fed89d945009f004bb148e07945b5f --- /dev/null +++ b/nextjs-95738-assets-hash-salt/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/deterministic-build/adapter-content-hashes.test.ts' --exclude='test/production/deterministic-build/adapter-content-hashes.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/deterministic-build/adapter-content-hashes.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/production/deterministic-build/adapter-content-hashes.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/deterministic-build/adapter-content-hashes.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'PATH="$HOME/.cargo/bin:$PATH" pnpm swc-build-native && pnpm --filter next build && pnpm test-start-turbo '"'"'test/production/deterministic-build/adapter-content-hashes.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'PATH="$HOME/.cargo/bin:$PATH" pnpm swc-build-native && pnpm --filter next build && pnpm test-start-turbo '"'"'test/production/deterministic-build/adapter-content-hashes.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 'PATH="$HOME/.cargo/bin:$PATH" pnpm swc-build-native && pnpm --filter next build && pnpm test-start-turbo '"'"'test/production/adapter-config/adapter-config-export.test.ts'"'"' '"'"'test/production/adapter-config-i18n/adapter-config-i18n.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 < | null = null ++ // Init error from an async userland module, rethrown by ensureUserland(). ++ private _initError: unknown = null ++ private _hasInitError = false + // Synchronous per-request userland getter for Turbopack dev mode. + // Called on every request to pick up server HMR updates. + private readonly _getUserland?: () => AppRouteUserlandModule +@@ -252,7 +255,12 @@ export class AppRouteRouteModule extends RouteModule< + this._pendingUserland = result.then((mod) => { + this._userland = mod + this._pendingUserland = null +- this._initFromUserland() ++ try { ++ this._initFromUserland() ++ } catch (err) { ++ this._initError = err ++ this._hasInitError = true ++ } + }) + } else { + this._userland = result +@@ -275,6 +283,9 @@ export class AppRouteRouteModule extends RouteModule< + if (this._pendingUserland) { + await this._pendingUserland + } ++ if (this._hasInitError) { ++ throw this._initError ++ } + } + + constructor({ +@@ -312,7 +323,12 @@ export class AppRouteRouteModule extends RouteModule< + this._pendingUserland = result.then((mod) => { + this._userland = mod + this._pendingUserland = null +- this._initFromUserland() ++ try { ++ this._initFromUserland() ++ } catch (err) { ++ this._initError = err ++ this._hasInitError = true ++ } + }) + } else { + this._userland = result diff --git a/nextjs-95799-async-route-init-errors/solution/solve.sh b/nextjs-95799-async-route-init-errors/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-95799-async-route-init-errors/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-95799-async-route-init-errors/tests/Dockerfile b/nextjs-95799-async-route-init-errors/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..18022ad4716395fcc390bc4e2674917226ad8b97 --- /dev/null +++ b/nextjs-95799-async-route-init-errors/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 && NEXT_TELEMETRY_DISABLED=1 pnpm build' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-95799-async-route-init-errors/tests/test.patch b/nextjs-95799-async-route-init-errors/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..7fffca15ddabff20e0edce653c124bfe36c1d951 --- /dev/null +++ b/nextjs-95799-async-route-init-errors/tests/test.patch @@ -0,0 +1,142 @@ +diff --git a/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts +new file mode 100644 +index 00000000..b26a97fd +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts +@@ -0,0 +1,6 @@ ++// Top-level await makes this an async module. ++await Promise.resolve() ++ ++export async function GET() { ++ return Response.json({ ok: true }) ++} +diff --git a/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx +new file mode 100644 +index 00000000..888614de +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/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/output-export-async-route-module/fixtures/invalid/app/page.tsx b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx +new file mode 100644 +index 00000000..ff7159d9 +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx +@@ -0,0 +1,3 @@ ++export default function Page() { ++ return

hello world

++} +diff --git a/test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js +new file mode 100644 +index 00000000..fecf9218 +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js +@@ -0,0 +1,8 @@ ++/** ++ * @type {import('next').NextConfig} ++ */ ++const nextConfig = { ++ output: 'export', ++} ++ ++module.exports = nextConfig +diff --git a/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts +new file mode 100644 +index 00000000..c60b6bb7 +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts +@@ -0,0 +1,8 @@ ++// Top-level await makes this an async module. ++await Promise.resolve() ++ ++export const dynamic = 'force-static' ++ ++export async function GET() { ++ return Response.json({ ok: true }) ++} +diff --git a/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx +new file mode 100644 +index 00000000..888614de +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/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/output-export-async-route-module/fixtures/valid/app/page.tsx b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx +new file mode 100644 +index 00000000..ff7159d9 +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx +@@ -0,0 +1,3 @@ ++export default function Page() { ++ return

hello world

++} +diff --git a/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js b/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js +new file mode 100644 +index 00000000..fecf9218 +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js +@@ -0,0 +1,8 @@ ++/** ++ * @type {import('next').NextConfig} ++ */ ++const nextConfig = { ++ output: 'export', ++} ++ ++module.exports = nextConfig +diff --git a/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts b/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts +new file mode 100644 +index 00000000..0c8ac29a +--- /dev/null ++++ b/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts +@@ -0,0 +1,36 @@ ++import { join } from 'path' ++import { nextTestSetup } from 'e2e-utils' ++ ++describe('output-export-async-route-module', () => { ++ describe('invalid route', () => { ++ const { next } = nextTestSetup({ ++ files: join(__dirname, 'fixtures', 'invalid'), ++ skipStart: true, ++ }) ++ ++ // The route module uses top-level await, so its `output: 'export'` ++ // validation runs after the module settles instead of throwing during ++ // require(). The resulting error must still fail the build. ++ it('fails the build when an async route module is not statically exportable', async () => { ++ const { exitCode, cliOutput } = await next.build() ++ expect(cliOutput).toContain( ++ 'not configured on route "/api/data" with "output: export"' ++ ) ++ expect(exitCode).toEqual(expect.any(Number)) ++ expect(exitCode).not.toBe(0) ++ }) ++ }) ++ ++ describe('valid route', () => { ++ const { next } = nextTestSetup({ ++ files: join(__dirname, 'fixtures', 'valid'), ++ skipStart: true, ++ }) ++ ++ it('exports an async route module that is statically exportable', async () => { ++ const { exitCode } = await next.build() ++ expect(exitCode).toBe(0) ++ expect(await next.readFile('out/api/data')).toBe('{"ok":true}') ++ }) ++ }) ++}) diff --git a/nextjs-95799-async-route-init-errors/tests/test.sh b/nextjs-95799-async-route-init-errors/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3098673d5213f11f0d90116d52209d729bc3c3fa --- /dev/null +++ b/nextjs-95799-async-route-init-errors/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx/*' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' --exclude='test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js/*' --exclude='test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts' --exclude='test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' 'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' 'test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' 'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts' '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx' '/app/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js' '/app/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'NEXT_TELEMETRY_DISABLED=1 pnpm --filter next build && pnpm test-start-webpack '"'"'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'NEXT_TELEMETRY_DISABLED=1 pnpm --filter next build && pnpm test-start-webpack '"'"'test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'true'; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json <`, ++ // ...) is not something we have an emitted source map for. ++ let scriptPath = scriptNameOrSourceURL ++ if (scriptNameOrSourceURL.startsWith('file://')) { ++ if (scriptNameOrSourceURL.includes('?')) { ++ return null ++ } ++ try { ++ scriptPath = fileURLToPath(scriptNameOrSourceURL) ++ } catch { ++ return null ++ } ++ } ++ if (!isAbsolute(scriptPath)) { ++ return null ++ } ++ ++ // Only chunks emitted into `distDir` have an on-disk source map to point at. ++ const relativePath = relative(distDir, scriptPath) ++ if ( ++ relativePath.startsWith('..') || ++ // On Windows an absolute path on a different drive is returned unchanged ++ // rather than as a `..`-prefixed relative path. ++ isAbsolute(relativePath) ++ ) { ++ return null ++ } ++ ++ // The emitted source map lives next to its chunk with a `.map` suffix (see ++ // `SourceMapAsset::path`). Encode through `pathToFileURL` so any special ++ // characters in the path are escaped into a well-formed `file:` URL. ++ return pathToFileURL(scriptPath + '.map').href ++} ++ + export async function createHotReloaderTurbopack( + opts: SetupOpts & { isSrcDir: boolean }, + serverFields: ServerFields, +@@ -410,6 +454,14 @@ export async function createHotReloaderTurbopack( + getSourceMapFromTurbopack.bind(null, project) + ) + ++ let canonicalDistDir = distDir ++ try { ++ canonicalDistDir = realpathSync(distDir) ++ } catch {} ++ setBundlerFindSourceMapURLImplementation( ++ getSourceMapURLFromTurbopack.bind(null, canonicalDistDir) ++ ) ++ + // Set up code frame renderer using native bindings + const { installCodeFrameSupport } = + require('../lib/install-code-frame') as typeof import('../lib/install-code-frame') +@@ -417,6 +469,7 @@ export async function createHotReloaderTurbopack( + + opts.onDevServerCleanup?.(async () => { + setBundlerFindSourceMapImplementation(() => undefined) ++ setBundlerFindSourceMapURLImplementation(() => null) + await project.onExit() + await lockfile?.unlock() + }) +diff --git a/packages/next/src/server/lib/source-maps.ts b/packages/next/src/server/lib/source-maps.ts +index 40b3a2204c..10f8a4880b 100644 +--- a/packages/next/src/server/lib/source-maps.ts ++++ b/packages/next/src/server/lib/source-maps.ts +@@ -158,6 +158,36 @@ export function filterStackFrameDEV( + } + } + ++// `scriptNameOrSourceURL` is what React forwards from the stack frame: the ++// script's `getScriptNameOrSourceURL()`, which for the server chunks we can ++// map is an absolute filesystem path, not a URL. The returned value is the ++// source map's URL (`file:` or `data:`). ++type FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null ++// Find the URL of a source map using the bundler's API. ++// Shared via `globalThis` because this module is compiled both into the server ++// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server` ++// (where the dev server registers the implementation), and each copy has its own ++// module state. ++const bundlerFindSourceMapURLSymbol = Symbol.for( ++ 'next.server.bundlerFindSourceMapURL' ++) ++ ++export function setBundlerFindSourceMapURLImplementation( ++ findSourceMapURLImplementation: FindSourceMapURL ++): void { ++ ;(globalThis as any)[bundlerFindSourceMapURLSymbol] = ++ findSourceMapURLImplementation ++} ++ ++function bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null { ++ const implementation: FindSourceMapURL | undefined = (globalThis as any)[ ++ bundlerFindSourceMapURLSymbol ++ ] ++ return implementation === undefined ++ ? null ++ : implementation(scriptNameOrSourceURL) ++} ++ + const invalidSourceMap = Symbol('invalid-source-map') + const sourceMapURLs = new LRUCache( + 512 * 1024 * 1024, +@@ -172,6 +202,19 @@ const sourceMapURLs = new LRUCache( + export function findSourceMapURLDEV( + scriptNameOrSourceURL: string + ): string | null { ++ try { ++ const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL) ++ if (bundlerSourceMapURL !== null) { ++ return bundlerSourceMapURL ++ } ++ } catch (cause) { ++ console.error( ++ `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}` ++ ) ++ } ++ ++ // No bundler implementation (e.g. Webpack): inline the source map Node.js ++ // knows as a `data:` URL. + let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL) + if (sourceMapURL === undefined) { + let sourceMapPayload: ModernSourceMapPayload | undefined +diff --git a/packages/next/src/server/patch-error-inspect.ts b/packages/next/src/server/patch-error-inspect.ts +index be16e4727b..2aa0025d1e 100644 +--- a/packages/next/src/server/patch-error-inspect.ts ++++ b/packages/next/src/server/patch-error-inspect.ts +@@ -181,7 +181,10 @@ function getSourcemappedFrameIfPossible( + let sourceMapConsumer: SyncSourceMapConsumer + let sourceMapPayload: ModernSourceMapPayload + if (sourceMapCacheEntry === undefined) { +- let sourceURL = frame.file ++ // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`) ++ // have their positions padded to match the underlying chunk, so they ++ // resolve via the chunk's source map. ++ let sourceURL = devirtualizeReactServerURL(frame.file) + // e.g. "/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js" + // or "C:\Users\foo\APP\.next\server\chunks\ssr\[root-of-the-server]__2934a0._.js" + // will be keyed by Node.js as "file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js". +@@ -189,8 +192,8 @@ function getSourcemappedFrameIfPossible( + // + // But frame.file might also be "webpack-internal:///(rsc)/./app/bad-sourcemap/page.js" or + // "" or "node:internal/process/task_queues" here +- if (path.isAbsolute(frame.file)) { +- sourceURL = url.pathToFileURL(frame.file).toString() ++ if (path.isAbsolute(sourceURL)) { ++ sourceURL = url.pathToFileURL(sourceURL).toString() + } + let maybeSourceMapPayload: ModernSourceMapPayload | undefined + try { +@@ -228,10 +231,9 @@ function getSourcemappedFrameIfPossible( + // is sufficient to compute relative paths but is actually wrong (the + // chunk and sourcemap have different content hashes). We are using the + // node API to read the sourcemap and it doesn't give us access to the +- // URI. Devirtualize `about://React/Server/file:///path/to/chunk.js?4` to +- // `file:///path/to/chunk.js` so that relative `sources` in the source map +- // resolve against the real chunk URL, not the virtual one. +- const sourceMapURL = devirtualizeReactServerURL(sourceURL) + '.map' ++ // URI. `sourceURL` is already devirtualized so that relative `sources` ++ // resolve against the real chunk URL, not React's virtual one. ++ const sourceMapURL = sourceURL + '.map' + sourceMapConsumer = new SyncSourceMapConsumer( + sourceMapPayload, + // @ts-expect-error: our typings don't include this parameter but it is here. diff --git a/nextjs-95946-file-sourcemaps/solution/solve.sh b/nextjs-95946-file-sourcemaps/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-95946-file-sourcemaps/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-95946-file-sourcemaps/tests/Dockerfile b/nextjs-95946-file-sourcemaps/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4d3094766db897cdab70c85cf0bc39ee0154a31c --- /dev/null +++ b/nextjs-95946-file-sourcemaps/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build && pnpm exec playwright install --with-deps chromium' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-95946-file-sourcemaps/tests/test.patch b/nextjs-95946-file-sourcemaps/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..ae6221b7668454679bd2ec101ac9939e7de1fae1 --- /dev/null +++ b/nextjs-95946-file-sourcemaps/tests/test.patch @@ -0,0 +1,115 @@ +diff --git a/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts b/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts +index be03cedc70..f59cd54945 100644 +--- a/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts ++++ b/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts +@@ -229,6 +229,21 @@ describe('app-dir - server source maps - fake frame source maps', () => { + }).toEqual({ url: script.url, hasSourceMap: true }) + } + ++ if (isTurbopack) { ++ // The resolver silently falls back to inlining `data:` URLs, so a ++ // defect in the `file:` URL derivation keeps all behavior-based ++ // assertions green. Only this assertion catches it. ++ for (const script of fakeScripts) { ++ expect({ ++ url: script.url, ++ sourceMapURL: script.sourceMapURL, ++ }).toEqual({ ++ url: script.url, ++ sourceMapURL: expect.stringMatching(/^file:/), ++ }) ++ } ++ } ++ + // Resolve each source map like a debugger frontend and map the + // padded `_()` call position of each fake function back to its + // original source, like clicking the frame in a debugger would. +@@ -282,6 +297,88 @@ describe('app-dir - server source maps - fake frame source maps', () => { + session.close() + } + }) ++ ++ it('fake stack frames from nested Flight requests are resolvable by an attached debugger', async () => { ++ // Rendering this page produces fake frame scripts whose frame ++ // filenames are `file:` URLs rather than file paths. ++ await next.render('/rsc-error-throw-cached') ++ ++ const target = await findServerInspectorTarget() ++ const session = await CDPSession.connect(target.webSocketDebuggerUrl) ++ try { ++ const evalScripts: { ++ scriptId: string ++ url: string ++ sourceMapURL: string ++ }[] = [] ++ session.onEvent = (method, params) => { ++ if (method === 'Debugger.scriptParsed' && params.hasSourceURL) { ++ evalScripts.push({ ++ scriptId: params.scriptId, ++ url: params.url, ++ sourceMapURL: params.sourceMapURL ?? '', ++ }) ++ } ++ } ++ await session.send('Debugger.enable', { maxScriptsCacheSize: 1 }) ++ ++ await retry(async () => { ++ expect( ++ evalScripts.filter((script) => ++ script.url.startsWith('about://React/Cache/') ++ ).length ++ ).toBeGreaterThan(0) ++ }) ++ ++ // React emits a fake frame script under `about://React/` with a ++ // source map, or, when no source map could be found for it, under ++ // the frame's raw filename without one. ++ const fakeScripts = evalScripts.filter( ++ (script) => ++ script.url.startsWith('about://React/') || ++ (script.url.startsWith('file:') && script.sourceMapURL === '') ++ ) ++ const mappedSources = new Set() ++ for (const script of fakeScripts) { ++ expect({ ++ url: script.url, ++ hasSourceMap: script.sourceMapURL !== '', ++ }).toEqual({ url: script.url, hasSourceMap: true }) ++ ++ const { sourceMap, mapURL } = await resolveSourceMapLikeADebugger( ++ session, ++ script.url, ++ script.sourceMapURL ++ ) ++ const { scriptSource } = await session.send( ++ 'Debugger.getScriptSource', ++ { scriptId: script.scriptId } ++ ) ++ const callIndex = scriptSource.indexOf('_()') ++ if (callIndex === -1) continue ++ const line = scriptSource.slice(0, callIndex).split('\n').length ++ const column = ++ callIndex - (scriptSource.lastIndexOf('\n', callIndex) + 1) ++ ++ const consumer = new SourceMap(sourceMap) ++ const original = consumer.findEntry(line - 1, column) ++ if (original.originalSource !== undefined) { ++ mappedSources.add( ++ mapURL === null ++ ? original.originalSource ++ : new URL(original.originalSource, mapURL).href ++ ) ++ } ++ } ++ ++ const testDirURL = url.pathToFileURL(fs.realpathSync(next.testDir)) ++ expect([...mappedSources]).toContain( ++ `${testDirURL.href}/app/rsc-error-throw-cached/page.js` ++ ) ++ } finally { ++ session.close() ++ } ++ }) + } else { + it('server chunk source maps are resolvable by an attached debugger', async () => { + await next.render('/rsc-error-log') diff --git a/nextjs-95946-file-sourcemaps/tests/test.sh b/nextjs-95946-file-sourcemaps/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b021c4146205395faf19341f6423c78ef283c45e --- /dev/null +++ b/nextjs-95946-file-sourcemaps/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts' --exclude='test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/server-source-maps.test.ts'"'"' '"'"'test/e2e/app-dir/server-source-maps/server-source-maps-edge.test.ts'"'"''; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json <\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [stream] Provide a placeholder with \`\` around the data access\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#wrap-in-or-move-into-suspense\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-runtime` + ) + } + +@@ -16,11 +15,9 @@ export function createDynamicBodyError(route: string): Error { + `\`fetch(...)\` or \`connection()\` accessed outside of \`\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [stream] Provide a placeholder with \`\` around the data access\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` + + ` - [cache] Cache the data access with \`"use cache"\` (does not apply to \`connection()\`)\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic` + ) + } + +@@ -30,9 +27,8 @@ export function createRuntimeBodyErrorInNavigation(route: string): Error { + `\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` accessed outside of \`\` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [stream] Provide a placeholder with \`\` around the data access\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#wrap-in-or-move-into-suspense\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-runtime#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-runtime` + ) + } + +@@ -42,9 +38,8 @@ export function createLinkBodyErrorInNavigation(route: string): Error { + `\`params\` or \`searchParams\` accessed outside of \`\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [stream] Provide a placeholder with \`\` around the data access\n` + +- ` https://nextjs.org/docs/messages/instant-shell-url-data#wrap-in-or-move-into-suspense\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/instant-shell-url-data#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/instant-shell-url-data` + ) + } + +@@ -54,11 +49,9 @@ export function createDynamicBodyErrorInNavigation(route: string): Error { + `\`fetch(...)\` or \`connection()\` accessed outside of \`\` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [stream] Provide a placeholder with \`\` around the data access\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` + + ` - [cache] Cache the data access with \`"use cache"\` (does not apply to \`connection()\`)\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic` + ) + } + +@@ -73,11 +66,9 @@ export function createDynamicOrRuntimeBodyError(route: string): Error { + `\`fetch(...)\`, \`cookies()\`, \`headers()\`, \`params\`, \`searchParams\`, or \`connection()\` accessed outside of \`\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [stream] Provide a placeholder with \`\` around the data access\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` + + ` - [cache] For uncached data (\`fetch\`, database calls): cache the access with \`"use cache"\` (does not apply to \`connection()\`)\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic` + ) + } + +@@ -87,9 +78,8 @@ export function createLinkMetadataError(route: string): Error { + `This route's metadata is blocked, but the rest of its content can be prefetched. \`params\` or \`searchParams\` accessed in \`generateMetadata()\` prevent it from being prefetched.\n\n` + + `Ways to fix this:\n` + + ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` + +- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic` ++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime` + ) + } + +@@ -99,9 +89,8 @@ export function createRuntimeMetadataError(route: string): Error { + `This route's metadata is blocked, but the rest of its content can be prerendered. \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` accessed in \`generateMetadata()\` cause it to run dynamically.\n\n` + + `Ways to fix this:\n` + + ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` + +- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic` ++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime` + ) + } + +@@ -111,9 +100,8 @@ export function createDynamicMetadataError(route: string): Error { + `This route's metadata is blocked, but the rest of its content can be prerendered. \`fetch(...)\` or \`connection()\` accessed in \`generateMetadata()\` cause it to run dynamically.\n\n` + + `Ways to fix this:\n` + + ` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (does not apply to \`connection()\`)\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#cache-the-metadata\n` + +- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#mark-the-route-as-dynamic` ++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic` + ) + } + +@@ -123,9 +111,8 @@ export function createLinkViewportError(route: string): Error { + `\`params\` or \`searchParams\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime` + ) + } + +@@ -135,9 +122,8 @@ export function createRuntimeViewportError(route: string): Error { + `\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime` + ) + } + +@@ -147,9 +133,8 @@ export function createDynamicViewportError(route: string): Error { + `\`fetch(...)\` or \`connection()\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` + + `Ways to fix this:\n` + + ` - [cache] Cache the viewport data with \`"use cache"\` in \`generateViewport()\` (does not apply to \`connection()\`)\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic` + ) + } + +@@ -164,11 +149,9 @@ export function createDynamicOrRuntimeViewportError(route: string): Error { + `This prevents the page from being prerendered, leading to a slower user experience. Unlike metadata, viewport cannot be streamed behind \`\` because it affects the initial page load.\n\n` + + `Ways to fix this:\n` + + ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` + + ` - [cache] For uncached data (\`fetch\`, database calls): cache the viewport with \`"use cache"\` in \`generateViewport()\` (does not apply to \`connection()\`)\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime` + ) + } + +@@ -183,11 +166,9 @@ export function createDynamicOrRuntimeMetadataError(route: string): Error { + `This route's metadata is blocked, but the rest of its content can be prerendered.\n\n` + + `Ways to fix this:\n` + + ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` + + ` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (does not apply to \`connection()\`)\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#cache-the-metadata\n` + +- ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#mark-the-route-as-dynamic` ++ ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`\` on the page\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime` + ) + } + +diff --git a/packages/next/src/server/app-render/sync-io-messages.ts b/packages/next/src/server/app-render/sync-io-messages.ts +index d65037c58d..b41ef8e909 100644 +--- a/packages/next/src/server/app-render/sync-io-messages.ts ++++ b/packages/next/src/server/app-render/sync-io-messages.ts +@@ -18,18 +18,12 @@ const SYNC_IO_RUNTIME_DOCS: Record = { + crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto', + } + +-function elapsedTimeBullet(type: SyncIOApiType, docsUrl: string): string { ++function elapsedTimeBullet(type: SyncIOApiType): string { + return type === 'time' +- ? `\n - [measure] If the value is for telemetry, use a timing API such as \`performance.now()\`\n ${docsUrl}#for-telemetry-use-a-timing-api` ++ ? `\n - [measure] If the value is for telemetry, use a timing API such as \`performance.now()\`` + : '' + } + +-const CACHE_ANCHOR: Record = { +- random: '#cache-the-random-value', +- time: '#cache-the-timestamp', +- crypto: '#cache-the-generated-value', +-} +- + function createSyncIOErrorImpl( + route: string, + expression: string, +@@ -40,10 +34,11 @@ function createSyncIOErrorImpl( + `Route "${route}": Next.js encountered the unstable value ${expression} while prerendering.\n\n` + + `This value can change between renders, so it must be either prerendered or computed later.\n\n` + + `Ways to fix this:\n` + +- ` - [dynamic] Render at request time by adding a dynamic data access (e.g. \`await connection()\`) before this call\n ${docsUrl}#generate-on-every-request\n` + +- ` - [cache] Prerender and cache the value with \`"use cache"\`\n ${docsUrl}${CACHE_ANCHOR[type]}\n` + +- ` - [client] Render the value on the client with \`"use client"\`\n ${docsUrl}#render-on-the-client` + +- elapsedTimeBullet(type, docsUrl) ++ ` - [dynamic] Render at request time by adding a dynamic data access (e.g. \`await connection()\`) before this call\n` + ++ ` - [cache] Prerender and cache the value with \`"use cache"\`\n` + ++ ` - [client] Render the value on the client with \`"use client"\`` + ++ elapsedTimeBullet(type) + ++ `\n\nLearn more: ${docsUrl}` + ) + } + +@@ -78,8 +73,9 @@ export function createSyncIOClientError( + `Route "${route}": Next.js encountered the unstable value ${expression} in a Client Component.\n\n` + + `This value would be evaluated during the prerender, instead of recomputed on each visit.\n\n` + + `Ways to fix this:\n` + +- ` - [stream] Wrap the Client Component in \`\`\n ${docsUrl}#wrap-in-or-move-into-suspense\n` + +- ` - [defer] Move the read into a \`useEffect\` or event handler\n ${docsUrl}#move-into-effect-or-event-handler` + +- elapsedTimeBullet(type, docsUrl) ++ ` - [stream] Wrap the Client Component in \`\`\n` + ++ ` - [defer] Move the read into a \`useEffect\` or event handler` + ++ elapsedTimeBullet(type) + ++ `\n\nLearn more: ${docsUrl}` + ) + } +diff --git a/packages/next/src/server/dynamic-rendering-utils.ts b/packages/next/src/server/dynamic-rendering-utils.ts +index 4158512e7f..91dcb37339 100644 +--- a/packages/next/src/server/dynamic-rendering-utils.ts ++++ b/packages/next/src/server/dynamic-rendering-utils.ts +@@ -42,9 +42,8 @@ export class ClientHookDynamicError extends Error { + `This blocks prerendering because the value is only available at runtime.\n\n` + + `Ways to fix this:\n` + + ` - [stream] Wrap the component in \`\` so the hook value streams in after prerendering\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-client-hook#wrap-in-or-move-into-suspense\n` + +- ` - [block] Set \`export const instant = false\` to allow a blocking route\n` + +- ` https://nextjs.org/docs/messages/blocking-prerender-client-hook#allow-blocking-route` ++ ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook` + ) + } + } +diff --git a/packages/next/src/shared/lib/instant-messages.ts b/packages/next/src/shared/lib/instant-messages.ts +index b53b6a41ac..ce620c8738 100644 +--- a/packages/next/src/shared/lib/instant-messages.ts ++++ b/packages/next/src/shared/lib/instant-messages.ts +@@ -11,9 +11,8 @@ export function createUnrenderedSegmentError( + `\n\n${label}:\n${missingFiles.map((p) => ` ${p}`).join('\n')}` + + `\n\nWays to fix this:` + + `\n - [render] Render the dropped segment` + +- `\n https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment` + + `\n - [ignore] Set \`export const instant = false\` to opt the dropped segment out of instant-navigation validation` + +- `\n https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment` ++ `\n\nLearn more: https://nextjs.org/docs/messages/instant-unrendered-segment` + } + return new Error(message) + } +@@ -24,10 +23,8 @@ export function createLinkPrefetchPartialError(pathname: string): Error { + `This will lead to slower, more expensive prefetches.\n\n` + + `Ways to fix this:\n` + + ` - [upgrade] Opt into Partial Prefetching by exporting \`const prefetch = 'partial'\` from the page or layout, or by setting \`partialPrefetching: true\` in next.config to opt the whole app in\n` + +- ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#opt-into-partial-prefetching\n` + + ` - [disable] Remove \`prefetch={true}\` from the to use the default prefetch\n` + +- ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#use-the-default-prefetch\n` + +- ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n` + +- ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#disable-validation-on-this-route` ++ ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n\n` + ++ `Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial` + ) + } diff --git a/nextjs-95967-single-learn-more-links/solution/solve.sh b/nextjs-95967-single-learn-more-links/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-95967-single-learn-more-links/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-95967-single-learn-more-links/tests/Dockerfile b/nextjs-95967-single-learn-more-links/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..80cb80920a7fe03f31f0c54cff60488cefbcf8c0 --- /dev/null +++ b/nextjs-95967-single-learn-more-links/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm build --filter=next' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-95967-single-learn-more-links/tests/test.patch b/nextjs-95967-single-learn-more-links/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..ca5cccff46f6496a39cd46f9ad76c0e62d0c9aa5 --- /dev/null +++ b/nextjs-95967-single-learn-more-links/tests/test.patch @@ -0,0 +1,276 @@ +diff --git a/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts b/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts +new file mode 100644 +index 00000000..5b889dba +--- /dev/null ++++ b/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts +@@ -0,0 +1,270 @@ ++import { ++ createDynamicBodyError, ++ createDynamicBodyErrorInNavigation, ++ createDynamicMetadataError, ++ createDynamicOrRuntimeBodyError, ++ createDynamicOrRuntimeMetadataError, ++ createDynamicOrRuntimeViewportError, ++ createDynamicViewportError, ++ createLinkBodyErrorInNavigation, ++ createLinkMetadataError, ++ createLinkViewportError, ++ createRuntimeBodyError, ++ createRuntimeBodyErrorInNavigation, ++ createRuntimeMetadataError, ++ createRuntimeViewportError, ++} from '../../../server/app-render/blocking-route-messages' ++import { ++ createSyncIOClientError, ++ createSyncIOError, ++ createSyncIORuntimeError, ++ type SyncIOApiType, ++} from '../../../server/app-render/sync-io-messages' ++import { ClientHookDynamicError } from '../../../server/dynamic-rendering-utils' ++import { ++ createLinkPrefetchPartialError, ++ createUnrenderedSegmentError, ++} from '../../../shared/lib/instant-messages' ++import { getCards } from '../components/instant/instant-guidance-data' ++import { getBlockingRouteErrorDetails } from './errors' ++ ++const ROUTE = '/insight-test' ++ ++type MessageCase = { ++ name: string ++ error: () => Error ++ docs: string | string[] ++ labels: string[] ++ context?: string[] ++} ++ ++function expectSingleLearnMoreLink({ ++ error, ++ docs, ++ labels, ++ context = [ROUTE], ++}: MessageCase): void { ++ const message = error().message ++ const urls = message.match(/https:\/\/[^\s]+/g) ?? [] ++ const allowedDocs = Array.isArray(docs) ? docs : [docs] ++ const renderedLabels = Array.from( ++ message.matchAll(/^\s*-\s*\[([a-z]+)\]/gm), ++ (match) => match[1] ++ ) ++ const learnMoreLines = Array.from( ++ message.matchAll(/^Learn more: (https:\/\/[^\s]+)$/gm), ++ (match) => match[1] ++ ) ++ ++ expect(renderedLabels).toEqual(labels) ++ expect(learnMoreLines).toHaveLength(1) ++ expect(allowedDocs).toContain(learnMoreLines[0]) ++ expect(urls).toEqual(learnMoreLines) ++ expect(learnMoreLines[0]).not.toContain('#') ++ expect(message).toMatch(/\n\nLearn more: https:\/\/[^\s]+\n?$/) ++ for (const value of context) { ++ expect(message).toContain(value) ++ } ++} ++ ++const blockingRouteCases: MessageCase[] = [ ++ { ++ name: 'runtime body', ++ error: () => createRuntimeBodyError(ROUTE), ++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-runtime', ++ labels: ['stream', 'block'], ++ }, ++ { ++ name: 'dynamic body', ++ error: () => createDynamicBodyError(ROUTE), ++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic', ++ labels: ['stream', 'cache', 'block'], ++ }, ++ { ++ name: 'runtime body during navigation', ++ error: () => createRuntimeBodyErrorInNavigation(ROUTE), ++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-runtime', ++ labels: ['stream', 'block'], ++ }, ++ { ++ name: 'URL body during navigation', ++ error: () => createLinkBodyErrorInNavigation(ROUTE), ++ docs: 'https://nextjs.org/docs/messages/instant-shell-url-data', ++ labels: ['stream', 'block'], ++ }, ++ { ++ name: 'dynamic body during navigation', ++ error: () => createDynamicBodyErrorInNavigation(ROUTE), ++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic', ++ labels: ['stream', 'cache', 'block'], ++ }, ++ { ++ name: 'combined dynamic and runtime body', ++ error: () => createDynamicOrRuntimeBodyError(ROUTE), ++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic', ++ labels: ['stream', 'cache', 'block'], ++ }, ++ { ++ name: 'URL metadata', ++ error: () => createLinkMetadataError(ROUTE), ++ docs: ++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime', ++ labels: ['static', 'dynamic'], ++ }, ++ { ++ name: 'runtime metadata', ++ error: () => createRuntimeMetadataError(ROUTE), ++ docs: ++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime', ++ labels: ['static', 'dynamic'], ++ }, ++ { ++ name: 'dynamic metadata', ++ error: () => createDynamicMetadataError(ROUTE), ++ docs: ++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic', ++ labels: ['cache', 'dynamic'], ++ }, ++ { ++ name: 'combined dynamic and runtime metadata', ++ error: () => createDynamicOrRuntimeMetadataError(ROUTE), ++ docs: [ ++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime', ++ 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic', ++ ], ++ labels: ['static', 'cache', 'dynamic'], ++ }, ++ { ++ name: 'URL viewport', ++ error: () => createLinkViewportError(ROUTE), ++ docs: ++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime', ++ labels: ['static', 'block'], ++ }, ++ { ++ name: 'runtime viewport', ++ error: () => createRuntimeViewportError(ROUTE), ++ docs: ++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime', ++ labels: ['static', 'block'], ++ }, ++ { ++ name: 'dynamic viewport', ++ error: () => createDynamicViewportError(ROUTE), ++ docs: ++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic', ++ labels: ['cache', 'block'], ++ }, ++ { ++ name: 'combined dynamic and runtime viewport', ++ error: () => createDynamicOrRuntimeViewportError(ROUTE), ++ docs: [ ++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime', ++ 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic', ++ ], ++ labels: ['static', 'cache', 'block'], ++ }, ++] ++ ++const syncIoTypes: SyncIOApiType[] = ['time', 'random', 'crypto'] ++const syncIoDocs: Record = { ++ time: 'https://nextjs.org/docs/messages/blocking-prerender-current-time', ++ random: 'https://nextjs.org/docs/messages/blocking-prerender-random', ++ crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto', ++} ++ ++const syncIoCases: MessageCase[] = syncIoTypes.flatMap((type) => { ++ const measure = type === 'time' ? ['measure'] : [] ++ return [ ++ { ++ name: `${type} prerender`, ++ error: () => createSyncIOError(ROUTE, `${type}()`, type), ++ docs: syncIoDocs[type], ++ labels: ['dynamic', 'cache', 'client', ...measure], ++ context: [ROUTE, `${type}()`], ++ }, ++ { ++ name: `${type} runtime prerender`, ++ error: () => createSyncIORuntimeError(ROUTE, `${type}()`, type), ++ docs: syncIoDocs[type], ++ labels: ['dynamic', 'cache', 'client', ...measure], ++ context: [ROUTE, `${type}()`], ++ }, ++ { ++ name: `${type} client component`, ++ error: () => createSyncIOClientError(ROUTE, `${type}()`, type), ++ docs: `${syncIoDocs[type]}-client`, ++ labels: ['stream', 'defer', ...measure], ++ context: [ROUTE, `${type}()`], ++ }, ++ ] ++}) ++ ++const instantCases: MessageCase[] = [ ++ { ++ name: 'client hook', ++ error: () => new ClientHookDynamicError(ROUTE, 'useSearchParams()'), ++ docs: 'https://nextjs.org/docs/messages/blocking-prerender-client-hook', ++ labels: ['stream', 'block'], ++ context: [ROUTE, 'useSearchParams()'], ++ }, ++ { ++ name: 'unrendered segment', ++ error: () => ++ createUnrenderedSegmentError(ROUTE, [ ++ 'app/@modal/default.tsx', ++ 'app/@sidebar/default.tsx', ++ ]), ++ docs: 'https://nextjs.org/docs/messages/instant-unrendered-segment', ++ labels: ['render', 'ignore'], ++ context: [ ++ ROUTE, ++ 'app/@modal/default.tsx', ++ 'app/@sidebar/default.tsx', ++ ], ++ }, ++ { ++ name: 'partial link prefetch', ++ error: () => createLinkPrefetchPartialError(ROUTE), ++ docs: 'https://nextjs.org/docs/messages/instant-link-prefetch-partial', ++ labels: ['upgrade', 'disable', 'ignore'], ++ }, ++] ++ ++describe('insight console guidance', () => { ++ it.each([...blockingRouteCases, ...syncIoCases, ...instantCases])( ++ '$name has one anchor-less Learn more link after its labeled fixes', ++ expectSingleLearnMoreLink ++ ) ++ ++ it.each(blockingRouteCases)( ++ '$name remains recognizable by the development overlay', ++ ({ error }) => { ++ expect(getBlockingRouteErrorDetails(error())).not.toBeNull() ++ } ++ ) ++ ++ it('preserves the unrendered-segment input list', () => { ++ const message = createUnrenderedSegmentError(ROUTE, [ ++ 'app/@modal/default.tsx', ++ 'app/@sidebar/default.tsx', ++ ]).message ++ expect(message).toContain('app/@modal/default.tsx') ++ expect(message).toContain('app/@sidebar/default.tsx') ++ }) ++ ++ it('keeps per-fix links on development-overlay cards', () => { ++ for (const [kind, variant] of [ ++ ['blocking-route', 'dynamic'], ++ ['metadata', 'runtime'], ++ ['viewport', 'dynamic'], ++ ['link-prefetch-partial', 'runtime'], ++ ] as const) { ++ const cards = getCards(kind, variant) ++ expect(cards.length).toBeGreaterThan(1) ++ for (const card of cards) { ++ expect(card.link).toMatch(/^https:\/\/nextjs\.org\/docs\/messages\/[^#]+#.+/) ++ } ++ } ++ }) ++}) diff --git a/nextjs-95967-single-learn-more-links/tests/test.sh b/nextjs-95967-single-learn-more-links/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7472b76223341cfcd0142e3dfce6f4142572b7a --- /dev/null +++ b/nextjs-95967-single-learn-more-links/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts' --exclude='packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/errors.test.ts'"'"' '"'"'packages/next/src/shared/lib/deep-freeze.test.ts'"'"''; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json <() +@@ -1495,6 +1503,16 @@ export async function createHotReloaderTurbopack( + } + }, + ++ getServerComponentsHmrRefreshHash() { ++ // The current server-components generation. Only the change subscription ++ // (an actual recompile) advances `hmrHash`; reloads and config ++ // invalidations don't, so the value stays stable across requests until a ++ // real edit. Returned unconditionally (`"0"` before the first edit) so ++ // `"use cache"` keys are present and consistent for every request, ++ // mirroring webpack's always-present `stats.hash`. ++ return String(hmrHash) ++ }, ++ + sendToLegacyClients(action) { + const payload = JSON.stringify(action) + +@@ -1641,7 +1659,6 @@ export async function createHotReloaderTurbopack( + await clearAllModuleContexts() + this.send({ + type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES, +- hash: String(++hmrHash), + }) + } + }, +@@ -1922,7 +1939,10 @@ export async function createHotReloaderTurbopack( + + sendToClient(client, { + type: HMR_MESSAGE_SENT_TO_BROWSER.BUILT, +- hash: String(++hmrHash), ++ // Report the current version without advancing it: a completed ++ // compilation is not itself an edit, and this hash is not ++ // consumed by the Turbopack client. ++ hash: String(hmrHash), + errors: [...clientErrors.values()], + warnings: [], + }) +@@ -1981,7 +2001,6 @@ export async function createHotReloaderTurbopack( + // Tell browsers to refetch RSC (soft refresh, not full page reload) + hotReloader.send({ + type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES, +- hash: String(++hmrHash), + }) + }, + }) +diff --git a/packages/next/src/server/dev/hot-reloader-types.ts b/packages/next/src/server/dev/hot-reloader-types.ts +index 04334c6f49..2e2855605d 100644 +--- a/packages/next/src/server/dev/hot-reloader-types.ts ++++ b/packages/next/src/server/dev/hot-reloader-types.ts +@@ -117,7 +117,6 @@ export interface ReloadPageMessage { + + export interface ServerComponentChangesMessage { + type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES +- hash: string + } + + /** +@@ -259,6 +258,13 @@ export interface NextJsHotReloaderInterface { + * and App Router clients that don't have Cache Components enabled. + */ + sendToLegacyClients(action: HmrMessageSentToBrowser): void ++ /** ++ * The hash of the most recent server component change, or `undefined` if no ++ * server component change has occurred yet. In dev, this is included in `"use ++ * cache"` cache keys so that cached entries are revalidated after an edit, ++ * for every client, regardless of whether it runs the HMR client. ++ */ ++ getServerComponentsHmrRefreshHash(): string | undefined + setCacheStatus(status: ServerCacheStatus, htmlRequestId: string): void + setReactDebugChannel( + debugChannel: ReactDebugChannelForBrowser, +diff --git a/packages/next/src/server/dev/hot-reloader-webpack.ts b/packages/next/src/server/dev/hot-reloader-webpack.ts +index 063ebe195a..3f687776c7 100644 +--- a/packages/next/src/server/dev/hot-reloader-webpack.ts ++++ b/packages/next/src/server/dev/hot-reloader-webpack.ts +@@ -241,6 +241,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { + private serverError: Error | null = null + private hmrServerError: Error | null = null + private serverPrevDocumentHash: string | null ++ private serverComponentsHmrRefreshHash: string | undefined + private serverChunkNames?: Set + private prevChunkNames?: Set + private onDemandEntries?: ReturnType +@@ -431,14 +432,18 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { + } + + protected async refreshServerComponents(hash: string): Promise { ++ this.serverComponentsHmrRefreshHash = hash + this.send({ + type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES, +- hash, + // TODO: granular reloading of changes + // entrypoints: serverComponentChanges, + }) + } + ++ public getServerComponentsHmrRefreshHash(): string | undefined { ++ return this.serverComponentsHmrRefreshHash ++ } ++ + public onHMR( + req: IncomingMessage, + _socket: Duplex, +diff --git a/packages/next/src/server/dev/next-dev-server.ts b/packages/next/src/server/dev/next-dev-server.ts +index 5f40da7ef9..54fa3aaf96 100644 +--- a/packages/next/src/server/dev/next-dev-server.ts ++++ b/packages/next/src/server/dev/next-dev-server.ts +@@ -231,6 +231,10 @@ export default class DevServer extends Server { + return this.serverComponentsHmrCache + } + ++ protected override getServerComponentsHmrRefreshHash(): string | undefined { ++ return this.bundlerService.getServerComponentsHmrRefreshHash() ++ } ++ + protected getRouteMatchers(): RouteMatcherManager { + const { pagesDir, appDir } = findPagesDir(this.dir) + +diff --git a/packages/next/src/server/dev/turbopack-utils.ts b/packages/next/src/server/dev/turbopack-utils.ts +index 25155df83f..7aa2900da5 100644 +--- a/packages/next/src/server/dev/turbopack-utils.ts ++++ b/packages/next/src/server/dev/turbopack-utils.ts +@@ -408,6 +408,34 @@ export async function handleRouteType({ + const writtenEndpoint = await route.endpoint.writeToDisk() + hooks?.handleWrittenEndpoint(key, writtenEndpoint, false) + ++ if (dev) { ++ // Advance the hot-reloader's HMR refresh hash whenever this route ++ // handler is recompiled, so its `"use cache"` entries are invalidated ++ // after an edit. Subscribing runs `subscribeToClientChanges`, which ++ // bumps the `hmrHash` counter on each change; that counter is returned ++ // by `getServerComponentsHmrRefreshHash` and folded into cache keys by ++ // `getHmrRefreshHash`. Unlike app pages there is no RSC for a connected ++ // browser to refetch, so `createMessage` returns nothing; the ++ // subscription exists only to advance the hash. ++ hooks?.subscribeToChanges( ++ key, ++ /** includeIssues= */ true, ++ route.endpoint, ++ () => undefined, ++ (error) => { ++ // This subscription only advances the refresh hash, so there is ++ // nothing to send the browser when it fails. `subscribeToChanges` ++ // drops the subscription on error and re-creates it the next time ++ // this route is ensured, so just log it. ++ console.error( ++ new Error(`Error in the "${page}" app-route HMR subscription`, { ++ cause: error, ++ }) ++ ) ++ } ++ ) ++ } ++ + const type = writtenEndpoint.type + + manifestLoader.loadAppPathsManifest(page) +diff --git a/packages/next/src/server/dev/use-cache-probe-worker.ts b/packages/next/src/server/dev/use-cache-probe-worker.ts +index c77c7c8901..a29a26bcb4 100644 +--- a/packages/next/src/server/dev/use-cache-probe-worker.ts ++++ b/packages/next/src/server/dev/use-cache-probe-worker.ts +@@ -167,6 +167,7 @@ export async function probeUseCache(msg: ProbeMessage): Promise { + previewProps: undefined, + isHmrRefresh: msg.request.isHmrRefresh, + serverComponentsHmrCache: undefined, ++ hmrRefreshHash: msg.request.hmrRefreshHash, + fallbackParams: null, + }) + +diff --git a/packages/next/src/server/lib/dev-bundler-service.ts b/packages/next/src/server/lib/dev-bundler-service.ts +index c1e963d0f6..f284e79b12 100644 +--- a/packages/next/src/server/lib/dev-bundler-service.ts ++++ b/packages/next/src/server/lib/dev-bundler-service.ts +@@ -64,6 +64,10 @@ export class DevBundlerService { + return await this.bundler.hotReloader.ensurePage(definition) + } + ++ public getServerComponentsHmrRefreshHash(): string | undefined { ++ return this.bundler.hotReloader.getServerComponentsHmrRefreshHash() ++ } ++ + public logErrorWithOriginalStack = + this.bundler.logErrorWithOriginalStack.bind(this.bundler) + +diff --git a/packages/next/src/server/request-meta.ts b/packages/next/src/server/request-meta.ts +index db02b9abdd..0521765ea2 100644 +--- a/packages/next/src/server/request-meta.ts ++++ b/packages/next/src/server/request-meta.ts +@@ -114,6 +114,14 @@ export interface RequestMeta { + */ + serverComponentsHmrCache?: ServerComponentsHmrCache + ++ /** ++ * The hash of the most recent server component change (dev only), set by the ++ * router-server from the hot-reloader. Included in `"use cache"` cache keys ++ * so that cached entries are revalidated after an edit, for every client, ++ * regardless of whether it runs the HMR client. ++ */ ++ hmrRefreshHash?: string ++ + /** + * Equals the segment path that was used for the prefetch RSC request. + */ +diff --git a/packages/next/src/server/route-modules/app-route/module.ts b/packages/next/src/server/route-modules/app-route/module.ts +index d87306003e..5bcc998eac 100644 +--- a/packages/next/src/server/route-modules/app-route/module.ts ++++ b/packages/next/src/server/route-modules/app-route/module.ts +@@ -805,7 +805,8 @@ export class AppRouteRouteModule extends RouteModule< + req.nextUrl, + implicitTags, + undefined, +- context.previewProps ++ context.previewProps, ++ context.renderOpts.hmrRefreshHash + ) + + const workStore = createWorkStore(staticGenerationContext) +diff --git a/packages/next/src/server/use-cache/use-cache-probe-globals.ts b/packages/next/src/server/use-cache/use-cache-probe-globals.ts +index 272e71d1a7..1f3b3a5f30 100644 +--- a/packages/next/src/server/use-cache/use-cache-probe-globals.ts ++++ b/packages/next/src/server/use-cache/use-cache-probe-globals.ts +@@ -24,6 +24,7 @@ export type UseCacheProbeRequestSnapshot = { + rootParams: Params + isDraftMode: boolean + isHmrRefresh: boolean ++ hmrRefreshHash: string | undefined + } + + /** +diff --git a/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts b/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts +index f8733b7e8f..dbed303bda 100644 +--- a/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts ++++ b/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts +@@ -115,6 +115,7 @@ export function setupProbeScheduler( + rootParams: outerRequestStore.rootParams ?? {}, + isDraftMode: workStore.isDraftMode ?? false, + isHmrRefresh: outerRequestStore.isHmrRefresh ?? false, ++ hmrRefreshHash: outerRequestStore.hmrRefreshHash, + }, + timeoutMs: probeInternalTimeoutMs, + }).then( +diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts +index 2bebc96297..f549de8b8d 100644 +--- a/packages/next/src/server/use-cache/use-cache-wrapper.ts ++++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts +@@ -74,10 +74,7 @@ import { + } from './handlers' + import type { CacheReadWriteHandler } from './tiered-cache-handler' + import { cloneCacheEntry } from './clone-cache-entry' +-import { +- NEXT_HMR_REFRESH_HASH_COOKIE, +- NEXT_INSTANT_TEST_COOKIE, +-} from '../../client/components/app-router-headers' ++import { NEXT_INSTANT_TEST_COOKIE } from '../../client/components/app-router-headers' + import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies' + import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers' + import { +@@ -366,10 +363,8 @@ function computeRootParamsCacheKeySuffix( + // Next-internal cookies that must not vary the private cache key, since they're + // not part of the application's own cookie state. The instant-navigation cookie + // toggles while a navigation lock is held, so including it would force spurious +-// misses. The HMR refresh hash is already part of the cache key (see +-// `cacheKeyParts`), so including its cookie too would just be redundant. ++// misses. + const COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY = new Set([ +- NEXT_HMR_REFRESH_HASH_COOKIE, + NEXT_INSTANT_TEST_COOKIE, + ]) + +diff --git a/packages/next/src/server/web/adapter.ts b/packages/next/src/server/web/adapter.ts +index 38c960b804..c9c2a43ac3 100644 +--- a/packages/next/src/server/web/adapter.ts ++++ b/packages/next/src/server/web/adapter.ts +@@ -313,7 +313,10 @@ export async function adapter( + request.nextUrl, + implicitTags, + onUpdateCookies, +- previewProps ++ previewProps, ++ // Edge route handlers can't use `"use cache"`, so there's no HMR ++ // refresh hash to thread through here. ++ undefined + ) + + const workStore = createWorkStore({ diff --git a/nextjs-96022-dev-use-cache-invalidation/solution/solve.sh b/nextjs-96022-dev-use-cache-invalidation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-96022-dev-use-cache-invalidation/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile b/nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6d305bb8a8c16799736860e2145f46dc5aa67c7d --- /dev/null +++ b/nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && corepack install --global pnpm@10.33.0 && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && TURBO_TASKS_AVAILABLE_PARALLELISM=4 ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium && chmod -R a+rwX packages/next' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-96022-dev-use-cache-invalidation/tests/test.patch b/nextjs-96022-dev-use-cache-invalidation/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..5cd68d81b3465790cd1bebd9f6f6349416446a47 --- /dev/null +++ b/nextjs-96022-dev-use-cache-invalidation/tests/test.patch @@ -0,0 +1,61 @@ +diff --git a/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts b/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts +index da4e0a22..ca835118 100644 +--- a/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts ++++ b/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts +@@ -108,15 +108,11 @@ describe('use-cache-dev', () => { + ) + }) + +- // These two currently fail in both Turbopack and Webpack. Dev "use cache" +- // invalidation relies on the __next_hmr_refresh_hash__ cookie that the +- // browser HMR client sets after an edit; a client that fetches directly +- // (curl, a plain fetch, a second device) never sends that cookie, so the +- // "use cache" key does not change across the edit and the stale entry is +- // reused. Change these to `it` once editing a file invalidates cached data +- // for requests that do not carry the cookie, covering both route handlers +- // and pages. +- it.failing( ++ // Regression coverage for requesters that don't run the browser HMR client. ++ // A direct requester never receives browser-authored refresh state, but it ++ // must still observe a new cache generation after the server recompiles an ++ // edited page or route handler. ++ it( + 'should update cached data used by a route handler after editing a file', + async () => { + const initialData = await next +@@ -160,10 +156,20 @@ describe('use-cache-dev', () => { + // random value due to a cache miss. + expect(newData.text).toBe('bar') + expect(newData.mathRandom).not.toBe(initialData.mathRandom) ++ ++ // Once the edited module has compiled, ordinary warm requests should ++ // keep reusing its new cache entry rather than advancing the cache key ++ // for development bookkeeping. ++ const warmData = await next ++ .fetch('/api/cached') ++ .then((res) => res.json()) ++ ++ expect(warmData.text).toBe('bar') ++ expect(warmData.mathRandom).toBe(newData.mathRandom) + } + ) + +- it.failing( ++ it( + 'should update cached data used by a page fetched without a cookie after editing a file', + async () => { + // `next.render$` fetches directly, without the browser HMR client, so +@@ -202,6 +208,13 @@ describe('use-cache-dev', () => { + // random value due to a cache miss. + expect($('#text').text()).toBe('bar') + expect($('#mathRandom').text()).not.toBe(initialMathRandom) ++ ++ // The post-edit value should remain cached on another direct request. ++ const editedMathRandom = $('#mathRandom').text() ++ $ = await next.render$('/cached-page') ++ ++ expect($('#text').text()).toBe('bar') ++ expect($('#mathRandom').text()).toBe(editedMathRandom) + } + ) + diff --git a/nextjs-96022-dev-use-cache-invalidation/tests/test.sh b/nextjs-96022-dev-use-cache-invalidation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c70725d2197d041ac085ab0a750d72db306c3a43 --- /dev/null +++ b/nextjs-96022-dev-use-cache-invalidation/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' --exclude='test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'git diff --name-only -z -- packages/next | while IFS= read -r -d '"'"''"'"' file; do if [ -f "$file" ] && [ ! -w "$file" ]; then cp -- "$file" "$file.selfbench-tmp" && mv -- "$file.selfbench-tmp" "$file"; fi; done && TURBO_TASKS_AVAILABLE_PARALLELISM=4 pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'git diff --name-only -z -- packages/next | while IFS= read -r -d '"'"''"'"' file; do if [ -f "$file" ] && [ ! -w "$file" ]; then cp -- "$file" "$file.selfbench-tmp" && mv -- "$file.selfbench-tmp" "$file"; fi; done && TURBO_TASKS_AVAILABLE_PARALLELISM=4 pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'git diff --name-only -z -- packages/next | while IFS= read -r -d '"'"''"'"' file; do if [ -f "$file" ] && [ ! -w "$file" ]; then cp -- "$file" "$file.selfbench-tmp" && mv -- "$file.selfbench-tmp" "$file"; fi; done && TURBO_TASKS_AVAILABLE_PARALLELISM=4 pnpm build && pnpm test-dev-turbo '"'"'test/development/app-dir/basic/basic.test.ts'"'"' '"'"'test/development/app-dir/multiple-compiles-single-route/multiple-compiles-single-route.test.ts'"'"''; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json <( + maxSize, +- (entry) => entry.size ++ (entry, cacheKey) => entry.size + cacheKey.length + ) + const pendingSets = new Map>() + +diff --git a/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts b/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts +index e446656409..d9f66ba850 100644 +--- a/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts ++++ b/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts +@@ -24,30 +24,37 @@ function getSegmentDataSize(segmentData: Map | undefined) { + + export function getMemoryCache(maxMemoryCacheSize: number) { + if (!memoryCache) { +- memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }) { ++ memoryCache = new LRUCache(maxMemoryCacheSize, function length( ++ { value }, ++ cacheKey ++ ) { ++ let valueSize: number ++ + if (!value) { +- return 25 ++ valueSize = 25 + } else if (value.kind === CachedRouteKind.REDIRECT) { +- return JSON.stringify(value.props).length ++ valueSize = JSON.stringify(value.props).length + } else if (value.kind === CachedRouteKind.IMAGE) { + throw new Error('invariant image should not be incremental-cache') + } else if (value.kind === CachedRouteKind.FETCH) { +- return JSON.stringify(value.data || '').length ++ valueSize = JSON.stringify(value.data || '').length + } else if (value.kind === CachedRouteKind.APP_ROUTE) { +- return value.body.length +- } +- // rough estimate of size of cache value +- if (value.kind === CachedRouteKind.APP_PAGE) { +- return Math.max( ++ valueSize = value.body.length ++ } else if (value.kind === CachedRouteKind.APP_PAGE) { ++ // rough estimate of size of cache value ++ valueSize = Math.max( + 1, + value.html.length + + getBufferSize(value.rscData) + + (value.postponed?.length || 0) + + getSegmentDataSize(value.segmentData) + ) ++ } else { ++ valueSize = ++ value.html.length + (JSON.stringify(value.pageData)?.length || 0) + } + +- return value.html.length + (JSON.stringify(value.pageData)?.length || 0) ++ return cacheKey.length + valueSize + }) + } + +diff --git a/packages/next/src/server/lib/source-maps.ts b/packages/next/src/server/lib/source-maps.ts +index af2969c03e..654de4126e 100644 +--- a/packages/next/src/server/lib/source-maps.ts ++++ b/packages/next/src/server/lib/source-maps.ts +@@ -215,13 +215,13 @@ function bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null { + const invalidSourceMap = Symbol('invalid-source-map') + const sourceMapURLs = new LRUCache( + 512 * 1024 * 1024, +- (url) => +- url === invalidSourceMap +- ? // Ideally we'd account for key length. So we just guestimate a small source map +- // so that we don't create a huge cache with empty source maps. ++ (url, sourceURL) => ++ sourceURL.length + ++ (url === invalidSourceMap ++ ? // Guestimate a small source map so invalid entries don't fill the cache. + 8 * 1024 + : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength +- url.length ++ url.length) + ) + export function findSourceMapURLDEV( + scriptNameOrSourceURL: string diff --git a/nextjs-byte-budgeted-lru-keys/solution/solve.sh b/nextjs-byte-budgeted-lru-keys/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-byte-budgeted-lru-keys/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-byte-budgeted-lru-keys/tests/Dockerfile b/nextjs-byte-budgeted-lru-keys/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6935ad83ca6c323529f66717ee83fc533edfb26d --- /dev/null +++ b/nextjs-byte-budgeted-lru-keys/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack prepare pnpm@10.33.0 --activate && mkdir -p .selfbench-bin && corepack enable --install-directory "$PWD/.selfbench-bin" && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 pnpm install --frozen-lockfile && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 ANALYZE=1 pnpm build' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-byte-budgeted-lru-keys/tests/test.patch b/nextjs-byte-budgeted-lru-keys/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..2806679886c4ac628927931483e3f928cbbdab18 --- /dev/null +++ b/nextjs-byte-budgeted-lru-keys/tests/test.patch @@ -0,0 +1,243 @@ +diff --git a/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts b/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts +new file mode 100644 +index 0000000000..4cb91c9136 +--- /dev/null ++++ b/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts +@@ -0,0 +1,237 @@ ++import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' ++import type { SourceMap } from 'module' ++import { tmpdir } from 'os' ++import { join } from 'path' ++import DevServer from 'next/dist/server/dev/next-dev-server' ++import { defaultConfig } from 'next/dist/server/config-shared' ++import type { CacheEntry } from './cache-handlers/types' ++import { createDefaultCacheHandler } from './cache-handlers/default' ++import { getMemoryCache } from './incremental-cache/memory-cache.external' ++ ++function cacheEntry(body: string): CacheEntry { ++ return { ++ value: new ReadableStream({ ++ start(controller) { ++ controller.enqueue(new TextEncoder().encode(body)) ++ controller.close() ++ }, ++ }), ++ tags: [], ++ stale: 60, ++ timestamp: Date.now(), ++ expire: 60, ++ revalidate: 60, ++ } ++} ++ ++class TestDevServer extends DevServer { ++ readStaticPaths(pathname: string) { ++ return this.getStaticPaths({ ++ pathname, ++ urlPathname: pathname, ++ requestHeaders: {}, ++ page: '/[slug]', ++ isAppPath: false, ++ }) ++ } ++ ++ hmrCache() { ++ return this.getServerComponentsHmrCache() ++ } ++} ++ ++describe('byte-budgeted server caches', () => { ++ it('charges incremental-cache keys against the memory budget', () => { ++ const cache = getMemoryCache(64) ++ const key = `/api/data?${'p'.repeat(80)}` ++ const warning = jest.spyOn(console, 'warn').mockImplementation() ++ ++ cache?.set(key, { ++ value: { kind: 'FETCH', data: { body: 'ok' } }, ++ lastModified: 1, ++ } as any) ++ ++ warning.mockRestore() ++ expect(cache?.get(key)).toBeUndefined() ++ }) ++ ++ it('charges use-cache keys against the default handler budget', async () => { ++ const handler = createDefaultCacheHandler(16) ++ const key = `cache-${'k'.repeat(32)}` ++ const warning = jest.spyOn(console, 'warn').mockImplementation() ++ ++ await handler.set(key, Promise.resolve(cacheEntry('x'))) ++ ++ warning.mockRestore() ++ expect(await handler.get(key, [])).toBeUndefined() ++ }) ++ ++ it('charges route keys against the development static paths budget', async () => { ++ const dir = mkdtempSync(join(tmpdir(), 'next-static-paths-cache-')) ++ mkdirSync(join(dir, 'pages')) ++ mkdirSync(join(dir, '.next', 'server', 'pages'), { recursive: true }) ++ writeFileSync( ++ join(dir, '.next', 'prerender-manifest.json'), ++ JSON.stringify({ ++ version: 4, ++ routes: {}, ++ dynamicRoutes: {}, ++ notFoundRoutes: [], ++ preview: { ++ previewModeId: 'a'.repeat(32), ++ previewModeSigningKey: 'b'.repeat(64), ++ previewModeEncryptionKey: 'c'.repeat(32), ++ }, ++ }) ++ ) ++ writeFileSync(join(dir, '.next', 'build-manifest.json'), '{}') ++ writeFileSync(join(dir, '.next', 'react-loadable-manifest.json'), '{}') ++ writeFileSync( ++ join(dir, '.next', 'server', 'pages-manifest.json'), ++ JSON.stringify({ ++ '/_document': 'pages/_document.js', ++ '/_app': 'pages/_app.js', ++ '/[slug]': 'pages/[slug].js', ++ }) ++ ) ++ writeFileSync( ++ join(dir, '.next', 'server', 'pages', '_document.js'), ++ 'module.exports={default:()=>null}' ++ ) ++ writeFileSync( ++ join(dir, '.next', 'server', 'pages', '_app.js'), ++ 'module.exports={default:()=>null}' ++ ) ++ const counter = join(dir, 'counter') ++ writeFileSync(counter, '0') ++ writeFileSync( ++ join(dir, '.next', 'server', 'pages', '[slug].js'), ++ `const fs=require('fs');const p=${JSON.stringify( ++ counter ++ )};module.exports={default:()=>null,getStaticProps:async()=>({props:{}}),getStaticPaths:async()=>{const n=+fs.readFileSync(p,'utf8')+1;fs.writeFileSync(p,String(n));return {paths:['/generated-'+n],fallback:false}}}` ++ ) ++ ++ try { ++ const server = new TestDevServer({ ++ dir, ++ conf: { ++ ...defaultConfig, ++ experimental: { ++ ...defaultConfig.experimental, ++ instantInsights: { validationLevel: 'warning' }, ++ useCacheTimeout: 50, ++ turbopackMemoryEvictionMode: 'auto', ++ }, ++ }, ++ bundlerService: { ++ getServerComponentsHmrRefreshHash: () => '', ++ sendHmrMessage: jest.fn(), ++ } as any, ++ startServerSpan: undefined as any, ++ }) ++ const parameterName = 'p'.repeat(3 * 1024 * 1024) ++ const first = `/[${parameterName}a]` ++ const second = `/[${parameterName}b]` ++ ++ await server.readStaticPaths(first) ++ await server.readStaticPaths(second) ++ const refreshed = await server.readStaticPaths(first) ++ ++ for (let i = 0; i < 100 && Number(readFileSync(counter)) < 3; i++) { ++ await new Promise((resolve) => setTimeout(resolve, 10)) ++ } ++ await new Promise((resolve) => setTimeout(resolve, 100)) ++ expect(refreshed.staticPaths).toEqual(['/generated-3']) ++ } finally { ++ rmSync(dir, { recursive: true, force: true }) ++ } ++ }) ++ ++ it('charges module keys against the development HMR cache budget', () => { ++ const dir = mkdtempSync(join(tmpdir(), 'next-dev-cache-')) ++ mkdirSync(join(dir, 'pages')) ++ mkdirSync(join(dir, '.next')) ++ writeFileSync( ++ join(dir, '.next', 'prerender-manifest.json'), ++ JSON.stringify({ ++ version: 4, ++ routes: {}, ++ dynamicRoutes: {}, ++ notFoundRoutes: [], ++ preview: { ++ previewModeId: 'a'.repeat(32), ++ previewModeSigningKey: 'b'.repeat(64), ++ previewModeEncryptionKey: 'c'.repeat(32), ++ }, ++ }) ++ ) ++ ++ try { ++ const server = new TestDevServer({ ++ dir, ++ conf: { ++ ...defaultConfig, ++ experimental: { ++ ...defaultConfig.experimental, ++ serverComponentsHmrCache: true, ++ instantInsights: { validationLevel: 'warning' }, ++ useCacheTimeout: 50, ++ turbopackMemoryEvictionMode: 'auto', ++ }, ++ }, ++ bundlerService: { ++ getServerComponentsHmrRefreshHash: () => '', ++ sendHmrMessage: jest.fn(), ++ } as any, ++ startServerSpan: undefined as any, ++ }) ++ const cache = server.hmrCache() ++ const prefix = 'm'.repeat(30 * 1024 * 1024) ++ const first = `${prefix}-first` ++ const second = `${prefix}-second` ++ ++ cache!.set(first, ['first'] as any) ++ cache!.set(second, ['second'] as any) ++ ++ expect(cache!.get(first)).toBeUndefined() ++ expect(cache!.get(second)).toEqual(['second']) ++ } finally { ++ rmSync(dir, { recursive: true, force: true }) ++ } ++ }) ++ ++ it('eventually revisits old source-map misses when URL keys fill the budget', () => { ++ jest.resetModules() ++ const nodeModule = jest.requireActual('module') ++ const available = new Map() ++ const findSourceMap = jest ++ .spyOn(nodeModule, 'findSourceMap') ++ .mockImplementation((sourceURL) => available.get(sourceURL)) ++ ++ let sourceMaps!: typeof import('./source-maps') ++ jest.isolateModules(() => { ++ sourceMaps = require('./source-maps') ++ }) ++ ++ const original = 'server-entry.js' ++ expect(sourceMaps.findSourceMapURLDEV(original)).toBeNull() ++ ++ for (let i = 0; i < 65_535; i++) { ++ sourceMaps.findSourceMapURLDEV(`chunk-${i}-${'x'.repeat(96)}`) ++ } ++ ++ available.set(original, { ++ payload: { ++ version: 3, ++ file: original, ++ sources: ['server-entry.ts'], ++ names: [], ++ mappings: '', ++ }, ++ } as SourceMap) ++ ++ const refreshed = sourceMaps.findSourceMapURLDEV(original) ++ findSourceMap.mockRestore() ++ expect(refreshed).toMatch(/^data:application\/json;base64,/) ++ }) ++}) diff --git a/nextjs-byte-budgeted-lru-keys/tests/test.sh b/nextjs-byte-budgeted-lru-keys/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f335044a27bb894dec71c23e3f549b6d1b193cbe --- /dev/null +++ b/nextjs-byte-budgeted-lru-keys/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' --exclude='packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 ANALYZE=1 pnpm build && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 pnpm test '"'"'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 ANALYZE=1 pnpm build && PATH="$PWD/.selfbench-bin:$PATH" NEXT_TELEMETRY_DISABLED=1 pnpm test '"'"'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'true'; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json < ++ ({ ++ version: 4, ++ routes: {}, ++ dynamicRoutes: {}, ++ notFoundRoutes: [], ++ preview: { ++ previewModeId: 'id', ++ previewModeSigningKey: 'key', ++ previewModeEncryptionKey: 'key', ++ }, ++ }) as any, ++ }) ++} ++ ++describe('IncrementalCache.generateCacheKey', () => { ++ const cache = createCache() ++ const url = 'https://example.com/api' ++ ++ it('distinguishes binary bodies that UTF-8 decoding would collapse', async () => { ++ // 0xff and 0xfe both decode to U+FFFD as UTF-8; the key must tell them ++ // apart by their raw bytes. ++ const a = await cache.generateCacheKey(url, { ++ body: new Uint8Array([0xff]), ++ }) ++ const b = await cache.generateCacheKey(url, { ++ body: new Uint8Array([0xfe]), ++ }) ++ expect(a).not.toBe(b) ++ }) ++ ++ it('distinguishes a string body from its UTF-8 encoded bytes', async () => { ++ // A string and the bytes it encodes to are different request shapes. ++ const a = await cache.generateCacheKey(url, { body: 'hello' }) ++ const b = await cache.generateCacheKey(url, { ++ body: new TextEncoder().encode('hello'), ++ }) ++ expect(a).not.toBe(b) ++ }) ++ ++ it('uses the selected bytes of arbitrary ArrayBuffer views', async () => { ++ const backing = new Uint8Array([9, 1, 2, 3, 9]) ++ const dataView = new DataView(backing.buffer, 1, 3) ++ const typedView = new Uint8Array([1, 2, 3]) ++ ++ const a = await cache.generateCacheKey(url, { body: dataView }) ++ const b = await cache.generateCacheKey(url, { body: typedView }) ++ expect(a).toBe(b) ++ }) ++ ++ it('distinguishes URLSearchParams, FormData, and string bodies', async () => { ++ const form = new FormData() ++ form.append('x', 'a') ++ ++ const formKey = await cache.generateCacheKey(url, { body: form }) ++ const paramsKey = await cache.generateCacheKey(url, { ++ body: new URLSearchParams([['x', 'a']]), ++ }) ++ const stringKey = await cache.generateCacheKey(url, { body: 'x=a' }) ++ ++ expect(new Set([formKey, paramsKey, stringKey]).size).toBe(3) ++ }) ++ ++ it('distinguishes a Blob from its raw content bytes', async () => { ++ const bytes = new Uint8Array([1, 2, 3]) ++ const blobKey = await cache.generateCacheKey(url, { ++ body: new Blob([bytes]), ++ }) ++ const bytesKey = await cache.generateCacheKey(url, { body: bytes }) ++ ++ expect(blobKey).not.toBe(bytesKey) ++ }) ++ ++ it('is deterministic for identical bodies', async () => { ++ const a = await cache.generateCacheKey(url, { ++ body: new Uint8Array([1, 2, 3]), ++ }) ++ const b = await cache.generateCacheKey(url, { ++ body: new Uint8Array([1, 2, 3]), ++ }) ++ expect(a).toBe(b) ++ }) ++ ++ it('does not collide FormData multi-values with a comma-joined string', async () => { ++ // The two values ['a', 'b'] must not hash the same as the single 'a,b'. ++ const multi = new FormData() ++ multi.append('x', 'a') ++ multi.append('x', 'b') ++ ++ const joined = new FormData() ++ joined.append('x', 'a,b') ++ ++ const a = await cache.generateCacheKey(url, { body: multi }) ++ const b = await cache.generateCacheKey(url, { body: joined }) ++ expect(a).not.toBe(b) ++ }) ++ ++ it('distinguishes blobs that differ only by content type', async () => { ++ const bytes = new Uint8Array([1, 2, 3]) ++ const a = await cache.generateCacheKey(url, { ++ body: new Blob([bytes], { type: 'text/plain' }), ++ }) ++ const b = await cache.generateCacheKey(url, { ++ body: new Blob([bytes], { type: 'application/json' }), ++ }) ++ expect(a).not.toBe(b) ++ }) ++ ++ it('distinguishes ArrayBuffers', async () => { ++ const a = await cache.generateCacheKey(url, { ++ body: new Uint8Array([1, 2, 3, 4]).buffer, ++ }) ++ const b = await cache.generateCacheKey(url, { ++ body: new Uint8Array([1, 2, 3]).buffer, ++ }) ++ expect(a).not.toBe(b) ++ }) ++ ++ it('produces the same key for identical bytes in different typed arrays', async () => { ++ const uint8View = new Uint8Array([1, 2, 3, 4]) ++ const uint16View = new Uint16Array( ++ uint8View.buffer, ++ uint8View.byteOffset, ++ uint8View.byteLength / 2 ++ ) ++ const a = await cache.generateCacheKey(url, { ++ body: uint8View, ++ }) ++ const b = await cache.generateCacheKey(url, { ++ body: uint16View, ++ }) ++ expect(a).toBe(b) ++ }) ++ ++ it('does not collide FormData with differently interleaved values', async () => { ++ const a = new FormData() ++ a.append('x', 'a') ++ a.append('x', 'b') ++ a.append('y', 'a') ++ ++ const b = new FormData() ++ b.append('x', 'a') ++ b.append('y', 'a') ++ b.append('x', 'b') ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++ ++ it('does not collide FormData whose value forges quoted entry delimiters', async () => { ++ // User values may resemble framing text and must remain data. ++ const a = new FormData() ++ a.append('x', 'a"key:"y"str:"b') ++ ++ const b = new FormData() ++ b.append('x', 'a') ++ b.append('y', 'b') ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++ ++ it('does not collide FormData whose value spans an entry boundary', async () => { ++ // One value may contain text resembling a complete following entry. ++ const a = new FormData() ++ a.append('x', 'akey:ystr:b') ++ ++ const b = new FormData() ++ b.append('x', 'a') ++ b.append('y', 'b') ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++ ++ it('does not collide FormData files that differ only by name/type split', async () => { ++ // File name and content type are separate fetch-relevant metadata. ++ const bytes = new Uint8Array([1, 2, 3]) ++ ++ const a = new FormData() ++ a.append('f', new Blob([bytes], { type: 'c' }), 'ab') ++ ++ const b = new FormData() ++ b.append('f', new Blob([bytes], { type: 'bc' }), 'a') ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++ ++ it('does not collide a file whose content forges a following entry', async () => { ++ // File bytes may resemble framing for a following field. ++ const enc = new TextEncoder() ++ ++ const a = new FormData() ++ a.append('f', new Blob([enc.encode('AAAkey:1kstr:1v')], { type: '' }), 'n') ++ ++ const b = new FormData() ++ b.append('f', new Blob([enc.encode('AAA')], { type: '' }), 'n') ++ b.append('k', 'v') ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++ ++ it('does not collide blobs that differ only by type/content split', async () => { ++ // Blob content types and bytes must be framed as separate values. ++ const enc = new TextEncoder() ++ ++ const a = new Blob([enc.encode('y')], { type: 'bytes:x' }) ++ const b = new Blob([enc.encode('xbytes:y')], { type: '' }) ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++ ++ it('does not collide a FormData value whose length digits absorb a forged entry', async () => { ++ // Length digits adjacent to user data must not make framing ambiguous. ++ const a = new FormData() ++ a.append('x', 'key:1astr:0') ++ ++ const b = new FormData() ++ b.append('x', '1') ++ b.append('a', '') ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++ ++ it('does not collide blobs whose type-length digits absorb the content', async () => { ++ // Type lengths and content beginning with digits remain distinct. ++ const enc = new TextEncoder() ++ const a = new Blob([new Uint8Array(0)], { type: 'bytes:aaaaa' }) ++ const b = new Blob([enc.encode('aaaaabytes:')], { type: '1' }) ++ ++ const keyA = await cache.generateCacheKey(url, { body: a }) ++ const keyB = await cache.generateCacheKey(url, { body: b }) ++ expect(keyA).not.toBe(keyB) ++ }) ++}) diff --git a/nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh b/nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..91514c7cb7900076407c698a5f6136a7d6465e28 --- /dev/null +++ b/nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/unit/incremental-cache/generate-cache-key.test.ts' --exclude='test/unit/incremental-cache/generate-cache-key.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/unit/incremental-cache/generate-cache-key.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/unit/incremental-cache/generate-cache-key.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/unit/incremental-cache/generate-cache-key.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/generate-cache-key.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/generate-cache-key.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/file-system-cache.test.ts'"'"' '"'"'test/unit/stream-utils/uint8array-helpers.test.ts'"'"''; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json < + /** + * Development-only. Puts a fast built-in in-memory `front` handler in front of + * a slower or persistent user-configured `backing` handler. Its only job is to +- * guarantee that warm reads resolve in a microtask (so they aren't counted as ++ * guarantee that cache hits resolve in a microtask (so they aren't counted as + * cache misses at a staged-render boundary, which would otherwise surface a + * cold cache indicator), while keeping the front in sync with the backing. + * +@@ -76,9 +76,9 @@ export function createTieredCacheHandler( + const frontEntry = await front.get(cacheKey, softTags) + + if (frontEntry) { +- // Warm hit: serve immediately (in a microtask). A background reconcile ++ // Cache hit: serve immediately (in a microtask). A background reconcile + // keeps the front in sync with the backing for the next read; +- // reconciles for the same key are serialized, so concurrent warm reads ++ // reconciles for the same key are serialized, so concurrent cache hits + // don't hit the backing in parallel. + scheduleBackgroundSync(cacheKey, () => + reconcileFrontFromBacking( +@@ -104,7 +104,7 @@ export function createTieredCacheHandler( + } + + // Mirror this freshly read backing entry into the front so the next read +- // is warm. The mirror is serialized per key: if a sync is already ++ // hits it. The mirror is serialized per key: if a sync is already + // running, this chains after it, so the front converges to this read even + // if the backing changed since that sync started. + const [servedEntry, mirroredEntry] = cloneCacheEntry(backingEntry) +@@ -130,9 +130,9 @@ export function createTieredCacheHandler( + } + + /** +- * After serving a warm front hit, consult the backing and mirror a newer entry +- * into the front for the next read. Runs in the background; failures are +- * non-fatal. ++ * After serving a cache hit from the front, consult the backing and mirror a ++ * newer entry into the front for the next read. Runs in the background; ++ * failures are non-fatal. + */ + async function reconcileFrontFromBacking( + front: CacheHandler, +@@ -186,17 +186,18 @@ async function mirrorIntoFront( + + /** + * Build an already-expired copy of an entry, used to evict it from the front +- * handler (which has no per-key delete) once the backing no longer has it. In +- * dev the default handler treats an entry as missing once `now > timestamp + +- * expire * 1000`, so `expire: 0` against the original (past) timestamp makes +- * the next read a miss. The value is never read once the entry is expired, but +- * it must carry at least one byte because the built-in LRU cache refuses to +- * store size-0 entries. ++ * handler (which has no per-key delete) once the backing no longer has it. The ++ * default handler treats a negative `expire` as an eviction sentinel and ++ * reports the entry as missing on the next read. A negative `expire` is used ++ * rather than `0` because the dev front handler enforces a minimum retention, ++ * so a `0` `expire` would be kept alive by that minimum instead of evicted. The ++ * value is never read once the entry is evicted, but it must carry at least one ++ * byte because the built-in LRU cache refuses to store size-0 entries. + */ + function toExpiredEntry(entry: CacheEntry): CacheEntry { + return { + ...entry, +- expire: 0, ++ expire: -1, + value: new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(1)) +diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts +index 9dfddda9d4..3ca4a061e8 100644 +--- a/packages/next/src/server/use-cache/use-cache-wrapper.ts ++++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts +@@ -1092,12 +1092,17 @@ async function collectResult( + // `MIN_PRERENDERABLE_EXPIRE` (5 minutes) caps how long an entry lingers in + // the dedicated in-memory private handler. It is the shortest `expire` that + // isn't treated as dynamic; a smaller `expire` would exclude the entry from +- // prerenders. The size-0 case (`cacheMaxMemorySize: 0`) deliberately does NOT +- // force this: it keeps its resolved cache life so that the cache entry can be +- // considered prerenderable instead of being misread as a dynamic hole, and a +- // separate dev revalidation (see the cache-hit path below) keeps its reloads +- // showing a fresh value. Custom kinds keep their real cache life too, since +- // their backing handler owns it. ++ // prerenders. Two other cases deliberately do NOT force this and keep their ++ // resolved cache life, relying instead on the dev handler's minimum retention ++ // and a dev revalidation (see the cache-hit path below) to keep reloads fast ++ // and fresh. The size-0 case (`cacheMaxMemorySize: 0`) keeps its life so the ++ // entry can be considered prerenderable instead of being misread as a dynamic ++ // hole. An explicit short-`expire` public cache (e.g. `cacheLife({ expire: 0 ++ // })`) keeps its life so it stays correctly excluded from static prerenders ++ // via its real `expire` while a reload still hits the cache; forcing ++ // `revalidate: 0` here would instead corrupt the cache life propagated to an ++ // enclosing cache and trigger the nested-dynamic error. A cache backed by a ++ // custom handler keeps its real cache life too, since that handler owns it. + const forceDynamicCacheLifeInDev = isPrivateCacheInDev + + // If cacheLife() was used to set an explicit revalidate/expire/stale time we +@@ -1640,7 +1645,7 @@ export async function cache( + if (isPrivate) { + // Private caches normally go to the Resume Data Cache (RDC), not a cache + // handler. In development we additionally persist them in a dedicated +- // built-in in-memory handler so that warm reloads are fast. ++ // built-in in-memory handler so that reloads are fast. + if (process.env.__NEXT_DEV_SERVER) { + cacheHandler = getPrivateCacheHandler() + } +@@ -1652,7 +1657,7 @@ export async function cache( + + // In development, a user-configured (custom) handler may be slow or + // remote, so we read through a tiered handler that puts a built-in +- // in-memory front in front of it to keep warm reads microtask-fast. ++ // in-memory front in front of it to keep cache hits microtask-fast. + // Built-in handlers (the default handler, and its size-0 replacement) are + // already in-memory and used directly. + if (process.env.__NEXT_DEV_SERVER && isCustomCacheHandler(kind)) { +@@ -2188,7 +2193,7 @@ export async function cache( + + let stream: undefined | ReadableStream = undefined + +- // Set when a short-lived warm hit ends its cache read up front (dev only) so ++ // Set when a short-lived cache hit ends its cache read up front (dev only) so + // the static-shell boundary doesn't count it as a phantom miss. Once set, the + // cache signal read is balanced, so serving must use a plain stream and skip + // any trailing cacheSignal.endRead() call. +@@ -2945,7 +2950,19 @@ export async function cache( + + if ( + entry === undefined || +- currentTime > entry.timestamp + entry.expire * 1000 || ++ // In dev, the built-in default handler retains a short-`expire` entry ++ // for at least `MIN_PRERENDERABLE_EXPIRE`, both when used directly ++ // and when fronting a custom cache handler. Apply that same minimum ++ // here so the retained entry is served and re-warmed in the ++ // background (below), rather than blocking to regenerate it on every ++ // read. The entry's real `expire` is untouched, so staging still ++ // treats it as dynamic. ++ currentTime > ++ entry.timestamp + ++ (process.env.__NEXT_DEV_SERVER ++ ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE) ++ : entry.expire) * ++ 1000 || + (workStore.isStaticGeneration && + currentTime > entry.timestamp + entry.revalidate * 1000) + ) { +@@ -3134,19 +3151,24 @@ export async function cache( + + // Trigger a background revalidation when the entry is stale (past its + // `revalidate`), so the next read gets a fresh value without blocking +- // this one. In development with the in-memory cache disabled +- // (`cacheMaxMemorySize: 0`), built-in entries keep their resolved +- // (potentially non-dynamic) cache life, so an entry read back from +- // the dev in-memory cache is normally still fresh and wouldn't +- // revalidate on its own; revalidate those on every dynamic request +- // render too, so each reload still shows a fresh value. ++ // this one. Development additionally re-warms on every dynamic ++ // request render in two cases where the dev in-memory entry would ++ // otherwise read back as fresh, so a subsequent reload still shows a ++ // fresh value. The first is with the in-memory cache disabled ++ // (`cacheMaxMemorySize: 0`), where built-in entries keep their ++ // resolved (potentially non-dynamic) cache life. The second is a ++ // short-`expire` entry (an explicit dynamic or client-only cache, ++ // e.g. `cacheLife({ expire: 0 })`), which is retained for at least ++ // `MIN_PRERENDERABLE_EXPIRE` so it is served from the cache; this ++ // also covers custom handlers, re-executing and writing through to ++ // the backing. + let shouldTriggerBackgroundRevalidation = + currentTime > entry.timestamp + entry.revalidate * 1000 + if ( + !shouldTriggerBackgroundRevalidation && + process.env.__NEXT_DEV_SERVER && +- isMemoryCacheDisabled() && +- !isCustomCacheHandler(kind) ++ (entry.expire < MIN_PRERENDERABLE_EXPIRE || ++ (isMemoryCacheDisabled() && !isCustomCacheHandler(kind))) + ) { + switch (workUnitStore.type) { + case 'request': diff --git a/nextjs-cache-short-expire-dev/solution/solve.sh b/nextjs-cache-short-expire-dev/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-cache-short-expire-dev/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-cache-short-expire-dev/tests/Dockerfile b/nextjs-cache-short-expire-dev/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cebc134b40f55703b8b59227f5737edd0e8b4e16 --- /dev/null +++ b/nextjs-cache-short-expire-dev/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-cache-short-expire-dev/tests/test.patch b/nextjs-cache-short-expire-dev/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..f37ad7c3be1f2e005c8164c647513ea07e071d55 --- /dev/null +++ b/nextjs-cache-short-expire-dev/tests/test.patch @@ -0,0 +1,246 @@ +diff --git a/test/development/app-dir/cache-components-dev-streaming/app/page.tsx b/test/development/app-dir/cache-components-dev-streaming/app/page.tsx +index a5d1524c73..4f3c15dfb9 100644 +--- a/test/development/app-dir/cache-components-dev-streaming/app/page.tsx ++++ b/test/development/app-dir/cache-components-dev-streaming/app/page.tsx +@@ -14,6 +14,11 @@ export default function Page() { + /use-cache-private-runtime-prefetch + + ++
  • ++ ++ /use-cache-expire-zero/nav ++ ++
  • +
  • + + /partial-prefetching/session-data +diff --git a/test/development/app-dir/cache-components-dev-streaming/app/use-cache-expire-zero/[slug]/page.tsx b/test/development/app-dir/cache-components-dev-streaming/app/use-cache-expire-zero/[slug]/page.tsx +new file mode 100644 +index 0000000000..cdf45502d4 +--- /dev/null ++++ b/test/development/app-dir/cache-components-dev-streaming/app/use-cache-expire-zero/[slug]/page.tsx +@@ -0,0 +1,43 @@ ++import { Suspense } from 'react' ++import { setTimeout } from 'timers/promises' ++import { cacheLife } from 'next/cache' ++ ++export const prefetch = 'allow-runtime' ++ ++// A distinct slug per test keys a separate cache entry (so the first request ++// for each slug is a genuine cold miss), while both tests share this one ++// runtime-prefetchable page. Declaring the slugs also keeps `params` statically ++// known, so the page shell doesn't depend on dynamic params. In development ++// this does not pre-fill the cache. ++export function generateStaticParams() { ++ return [{ slug: 'nav' }, { slug: 'reload' }] ++} ++ ++async function getExpireZeroValue(slug: string) { ++ 'use cache' ++ // An explicit short `expire` opts this public cache into a dynamic, ++ // client-only life: excluded from the static shell, but included in the ++ // runtime prefetch. The slug keys the entry; the value itself is just a ++ // timestamp. ++ cacheLife({ expire: 0 }) ++ await setTimeout(1500) ++ return new Date().toISOString() ++} ++ ++async function ExpireZeroCached({ slug }: Promise<{ slug: string }>) { ++ const value = await getExpireZeroValue(slug) ++ ++ return

    {value}

    ++} ++ ++export default function Page({ ++ params, ++}: { ++ params: Promise<{ slug: string }> ++}) { ++ return ( ++ Loading...

    }> ++ slug)} /> ++
    ++ ) ++} +diff --git a/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts b/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts +index 2f649898b1..b8c3b0eb1a 100644 +--- a/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts ++++ b/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts +@@ -189,6 +189,91 @@ describe('cache-components-dev-streaming', () => { + }) + }) + ++ it('shows the short-expire-cache fallback on a cold client navigation but not on a warm one', async () => { ++ // A public `'use cache'` with an explicit short `expire` (`cacheLife({ ++ // expire: 0 })`) is a runtime-prefetch route here, so its cached content ++ // belongs to the runtime shell stage. On a warm navigation the dev minimum ++ // retention keeps the entry available, and the client defers revealing the ++ // response until the shell has flushed, so the content arrives with the ++ // shell and the fallback isn't shown - just like a private cache. ++ const browser = await next.browser('/') ++ ++ // Cold navigation: the cache misses and fills in the background, so the ++ // fallback is shown until the content streams in. ++ await browser.elementByCss('a[href="/use-cache-expire-zero/nav"]').click() ++ expect(await browser.elementByCss('#expire-zero-fallback').text()).toBe( ++ 'Loading...' ++ ) ++ expect(await browser.elementByCss('#expire-zero').text()).toBeDateString() ++ ++ // Wait for the background write to settle so the next navigation hits the ++ // warm entry instead of racing a pending write. ++ await waitFor(2000) ++ ++ // Hard-reload home so the warm navigation below starts from a fresh page. ++ await browser.loadPage(new URL('/', next.url).href) ++ ++ // Warm navigation: record whether the fallback ever enters the DOM. It ++ // shouldn't, since the retained entry is delivered with the shell. (The ++ // client-side reveal race that this delivery relies on is covered by the ++ // private-cache test above, so we don't repeat its stress loop here.) ++ const fallbackObserver = observeNodeAppearances(browser, [ ++ 'expire-zero-fallback', ++ ]) ++ ++ await fallbackObserver.observe() ++ ++ await browser.elementByCss('a[href="/use-cache-expire-zero/nav"]').click() ++ expect(await browser.elementByCss('#expire-zero').text()).toBeDateString() ++ ++ const appearanceCounts = await fallbackObserver.getResult() ++ expect(appearanceCounts).toEqual({ ++ 'expire-zero-fallback': 0, ++ }) ++ }) ++ ++ it('serves a short-expire cache warm on reload and converges to a fresh value', async () => { ++ const browser = await next.browser('/use-cache-expire-zero/reload', { ++ waitHydration: false, ++ // Do not wait for "load"; inspect the page as it streams in. ++ waitUntil: 'commit', ++ }) ++ ++ // Cold load: the cache misses, so the fallback streams first, and the ++ // generated value streams in once generation completes. The value is a ++ // dynamic hole (real `expire: 0`), so it streams in after the shell. ++ expect( ++ await browser ++ .elementByCss('#expire-zero-fallback', { waitUntil: false }) ++ .text() ++ ).toBe('Loading...') ++ const coldValue = await browser ++ .elementByCss('#expire-zero', { waitUntil: false }) ++ .text() ++ expect(coldValue).toBeDateString() ++ ++ // Warm reload: the dev minimum retention keeps the short-expire entry, so ++ // the reload serves the previously cached value fast instead of ++ // regenerating it. A background revalidation regenerates a fresh entry for ++ // the next reload (asserted below). We wait for the streamed-in element ++ // without waiting for "load", so no retry is needed. ++ await browser.refresh({ waitUntil: 'commit' }) ++ expect( ++ await browser.elementByCss('#expire-zero', { waitUntil: false }).text() ++ ).toBe(coldValue) ++ ++ // That warm reload re-warmed a fresh entry in the background, so a later ++ // reload converges to the new value. Read after "load" here (a plain ++ // refresh) since we want the settled value, not the streaming inspection ++ // above. ++ await retry(async () => { ++ await browser.refresh() ++ expect(await browser.elementById('expire-zero').text()).not.toBe( ++ coldValue ++ ) ++ }) ++ }) ++ + // The following are smoke tests that Cache Components validation still + // surfaces errors for both cold-cache renders (validated via a separate + // warm-cache render) and warm-cache renders (validated via the streamed +diff --git a/test/development/app-dir/use-cache-custom-handler-dev/app/expire-zero/page.tsx b/test/development/app-dir/use-cache-custom-handler-dev/app/expire-zero/page.tsx +new file mode 100644 +index 0000000000..e7d5b06820 +--- /dev/null ++++ b/test/development/app-dir/use-cache-custom-handler-dev/app/expire-zero/page.tsx +@@ -0,0 +1,36 @@ ++import { Suspense } from 'react' ++import { setTimeout } from 'timers/promises' ++import { cacheLife } from 'next/cache' ++ ++// A public `'use cache'` routed through the custom (slow) handler, with an ++// explicit short `expire`. In dev the built-in front handler applies a minimum ++// retention, so a cache hit still resolves from the front in a microtask ++// instead of paying the backing's latency on every read. ++async function getCachedValue() { ++ 'use cache' ++ // `expire: 0` gives a short, dynamic (client-only) cache life, excluded from ++ // static prerenders. Reusing it across client navigations would require ++ // opting the route into runtime prefetching (`prefetch = 'allow-runtime'`) so ++ // Cached Navigations embeds it into the client router cache; this fixture ++ // doesn't, since the test only exercises the dev front handler serving it ++ // warm on reloads. ++ cacheLife({ expire: 0 }) ++ await setTimeout(1000) ++ return new Date().toISOString() ++} ++ ++async function CachedValue() { ++ const value = await getCachedValue() ++ ++ return

    {value}

    ++} ++ ++export default function Page() { ++ return ( ++
    ++ Loading...

    }> ++ ++
    ++
    ++ ) ++} +diff --git a/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts b/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts +index f7a8508129..197060fa4a 100644 +--- a/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts ++++ b/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts +@@ -40,6 +40,38 @@ describe('use-cache-custom-handler-dev', () => { + expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(false) + }) + ++ it('serves a short-expire value warm through a custom handler and re-warms it on each reload', async () => { ++ const browser = await next.browser('/expire-zero', { ++ waitHydration: false, ++ // Do not wait for "load"; inspect the page as it streams in. ++ waitUntil: 'commit', ++ }) ++ ++ // Cold load: the custom handler misses, the value generates and is written ++ // through to both the backing handler and the dev-only in-memory front. We ++ // wait for the streamed-in element without waiting for "load". ++ const coldValue = await browser ++ .elementByCss('#value', { waitUntil: false }) ++ .text() ++ expect(coldValue).toBeDateString() ++ ++ // Warm reload: served fast from the front, whose minimum retention keeps ++ // the short-`expire` entry. The custom handler's slow `get` isn't on the ++ // critical path, and the short `expire` no longer evicts the front entry on ++ // every read, so the same cached value shows. ++ await browser.refresh({ waitUntil: 'commit' }) ++ expect( ++ await browser.elementByCss('#value', { waitUntil: false }).text() ++ ).toBe(coldValue) ++ ++ // Each warm reload re-executes the cache function and writes through to the ++ // backing, so reloads converge to a fresh value. ++ await retry(async () => { ++ await browser.refresh() ++ expect(await browser.elementById('value').text()).not.toBe(coldValue) ++ }) ++ }) ++ + it('stops serving a front-cached entry after the backing cache is purged out-of-band', async () => { + const browser = await next.browser('/purged') + diff --git a/nextjs-cache-short-expire-dev/tests/test.sh b/nextjs-cache-short-expire-dev/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3c45e7cf4987374ff37136f1730c4164998cf2d --- /dev/null +++ b/nextjs-cache-short-expire-dev/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' --exclude='test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts/*' --exclude='test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts' --exclude='test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' 'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' 'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts' '/app/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-dev '"'"'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts'"'"' '"'"'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-dev '"'"'test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts'"'"' '"'"'test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-dev '"'"'test/development/app-dir/use-cache-size-zero/use-cache-size-zero.test.ts'"'"' '"'"'test/development/app-dir/basic/basic.test.ts'"'"''; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json < { ++ const isTailwindTemplate = [ ++ 'app-tw', ++ 'app-tw-empty', ++ 'default-tw', ++ 'default-tw-empty', ++ ].includes(template) ++ + projectFilesShouldExist({ + cwd, + projectName, + files: getProjectSetting({ template, mode, setting: 'files', srcDir }), + }) + +- // Tailwind templates share the same files (tailwind.config.mjs, postcss.config.mjs) +- if ( +- !['app-tw', 'app-tw-empty', 'default-tw', 'default-tw-empty'].includes( +- template +- ) +- ) { ++ // Tailwind templates share the same files across JavaScript and TypeScript. ++ if (!isTailwindTemplate) { + projectFilesShouldNotExist({ + cwd, + projectName, +@@ -165,6 +168,14 @@ export const shouldBeTemplateProject = ({ + }) + } + ++ if (isTailwindTemplate && !process.env.NEXT_RSPACK) { ++ projectFilesShouldNotExist({ ++ cwd, ++ projectName, ++ files: ['postcss.config.mjs'], ++ }) ++ } ++ + projectDepsShouldBe({ + type: 'dependencies', + cwd, +diff --git a/test/production/create-next-app/templates/app.test.ts b/test/production/create-next-app/templates/app.test.ts +index f52d05fa..9593db13 100644 +--- a/test/production/create-next-app/templates/app.test.ts ++++ b/test/production/create-next-app/templates/app.test.ts +@@ -1,4 +1,7 @@ ++import { readFileSync } from 'fs' ++import { join } from 'path' + import { ++ projectFilesShouldExist, + projectShouldHaveNoGitChanges, + resolveNextTgzFilename, + shouldBeTemplateProject, +@@ -145,7 +148,49 @@ describe('create-next-app --app (App Router)', () => { + await tryNextDev({ + cwd, + projectName, ++ tailwind: true, + }) ++ ++ // The non-Turbopack path must keep its PostCSS integration. ++ if (!process.env.NEXT_RSPACK) { ++ const rspackProjectName = 'app-tw-rspack' ++ const rspackResult = await run( ++ [ ++ rspackProjectName, ++ '--ts', ++ '--app', ++ '--tailwind', ++ '--rspack', ++ '--skip-install', ++ '--no-eslint', ++ '--no-biome', ++ '--no-src-dir', ++ '--no-import-alias', ++ '--no-react-compiler', ++ '--no-agents-md', ++ ], ++ nextTgzFilename, ++ { cwd } ++ ) ++ ++ expect(rspackResult.exitCode).toBe(0) ++ projectFilesShouldExist({ ++ cwd, ++ projectName: rspackProjectName, ++ files: ['postcss.config.mjs'], ++ }) ++ const rspackRoot = join(cwd, rspackProjectName) ++ const rspackPackage = JSON.parse( ++ readFileSync(join(rspackRoot, 'package.json'), 'utf8') ++ ) ++ expect(rspackPackage.devDependencies).toHaveProperty( ++ '@tailwindcss/postcss' ++ ) ++ expect(rspackPackage.devDependencies).toHaveProperty('tailwindcss') ++ expect(rspackPackage.devDependencies).not.toHaveProperty( ++ '@tailwindcss/turbopack' ++ ) ++ } + }) + }) + +diff --git a/test/production/create-next-app/utils.ts b/test/production/create-next-app/utils.ts +index 73a46770..39411d8a 100644 +--- a/test/production/create-next-app/utils.ts ++++ b/test/production/create-next-app/utils.ts +@@ -2,6 +2,7 @@ import execa from 'execa' + import { join } from 'path' + import { spawn } from 'child_process' + import { fetchViaHTTP, findPort, killApp } from 'next-test-utils' ++import webdriver from 'next-webdriver' + import { + resolveTestPkgPaths, + serializeTestPkgPathsEnv, +@@ -9,6 +10,15 @@ import { + + export const CNA_PATH = require.resolve('create-next-app/dist/index.js') + ++// Run create-next-app from TypeScript source so the test exercises the current ++// checkout. The verifier applies candidate changes after its build fixtures are ++// prepared, so invoking dist/index.js here would test a stale pre-patch bundle. ++const CNA_SOURCE_PATH = join( ++ __dirname, ++ '../../../packages/create-next-app/index.ts' ++) ++const TSX_CLI_PATH = require.resolve('tsx/cli') ++ + /** + * Resolves the path to the packed `next` tarball. Uses NEXT_TEST_PKG_PATHS + * when available (set by run-tests.js), otherwise finds packed.tgz files +@@ -49,7 +59,7 @@ export const run = async ( + env?: Record + } + ) => { +- return execa('node', [CNA_PATH].concat(args), { ++ return execa('node', [TSX_CLI_PATH, CNA_SOURCE_PATH].concat(args), { + // tests with options.reject false are expected to exit(1) so don't inherit + stdio: options.reject === false ? 'pipe' : 'inherit', + ...options, +@@ -84,12 +94,14 @@ export async function tryNextDev({ + isApp = true, + isApi = false, + isEmpty = false, ++ tailwind = false, + }: { + cwd: string + projectName: string + isApp?: boolean + isApi?: boolean + isEmpty?: boolean ++ tailwind?: boolean + }) { + // The caller wraps this in `useTempDir`, so `cwd` (and the CNA project + // inside it) is already an isolated temp directory that gets removed +@@ -129,6 +141,8 @@ export async function tryNextDev({ + // headroom so these tests aren't flaky on loaded CI machines. + const startServerTimeout = 60_000 + ++ let browser: Awaited> | undefined ++ + try { + await new Promise((resolve, reject) => { + const onTimeout = setTimeout(() => { +@@ -164,6 +178,17 @@ export async function tryNextDev({ + }) + }) + ++ // The webpack test matrix forces generated apps to build with webpack, ++ // but create-next-app only exposes Turbopack and Rspack as bundler choices. ++ // Only assert rendered Tailwind styles when the generated bundler matches ++ // the test bundler. ++ if (tailwind && !process.env.IS_WEBPACK_TEST) { ++ browser = await webdriver(port, '/') ++ expect(await browser.elementByCss('main').getComputedCss('display')).toBe( ++ 'flex' ++ ) ++ } ++ + const res = await fetchViaHTTP(port, '/') + if (isEmpty || isApi) { + expect(await res.text()).toContain('Hello world!') +@@ -190,6 +215,7 @@ export async function tryNextDev({ + expect(apiRes.status).toBe(200) + } + } finally { ++ await browser?.close() + await killApp(server).catch(() => {}) + } + } diff --git a/nextjs-cna-tailwind-turbopack/tests/test.sh b/nextjs-cna-tailwind-turbopack/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b88846a61b6ccafa6a50f520f130f5642ce0a0 --- /dev/null +++ b/nextjs-cna-tailwind-turbopack/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/production/create-next-app/templates/app.test.ts' --exclude='test/production/create-next-app/templates/app.test.ts/*' --exclude='test/production/create-next-app/eslint-config.test.ts' --exclude='test/production/create-next-app/eslint-config.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/production/create-next-app/templates/app.test.ts' 'test/production/create-next-app/eslint-config.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/production/create-next-app/templates/app.test.ts' 'test/production/create-next-app/eslint-config.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/production/create-next-app/templates/app.test.ts' '/app/test/production/create-next-app/eslint-config.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'NEXT_TEST_NATIVE_DIR="$PWD/node_modules/@next/swc-linux-x64-gnu" pnpm test-start-turbo '"'"'test/production/create-next-app/templates/app.test.ts'"'"' -t '"'"'should create TailwindCSS project with --tailwind flag|should generate eslint.config.mjs for TypeScript project with ESLint'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'NEXT_TEST_NATIVE_DIR="$PWD/node_modules/@next/swc-linux-x64-gnu" pnpm test-start-turbo '"'"'test/production/create-next-app/templates/app.test.ts'"'"' -t '"'"'should create TailwindCSS project with --tailwind flag|should generate eslint.config.mjs for TypeScript project with ESLint'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'NEXT_TEST_NATIVE_DIR="$PWD/node_modules/@next/swc-linux-x64-gnu" pnpm test-start-turbo '"'"'test/production/create-next-app/eslint-config.test.ts'"'"' -t '"'"'should create TailwindCSS project with --tailwind flag|should generate eslint.config.mjs for TypeScript project with ESLint'"'"''; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json < = {} + ): Promise { + const isCompileMode = experimentalBuildMode === 'compile' +@@ -977,7 +978,6 @@ export default async function build( + NextBuildContext.reactProductionProfiling = reactProductionProfiling + NextBuildContext.noMangling = noMangling + NextBuildContext.debugPrerender = debugPrerender +- NextBuildContext.debugBuildPaths = debugBuildPaths + + await nextBuildSpan.traceAsyncFn(async () => { + // attempt to load global env values so they are available in next.config.js +@@ -1018,6 +1018,19 @@ export default async function build( + ) + loadedConfig = config + ++ // Resolve selective build paths now that the page extensions are known. ++ const debugBuildPaths = debugBuildPathsPatterns ++ ? await (async () => { ++ const resolved = await resolveBuildPaths( ++ debugBuildPathsPatterns, ++ dir, ++ config.pageExtensions ++ ) ++ return { app: resolved.appPaths, pages: resolved.pagePaths } ++ })() ++ : undefined ++ NextBuildContext.debugBuildPaths = debugBuildPaths ++ + // Validate deploymentId if provided + if (config.deploymentId !== undefined) { + if (typeof config.deploymentId !== 'string') { +diff --git a/packages/next/src/cli/next-build.ts b/packages/next/src/cli/next-build.ts +index bc2ac3537e3cfa4b75301538f7a8ed2f8626c480..a0e3cdcdb3f41814f80e511c82cad7d4a5533822 100755 +--- a/packages/next/src/cli/next-build.ts ++++ b/packages/next/src/cli/next-build.ts +@@ -11,10 +11,7 @@ import { getProjectDir } from '../lib/get-project-dir' + import { enableMemoryDebuggingMode } from '../lib/memory/startup' + import { disableMemoryDebuggingMode } from '../lib/memory/shutdown' + import { Bundler, parseBundlerArgs } from '../lib/bundler' +-import { +- resolveBuildPaths, +- parseBuildPathsInput, +-} from '../lib/resolve-build-paths' ++import { parseBuildPathsInput } from '../lib/resolve-build-paths' + + export type NextBuildOptions = { + experimentalAnalyze?: boolean +@@ -104,24 +101,13 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => { + printAndExit(`> No such directory exists as the project root: ${dir}`) + } + +- // Resolve selective build paths +- let resolvedBuildPaths: { app: string[]; pages: string[] } | undefined ++ let debugBuildPathsPatterns: string[] | undefined + + if (debugBuildPaths) { +- try { +- const patterns = parseBuildPathsInput(debugBuildPaths) +- +- if (patterns.length > 0) { +- const resolved = await resolveBuildPaths(patterns, dir) +- resolvedBuildPaths = { +- app: resolved.appPaths, +- pages: resolved.pagePaths, +- } +- } +- } catch (err) { +- printAndExit( +- `Failed to resolve build paths: ${isError(err) ? err.message : String(err)}` +- ) ++ const patterns = parseBuildPathsInput(debugBuildPaths) ++ ++ if (patterns.length > 0) { ++ debugBuildPathsPatterns = patterns + } + } + +@@ -145,7 +131,7 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => { + bundler, + experimentalBuildMode, + traceUploadUrl, +- resolvedBuildPaths, ++ debugBuildPathsPatterns, + enabledFeatures + ) + .catch((err) => { +diff --git a/packages/next/src/lib/resolve-build-paths.ts b/packages/next/src/lib/resolve-build-paths.ts +index 9ffb4c70b7bc044c7eb58fe652b79625afe264e1..b8759df8a0b7d7a85bc19c238c9095e86ed929ad 100644 +--- a/packages/next/src/lib/resolve-build-paths.ts ++++ b/packages/next/src/lib/resolve-build-paths.ts +@@ -4,6 +4,8 @@ import * as Log from '../build/output/log' + import path from 'path' + import fs from 'fs' + import isError from './is-error' ++import { createValidFileMatcher } from '../server/lib/find-page-file' ++import type { PageExtensions } from '../build/page-extensions-type' + + const glob = promisify(globOriginal) + +@@ -35,10 +37,12 @@ function escapeBrackets(pattern: string): string { + */ + export async function resolveBuildPaths( + patterns: string[], +- projectDir: string ++ projectDir: string, ++ pageExtensions: PageExtensions + ): Promise { + const appPaths: Set = new Set() + const pagePaths: Set = new Set() ++ const validFileMatcher = createValidFileMatcher(pageExtensions, undefined) + + // Detect whether the project keeps its routes under `src/` so we can accept + // patterns written with or without that prefix (e.g. both `app/foo/page.tsx` +@@ -89,7 +93,7 @@ export async function resolveBuildPaths( + + for (const file of matches) { + if (!fs.statSync(path.join(projectDir, file)).isDirectory()) { +- categorizeAndAddPath(file, appPaths, pagePaths) ++ categorizeAndAddPath(file, appPaths, pagePaths, validFileMatcher) + } + } + } catch (error) { +@@ -128,7 +132,7 @@ function addSrcPrefixIfNeeded( + + /** + * Categorizes a file path to either app or pages router based on its prefix. +- * For app router, only route-defining files (page.*, route.*) are included. ++ * For app router, only route-defining files are included. + * + * Accepts both top-level (`app/...`, `pages/...`) and src-prefixed + * (`src/app/...`, `src/pages/...`) project structures. +@@ -142,7 +146,8 @@ function addSrcPrefixIfNeeded( + function categorizeAndAddPath( + filePath: string, + appPaths: Set, +- pagePaths: Set ++ pagePaths: Set, ++ validFileMatcher: ReturnType + ): void { + let normalized = filePath.replace(/\\/g, '/') + +@@ -151,9 +156,9 @@ function categorizeAndAddPath( + } + + if (normalized.startsWith('app/')) { +- // Only include route-defining files (page.* or route.*) +- if (/\/(page|route)\.[^/]+$/.test(normalized)) { +- appPaths.add('/' + normalized.slice(4)) ++ const appRelativePath = '/' + normalized.slice(4) ++ if (validFileMatcher.isAppRouterPage(appRelativePath)) { ++ appPaths.add(appRelativePath) + } + } else if (normalized.startsWith('pages/')) { + pagePaths.add('/' + normalized.slice(6)) diff --git a/nextjs-debug-build-paths-metadata/solution/solve.sh b/nextjs-debug-build-paths-metadata/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-debug-build-paths-metadata/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-debug-build-paths-metadata/tests/Dockerfile b/nextjs-debug-build-paths-metadata/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dfe1584980495892ac74a9a85e157b20addb6d5b --- /dev/null +++ b/nextjs-debug-build-paths-metadata/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-debug-build-paths-metadata/tests/test.patch b/nextjs-debug-build-paths-metadata/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..fb7123491300513a8d384f205fe70aa60b3d330d --- /dev/null +++ b/nextjs-debug-build-paths-metadata/tests/test.patch @@ -0,0 +1,96 @@ +diff --git a/test/production/debug-build-path/fixtures/default/app/robots.metadata.ts b/test/production/debug-build-path/fixtures/default/app/robots.metadata.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..309e3e197d231f2a9ea60926a67b9c6456c65b56 +--- /dev/null ++++ b/test/production/debug-build-path/fixtures/default/app/robots.metadata.ts +@@ -0,0 +1,8 @@ ++export default function robots() { ++ return { ++ rules: { ++ userAgent: '*', ++ allow: '/', ++ }, ++ } ++} +diff --git a/test/production/debug-build-path/fixtures/default/app/sitemap.metadata.ts b/test/production/debug-build-path/fixtures/default/app/sitemap.metadata.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..7d37bfe091ebf1a2c2cbc1d9e32ea654acbb39c8 +--- /dev/null ++++ b/test/production/debug-build-path/fixtures/default/app/sitemap.metadata.ts +@@ -0,0 +1,3 @@ ++export default function sitemap() { ++ return [{ url: 'https://example.com' }] ++} +diff --git a/test/production/debug-build-path/fixtures/default/next.config.js b/test/production/debug-build-path/fixtures/default/next.config.js +index 767719fc4fba59345ae29e29159c9aff270f5819..af7a39f7888845358a628ac3f0e2e2a2130754de 100644 +--- a/test/production/debug-build-path/fixtures/default/next.config.js ++++ b/test/production/debug-build-path/fixtures/default/next.config.js +@@ -1,4 +1,6 @@ + /** @type {import('next').NextConfig} */ +-const nextConfig = {} ++const nextConfig = { ++ pageExtensions: ['metadata.ts', 'js', 'jsx', 'ts', 'tsx'], ++} + + module.exports = nextConfig +diff --git a/test/production/debug-build-path/metadata-routes.test.ts b/test/production/debug-build-path/metadata-routes.test.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..eb06963fafb3fc74463da0c1a352da5628d0a884 +--- /dev/null ++++ b/test/production/debug-build-path/metadata-routes.test.ts +@@ -0,0 +1,26 @@ ++import path from 'path' ++import { nextTestSetup } from 'e2e-utils' ++ ++describe('debug-build-paths metadata routes', () => { ++ const { next } = nextTestSetup({ ++ files: path.join(__dirname, 'fixtures/default'), ++ skipStart: true, ++ env: { ++ __NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT: '1', ++ }, ++ }) ++ ++ it('selectively builds App Router metadata routes', async () => { ++ const result = await next.build({ ++ args: [ ++ '--debug-build-paths', ++ 'app/robots.metadata.ts,app/sitemap.metadata.ts', ++ ], ++ }) ++ ++ expect(result.exitCode).toBe(0) ++ expect(result.cliOutput).toContain('/robots.txt') ++ expect(result.cliOutput).toContain('/sitemap.xml') ++ expect(result.cliOutput).not.toContain('/about') ++ }) ++}) +diff --git a/test/production/debug-build-path/page-route.test.ts b/test/production/debug-build-path/page-route.test.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..6febe039083cf070a099aae81574fb70a18a7ee1 +--- /dev/null ++++ b/test/production/debug-build-path/page-route.test.ts +@@ -0,0 +1,23 @@ ++import path from 'path' ++import { nextTestSetup } from 'e2e-utils' ++ ++describe('debug-build-paths page route regression', () => { ++ const { next } = nextTestSetup({ ++ files: path.join(__dirname, 'fixtures/default'), ++ skipStart: true, ++ env: { ++ __NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT: '1', ++ }, ++ }) ++ ++ it('continues to selectively build a regular App Router page', async () => { ++ const result = await next.build({ ++ args: ['--debug-build-paths', 'app/about/page.tsx'], ++ }) ++ ++ expect(result.exitCode).toBe(0) ++ expect(result.cliOutput).toContain('/about') ++ expect(result.cliOutput).not.toContain('/robots.txt') ++ expect(result.cliOutput).not.toContain('/sitemap.xml') ++ }) ++}) diff --git a/nextjs-debug-build-paths-metadata/tests/test.sh b/nextjs-debug-build-paths-metadata/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a1649816a523c886074d7a59c344a8aa8e66bbe3 --- /dev/null +++ b/nextjs-debug-build-paths-metadata/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/production/debug-build-path/metadata-routes.test.ts' --exclude='test/production/debug-build-path/metadata-routes.test.ts/*' --exclude='test/production/debug-build-path/page-route.test.ts' --exclude='test/production/debug-build-path/page-route.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/production/debug-build-path/metadata-routes.test.ts' 'test/production/debug-build-path/page-route.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/production/debug-build-path/metadata-routes.test.ts' 'test/production/debug-build-path/page-route.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/production/debug-build-path/metadata-routes.test.ts' '/app/test/production/debug-build-path/page-route.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'pnpm build && NEXT_SKIP_ISOLATE=1 pnpm test-start-webpack '"'"'test/production/debug-build-path/metadata-routes.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm build && NEXT_SKIP_ISOLATE=1 pnpm test-start-webpack '"'"'test/production/debug-build-path/metadata-routes.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'pnpm build && NEXT_SKIP_ISOLATE=1 pnpm test-start-webpack '"'"'test/production/debug-build-path/page-route.test.ts'"'"''; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json < ( +- match urlencoding::decode(&token.original_file)? { +- Cow::Borrowed(_) => token.original_file, +- Cow::Owned(original_file) => RcStr::from(original_file), +- }, ++ // Still percent-encoded, like the URIs it's compared against. ++ token.original_file, + // JS stack frames are 1-indexed, source map tokens are 0-indexed + Some(token.original_line + 1), + Some(token.original_column + 1), +@@ -2361,36 +2359,51 @@ async fn project_trace_source_operation( + } + }; + ++ // Turns a percent-encoded URI fragment back into a path for output. ++ fn decode_uri_fragment(value: &str) -> Result { ++ Ok(match urlencoding::decode(value)? { ++ Cow::Borrowed(borrowed) => RcStr::from(borrowed), ++ Cow::Owned(owned) => RcStr::from(owned), ++ }) ++ } ++ + let project_root_uri = + uri_from_file(container.project().project_root_path().owned().await?, None).await? + "/"; ++ // Relative paths are computed on decoded inputs: they come from ++ // different encoders that disagree on characters like `[` vs `%5B`. ++ let current_directory_path = decode_uri_fragment(¤t_directory_file_url)?; + let (file, original_file) = + if let Some(source_file) = original_file.strip_prefix(&project_root_uri) { + // Client code uses file:// + ( + RcStr::from( +- get_relative_path_to(¤t_directory_file_url, &original_file) +- // TODO(sokra) remove this to include a ./ here to make it a relative path +- .trim_start_matches("./"), ++ get_relative_path_to( ++ ¤t_directory_path, ++ &decode_uri_fragment(&original_file)?, ++ ) ++ // TODO(sokra) remove this to include a ./ here to make it a relative path ++ .trim_start_matches("./"), + ), +- Some(RcStr::from(source_file)), ++ Some(decode_uri_fragment(source_file)?), + ) + } else if let Some(source_file) = original_file.strip_prefix(&*SOURCE_MAP_PREFIX_PROJECT) { + // Server code uses turbopack:///[project] + // TODO should this also be file://? ++ let source_file = decode_uri_fragment(source_file)?; + ( + RcStr::from( + get_relative_path_to( +- ¤t_directory_file_url, +- &format!("{project_root_uri}{source_file}"), ++ ¤t_directory_path, ++ &format!("{}{}", decode_uri_fragment(&project_root_uri)?, source_file), + ) + // TODO(sokra) remove this to include a ./ here to make it a relative path + .trim_start_matches("./"), + ), +- Some(RcStr::from(source_file)), ++ Some(source_file), + ) + } else if let Some(source_file) = original_file.strip_prefix(&*SOURCE_MAP_PREFIX) { + // TODO(veil): Should the protocol be preserved? +- (RcStr::from(source_file), None) ++ (decode_uri_fragment(source_file)?, None) + } else { + bail!( + "Original file ({}) outside project ({})", +diff --git a/packages/next/src/server/dev/middleware-turbopack.ts b/packages/next/src/server/dev/middleware-turbopack.ts +index d733e77aa41ac46c297d1e5c4f154f4dec14815b..5de99c4d43dc9732ce0256718cca887f5fe5c7f4 100644 +--- a/packages/next/src/server/dev/middleware-turbopack.ts ++++ b/packages/next/src/server/dev/middleware-turbopack.ts +@@ -130,7 +130,16 @@ function parseFile(fileParam: string | null): string | undefined { + return undefined + } + +- return devirtualizeReactServerURL(fileParam) ++ const file = devirtualizeReactServerURL(fileParam) ++ // React virtualizes filenames as `'file://' + path`, which is malformed ++ // for paths that need percent-encoding (e.g. a space in the project path) ++ // and then fails both Turbopack's `traceSource` and Node.js' source map ++ // cache lookups. Re-encode through WHATWG URL parsing. ++ // TODO(veil): Revisit if React's virtualization round-trips losslessly. ++ if (file.startsWith('file://') && URL.canParse(file)) { ++ return new URL(file).href ++ } ++ return file + } + + function createStackFrames( diff --git a/nextjs-dev-overlay-encoded-paths/solution/solve.sh b/nextjs-dev-overlay-encoded-paths/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-dev-overlay-encoded-paths/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-dev-overlay-encoded-paths/tests/Dockerfile b/nextjs-dev-overlay-encoded-paths/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..71b3414d677d6a424cd89a512e08543bffb5a0ee --- /dev/null +++ b/nextjs-dev-overlay-encoded-paths/tests/Dockerfile @@ -0,0 +1,43 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | env RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo sh -s -- -y --no-modify-path --profile minimal --default-toolchain 1.90.0 +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm build && pnpm --dir packages/next-swc build-native && pnpm exec playwright install --with-deps chromium' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-dev-overlay-encoded-paths/tests/test.patch b/nextjs-dev-overlay-encoded-paths/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..133c427ef9f88cba128e05ec4dce45c80af8f0bc --- /dev/null +++ b/nextjs-dev-overlay-encoded-paths/tests/test.patch @@ -0,0 +1,119 @@ +diff --git a/test/development/app-dir/special-project-paths/fixtures/app/layout.js b/test/development/app-dir/special-project-paths/fixtures/app/layout.js +new file mode 100644 +index 0000000000000000000000000000000000000000..803f17d863c8ad887c14588aab3487e473367b41 +--- /dev/null ++++ b/test/development/app-dir/special-project-paths/fixtures/app/layout.js +@@ -0,0 +1,7 @@ ++export default function RootLayout({ children }) { ++ return ( ++ ++ {children} ++ ++ ) ++} +diff --git a/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/Thrower.js b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/Thrower.js +new file mode 100644 +index 0000000000000000000000000000000000000000..140fa61e8ba3c0d722afbabe5ba1d69de79bf0f2 +--- /dev/null ++++ b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/Thrower.js +@@ -0,0 +1,10 @@ ++'use client' ++ ++function throwError() { ++ throw new Error('ssr-throw') ++} ++ ++export function Thrower() { ++ throwError() ++ return null ++} +diff --git a/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/page.js b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/page.js +new file mode 100644 +index 0000000000000000000000000000000000000000..d5d6f5cad684f2e81f3c796e9a7e0ede72c95637 +--- /dev/null ++++ b/test/development/app-dir/special-project-paths/fixtures/app/ssr-throw/page.js +@@ -0,0 +1,5 @@ ++import { Thrower } from './Thrower' ++ ++export default function Page() { ++ return ++} +diff --git a/test/development/app-dir/special-project-paths/fixtures/next.config.js b/test/development/app-dir/special-project-paths/fixtures/next.config.js +new file mode 100644 +index 0000000000000000000000000000000000000000..4ba52ba2c8df6758685c8f65f490306b5c44eb76 +--- /dev/null ++++ b/test/development/app-dir/special-project-paths/fixtures/next.config.js +@@ -0,0 +1 @@ ++module.exports = {} +diff --git a/test/development/app-dir/special-project-paths/special-project-paths.test.ts b/test/development/app-dir/special-project-paths/special-project-paths.test.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..4f5399aff3c8c153fa06a243c81ad8ea6c6ff89d +--- /dev/null ++++ b/test/development/app-dir/special-project-paths/special-project-paths.test.ts +@@ -0,0 +1,66 @@ ++import * as path from 'path' ++import { nextTestSetup } from 'e2e-utils' ++import stripAnsi from 'strip-ansi' ++import { getRedboxSource, retry } from 'next-test-utils' ++ ++function setup(subDir: string) { ++ return nextTestSetup({ ++ files: path.join(__dirname, 'fixtures'), ++ subDir, ++ }) ++} ++ ++async function assertSymbolicatedSSRError( ++ next: ReturnType['next'] ++) { ++ const outputIndex = next.cliOutput.length ++ const browser = await next.browser('/ssr-throw') ++ ++ await retry(() => { ++ expect(next.cliOutput.slice(outputIndex)).toContain('Error: ssr-throw') ++ }) ++ ++ const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex)) ++ expect(cliOutput).toContain('at throwError (app/ssr-throw/Thrower.js:4:9)') ++ expect(cliOutput).toContain('at Thrower (app/ssr-throw/Thrower.js:8:3)') ++ expect(cliOutput).toContain("throw new Error('ssr-throw')") ++ ++ let redboxSource: string | null = null ++ await retry(async () => { ++ redboxSource = await getRedboxSource(browser) ++ expect(redboxSource).not.toBeNull() ++ }) ++ expect(redboxSource).toContain('app/ssr-throw/Thrower.js (4:9) @ throwError') ++ expect(redboxSource).toContain("throw new Error('ssr-throw')") ++} ++ ++// Symbolication must work in project directories whose absolute path ++// contains characters that need percent-encoding in URLs. ++describe('special project paths', () => { ++ describe('in "space dir"', () => { ++ const { skipped, next } = setup('space dir') ++ if (skipped) return ++ ++ it('symbolicates thrown SSR errors', async () => { ++ await assertSymbolicatedSSRError(next) ++ }) ++ }) ++ ++ describe('in "ünïcode-dir"', () => { ++ const { skipped, next } = setup('ünïcode-dir') ++ if (skipped) return ++ ++ it('symbolicates thrown SSR errors', async () => { ++ await assertSymbolicatedSSRError(next) ++ }) ++ }) ++ ++ describe('in "bracket [dir]"', () => { ++ const { skipped, next } = setup('bracket [dir]') ++ if (skipped) return ++ ++ it('symbolicates thrown SSR errors', async () => { ++ await assertSymbolicatedSSRError(next) ++ }) ++ }) ++}) diff --git a/nextjs-dev-overlay-encoded-paths/tests/test.sh b/nextjs-dev-overlay-encoded-paths/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7332ab57cf057eb886b395cb374d2747c10be92d --- /dev/null +++ b/nextjs-dev-overlay-encoded-paths/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='test/development/app-dir/special-project-paths/special-project-paths.test.ts' --exclude='test/development/app-dir/special-project-paths/special-project-paths.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'test/development/app-dir/special-project-paths/special-project-paths.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/development/app-dir/special-project-paths/special-project-paths.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/test/development/app-dir/special-project-paths/special-project-paths.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'pnpm build && pnpm --dir packages/next-swc build-native && pnpm test-dev-turbo '"'"'test/development/app-dir/special-project-paths/special-project-paths.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm build && pnpm --dir packages/next-swc build-native && pnpm test-dev-turbo '"'"'test/development/app-dir/special-project-paths/special-project-paths.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'true'; then + pass_to_pass_exit_code=0 + pass_to_pass=1 + else + pass_to_pass_exit_code=$? + fi + rm -rf "$verifier_cache" +fi + +reward=0 +if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi +cat > /logs/verifier/reward.json < { +- const tracer = originalGetTracer.apply(provider, args) +- if (WeakTracers.has(tracer)) { +- return tracer +- } +- const originalStartSpan = tracer.startSpan +- tracer.startSpan = (...startSpanArgs) => { +- return workUnitAsyncStorage.exit(() => +- originalStartSpan.apply(tracer, startSpanArgs) +- ) ++ return instrumentTracerForCacheComponents( ++ originalGetTracer.apply(provider, args) ++ ) ++ } ++ ++ // Tracers acquired before registration can use getDelegateTracer() from the ++ // proxy provider to get a tracer from the registered provider, bypassing the ++ // getTracer() patch above. This can be problematic when third-party ++ // instrumentation creates spans that call dynamic APIs like Math.random(), ++ // causing a prerendering error. Therefore, patch getDelegateTracer() to apply ++ // the same tracer instrumentation as getTracer(). ++ if (isProxyTracerProvider(provider)) { ++ const originalGetDelegateTracer = provider.getDelegateTracer.bind(provider) ++ provider.getDelegateTracer = (...args) => { ++ const tracer = originalGetDelegateTracer(...args) ++ return tracer === undefined ++ ? undefined ++ : instrumentTracerForCacheComponents(tracer) + } ++ } ++} + +- const originalStartActiveSpan = tracer.startActiveSpan +- // @ts-ignore TS doesn't recognize the overloads correctly +- tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => { +- const workUnitStore = workUnitAsyncStorage.getStore() +- if (!workUnitStore) { +- // @ts-ignore TS doesn't recognize the overloads correctly +- return originalStartActiveSpan.apply(tracer, startActiveSpanArgs) +- } ++function instrumentTracerForCacheComponents(tracer: Tracer): Tracer { ++ if (WeakTracers.has(tracer)) { ++ return tracer ++ } ++ const originalStartSpan = tracer.startSpan ++ tracer.startSpan = (...startSpanArgs) => { ++ return workUnitAsyncStorage.exit(() => ++ originalStartSpan.apply(tracer, startSpanArgs) ++ ) ++ } + +- let fnIdx: number = 0 +- if ( +- startActiveSpanArgs.length === 2 && +- typeof startActiveSpanArgs[1] === 'function' +- ) { +- fnIdx = 1 +- } else if ( +- startActiveSpanArgs.length === 3 && +- typeof startActiveSpanArgs[2] === 'function' +- ) { +- fnIdx = 2 +- } else if ( +- startActiveSpanArgs.length > 3 && +- typeof startActiveSpanArgs[3] === 'function' +- ) { +- fnIdx = 3 +- } ++ const originalStartActiveSpan = tracer.startActiveSpan ++ // @ts-ignore TS doesn't recognize the overloads correctly ++ tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => { ++ const workUnitStore = workUnitAsyncStorage.getStore() ++ if (!workUnitStore) { ++ // @ts-ignore TS doesn't recognize the overloads correctly ++ return originalStartActiveSpan.apply(tracer, startActiveSpanArgs) ++ } + +- if (fnIdx) { +- const originalFn = startActiveSpanArgs[fnIdx] +- if (isUseCacheFunction(originalFn)) { +- console.error( +- 'A Cache Function (`use cache`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.' +- ) +- } +- startActiveSpanArgs[fnIdx] = withWorkUnitContext( +- workUnitStore, +- originalFn ++ let fnIdx: number = 0 ++ if ( ++ startActiveSpanArgs.length === 2 && ++ typeof startActiveSpanArgs[1] === 'function' ++ ) { ++ fnIdx = 1 ++ } else if ( ++ startActiveSpanArgs.length === 3 && ++ typeof startActiveSpanArgs[2] === 'function' ++ ) { ++ fnIdx = 2 ++ } else if ( ++ startActiveSpanArgs.length > 3 && ++ typeof startActiveSpanArgs[3] === 'function' ++ ) { ++ fnIdx = 3 ++ } ++ ++ if (fnIdx) { ++ const originalFn = startActiveSpanArgs[fnIdx] ++ if (isUseCacheFunction(originalFn)) { ++ console.error( ++ 'A Cache Function (`use cache`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.' + ) + } +- +- return workUnitAsyncStorage.exit(() => { +- // @ts-ignore TS doesn't recognize the overloads correctly +- return originalStartActiveSpan.apply(tracer, startActiveSpanArgs) +- }) ++ startActiveSpanArgs[fnIdx] = withWorkUnitContext( ++ workUnitStore, ++ originalFn ++ ) + } + +- WeakTracers.add(tracer) +- return tracer ++ return workUnitAsyncStorage.exit(() => { ++ // @ts-ignore TS doesn't recognize the overloads correctly ++ return originalStartActiveSpan.apply(tracer, startActiveSpanArgs) ++ }) + } ++ ++ WeakTracers.add(tracer) ++ return tracer + } + + const WeakTracers = new WeakSet() diff --git a/nextjs-early-otel-proxy-tracers/solution/solve.sh b/nextjs-early-otel-proxy-tracers/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-early-otel-proxy-tracers/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +git -C /app apply --binary --whitespace=nowarn /solution/gold.patch diff --git a/nextjs-early-otel-proxy-tracers/tests/Dockerfile b/nextjs-early-otel-proxy-tracers/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..81e249ceb76ad970bf76970c9e958e1eed759918 --- /dev/null +++ b/nextjs-early-otel-proxy-tracers/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium && NEXT_TELEMETRY_DISABLED=1 pnpm build' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-early-otel-proxy-tracers/tests/test.patch b/nextjs-early-otel-proxy-tracers/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..2c78e9bd1a79a7a9234608e9b21f6b56430e3415 --- /dev/null +++ b/nextjs-early-otel-proxy-tracers/tests/test.patch @@ -0,0 +1,157 @@ +diff --git a/test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/early-span/page.tsx b/test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/early-span/page.tsx +new file mode 100644 +index 0000000000..6e63ee216c +--- /dev/null ++++ b/test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/early-span/page.tsx +@@ -0,0 +1,18 @@ ++import { TracedComponentEarlyTracerSpan } from '../../traced-work' ++ ++export function generateStaticParams() { ++ return [{ slug: 'prerendered' }] ++} ++ ++export default async function Page({ ++ params, ++}: { ++ params: Promise<{ slug: string }> ++}) { ++ const { slug } = await params ++ if (slug === 'prerendered') { ++ return null ++ } ++ ++ return ++} +diff --git a/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx b/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx +index 067d6cf484..9c614ed403 100644 +--- a/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx ++++ b/test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx +@@ -1,4 +1,4 @@ +-import { type Span, trace, context } from '@opentelemetry/api' ++import { type Span, type Tracer, trace, context } from '@opentelemetry/api' + import { Suspense } from 'react' + + async function asyncWork() { +@@ -173,6 +173,45 @@ export const TracedComponentActiveSpan = withActiveSpan(async function ( + ) + }) + ++type TestGlobal = typeof globalThis & { ++ __nextTestEarlyTracer?: Tracer ++} ++ ++export async function TracedComponentEarlyTracerSpan() { ++ const tracer = (globalThis as TestGlobal).__nextTestEarlyTracer ++ if (!tracer) { ++ throw new Error( ++ 'Expected instrumentation to register the early tracer before rendering' ++ ) ++ } ++ ++ const span = tracer.startSpan('span-early-manual-span') ++ const ctx = trace.setSpan(context.active(), span) ++ ++ return context.with(ctx, async () => { ++ async function Inner() { ++ const result = await asyncWork() ++ return {result} ++ } ++ return ( ++
    ++

    (Manual Span) Tracer acquired before provider registration

    ++
    ++

    ++ Span Representative{' '} ++ ++ {parseInt(span.spanContext().spanId.slice(10), 16)} ++ ++

    ++ }> ++ ++ ++
    ++
    ++ ) ++ }) ++} ++ + function Loading() { + return loading... + } +diff --git a/test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts b/test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts +index aa5bc5e47b..71207f663a 100644 +--- a/test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts ++++ b/test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts +@@ -367,5 +367,17 @@ describe('cache-components OTEL spans', () => { + expect(t8againValue).not.toEqual(0) + } + }) ++ it('should allow creating Spans from a tracer acquired before provider registration', async () => { ++ const outputIndex = next.cliOutput.length ++ const browser = await next.browser('/novel/early-span') ++ // Guard the reported regression directly: span ID generation must not be treated as dynamic Math.random() access during prerendering. ++ expect( ++ next.cliOutput ++ .slice(outputIndex) ++ .match(/unstable value.*Math\.random\(\).*prerendering/) ++ ).toBeNull() ++ const result = await browser.elementByCss('#t9 .result') ++ expect(await result.textContent()).toEqual('42') ++ }) + } + }) +diff --git a/test/e2e/app-dir/cache-components-allow-otel-spans/instrumentation.node.ts b/test/e2e/app-dir/cache-components-allow-otel-spans/instrumentation.node.ts +index ca202f0d79..e6d7ba2e87 100644 +--- a/test/e2e/app-dir/cache-components-allow-otel-spans/instrumentation.node.ts ++++ b/test/e2e/app-dir/cache-components-allow-otel-spans/instrumentation.node.ts +@@ -1,8 +1,19 @@ ++import { trace, type Tracer } from '@opentelemetry/api' + import { NodeSDK } from '@opentelemetry/sdk-node' + import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http' + import { HttpInstrumentation } from '@opentelemetry/instrumentation-http' + import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express' + ++type TestGlobal = typeof globalThis & { ++ __nextTestEarlyTracer?: Tracer ++} ++ ++// Acquire this before sdk.start() to reproduce how instrumentation libraries ++// receive a ProxyTracer before the real provider is registered. ++;(globalThis as TestGlobal).__nextTestEarlyTracer ??= trace.getTracer( ++ 'next-test-early-tracer' ++) ++ + const sdk = new NodeSDK({ + serviceName: 'nextjs-otel-app', + traceExporter: new OTLPTraceExporter({ +diff --git a/test/e2e/app-dir/cache-components-allow-otel-spans/package.json b/test/e2e/app-dir/cache-components-allow-otel-spans/package.json +index ff5e809b1c..169a8373b7 100644 +--- a/test/e2e/app-dir/cache-components-allow-otel-spans/package.json ++++ b/test/e2e/app-dir/cache-components-allow-otel-spans/package.json +@@ -1,14 +1,16 @@ + { + "dependencies": { +- "@opentelemetry/api": "^1.9.0", +- "@opentelemetry/auto-instrumentations-node": "^0.62.0", +- "@opentelemetry/exporter-jaeger": "^2.0.1", +- "@opentelemetry/exporter-trace-otlp-http": "^0.203.0", +- "@opentelemetry/instrumentation-express": "^0.52.0", +- "@opentelemetry/instrumentation-http": "^0.203.0", +- "@opentelemetry/resources": "^2.0.1", +- "@opentelemetry/sdk-node": "^0.203.0", +- "@opentelemetry/semantic-conventions": "^1.36.0", +- "@opentelemetry/winston-transport": "^0.14.0" ++ "@opentelemetry/api": "1.9.0", ++ "@opentelemetry/auto-instrumentations-node": "0.62.0", ++ "@opentelemetry/exporter-jaeger": "2.0.1", ++ "@opentelemetry/exporter-trace-otlp-http": "0.203.0", ++ "@opentelemetry/instrumentation-express": "0.52.0", ++ "@opentelemetry/instrumentation-http": "0.203.0", ++ "@opentelemetry/resources": "2.0.1", ++ "@opentelemetry/sdk-node": "0.203.0", ++ "@opentelemetry/semantic-conventions": "1.36.0", ++ "@opentelemetry/winston-transport": "0.14.0", ++ "typescript": "6.0.2", ++ "@types/node": "20.17.6" + } + } diff --git a/nextjs-early-otel-proxy-tracers/tests/test.sh b/nextjs-early-otel-proxy-tracers/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..64bb6db233d945f2a1369e70334f3d1ab3ffea7d --- /dev/null +++ b/nextjs-early-otel-proxy-tracers/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/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts' --exclude='test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.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/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.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/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'NEXT_TELEMETRY_DISABLED=1 pnpm --filter next build && NEXT_TELEMETRY_DISABLED=1 NEXT_TEST_PREFER_OFFLINE=1 pnpm test-start '"'"'test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'NEXT_TELEMETRY_DISABLED=1 pnpm --filter next build && NEXT_TELEMETRY_DISABLED=1 NEXT_TEST_PREFER_OFFLINE=1 pnpm test-start '"'"'test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.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 < bodySizeLimitBytes) { ++ const { ApiError } = ++ require('../api-utils') as typeof import('../api-utils') ++ throw new ApiError( ++ 413, ++ `Body exceeded ${bodySizeLimit} limit.\n` + ++ `To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit` ++ ) ++ } ++ edgeChunks.push(value) ++ } ++ // Reconstruct a Blob from the buffered chunks and parse formData from it. ++ // Note: we must pass the original Content-Type as an explicit header ++ // rather than relying on the Blob's `type`. The Blob constructor ++ // normalizes `type` to ASCII lowercase per the File API spec, which ++ // would lowercase the multipart boundary parameter (e.g. ++ // `boundary=----WebKitFormBoundaryAbCdEf`). The body bytes contain the ++ // original mixed-case boundary delimiter, so a lowercased boundary ++ // would fail to match and `formData()` would throw. An explicit header ++ // on the Request takes precedence over the Blob's normalized type. ++ const edgeBodyBlob = new Blob(edgeChunks as BlobPart[]) ++ const formData = await new Request('http://n/', { ++ method: 'POST', ++ headers: { 'content-type': req.headers['content-type'] ?? '' }, ++ body: edgeBodyBlob, ++ }).formData() + if (isFetchAction) { + // A fetch action with a multipart body. + +@@ -882,6 +925,7 @@ export async function handleAction({ + // which can happen for very simple JSON-like values that don't need multiple flight rows. + + const chunks: Buffer[] = [] ++ let nonMultipartBodySize = 0 + const reader = req.body.getReader() + while (true) { + const { done, value } = await reader.read() +@@ -889,6 +933,16 @@ export async function handleAction({ + break + } + ++ nonMultipartBodySize += value.byteLength ++ if (nonMultipartBodySize > bodySizeLimitBytes) { ++ const { ApiError } = ++ require('../api-utils') as typeof import('../api-utils') ++ throw new ApiError( ++ 413, ++ `Body exceeded ${bodySizeLimit} limit.\n` + ++ `To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit` ++ ) ++ } + chunks.push(value) + } + +@@ -931,16 +985,6 @@ export async function handleAction({ + ? Readable.from(actionBodyFromMeta) + : req.body + +- const defaultBodySizeLimit = '1 MB' +- const bodySizeLimit = +- serverActions?.bodySizeLimit ?? defaultBodySizeLimit +- const bodySizeLimitBytes = +- bodySizeLimit !== defaultBodySizeLimit +- ? ( +- require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes') +- ).parse(bodySizeLimit) +- : 1024 * 1024 // 1 MB +- + let size = 0 + const sizeLimitTransform = new Transform({ + transform(chunk, encoding, callback) { diff --git a/nextjs-edge-action-body-size-limit/solution/solve.sh b/nextjs-edge-action-body-size-limit/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-edge-action-body-size-limit/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-edge-action-body-size-limit/tests/Dockerfile b/nextjs-edge-action-body-size-limit/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b09554c83b17bd2ed69746f220de4fb96a44aabf --- /dev/null +++ b/nextjs-edge-action-body-size-limit/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium && 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-edge-action-body-size-limit/tests/test.patch b/nextjs-edge-action-body-size-limit/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..1ebf4f0a10ad2937ff560b8e7580adca1717584b --- /dev/null +++ b/nextjs-edge-action-body-size-limit/tests/test.patch @@ -0,0 +1,153 @@ +diff --git a/test/e2e/app-dir/edge-action-body-size-limit/app/error.js b/test/e2e/app-dir/edge-action-body-size-limit/app/error.js +new file mode 100644 +index 0000000000..1b84de9e68 +--- /dev/null ++++ b/test/e2e/app-dir/edge-action-body-size-limit/app/error.js +@@ -0,0 +1,5 @@ ++'use client' ++ ++export default function Error() { ++ return

    The action was rejected.

    ++} +diff --git a/test/e2e/app-dir/edge-action-body-size-limit/app/layout.js b/test/e2e/app-dir/edge-action-body-size-limit/app/layout.js +new file mode 100644 +index 0000000000..803f17d863 +--- /dev/null ++++ b/test/e2e/app-dir/edge-action-body-size-limit/app/layout.js +@@ -0,0 +1,7 @@ ++export default function RootLayout({ children }) { ++ return ( ++ ++ {children} ++ ++ ) ++} +diff --git a/test/e2e/app-dir/edge-action-body-size-limit/app/multipart/page.js b/test/e2e/app-dir/edge-action-body-size-limit/app/multipart/page.js +new file mode 100644 +index 0000000000..581be94ed7 +--- /dev/null ++++ b/test/e2e/app-dir/edge-action-body-size-limit/app/multipart/page.js +@@ -0,0 +1,28 @@ ++export const runtime = 'edge' ++ ++async function action(formData) { ++ 'use server' ++ return formData.get('payload').length ++} ++ ++function Form({ id, megabytes }) { ++ return ( ++
    ++ ++ ++
    ++ ) ++} ++ ++export default function Page() { ++ return ( ++ <> ++
    ++ ++ ++ ) ++} +diff --git a/test/e2e/app-dir/edge-action-body-size-limit/app/plain/form.js b/test/e2e/app-dir/edge-action-body-size-limit/app/plain/form.js +new file mode 100644 +index 0000000000..a62274b242 +--- /dev/null ++++ b/test/e2e/app-dir/edge-action-body-size-limit/app/plain/form.js +@@ -0,0 +1,21 @@ ++'use client' ++ ++import { useActionState } from 'react' ++ ++const payload = (megabytes) => 'a'.repeat(megabytes * 1024 * 1024) ++ ++export default function Form({ action }) { ++ const [, submitUnderLimit] = useActionState(() => action(payload(1)), null) ++ const [, submitOverLimit] = useActionState(() => action(payload(3)), null) ++ ++ return ( ++ <> ++ ++ ++ ++ ) ++} +diff --git a/test/e2e/app-dir/edge-action-body-size-limit/app/plain/page.js b/test/e2e/app-dir/edge-action-body-size-limit/app/plain/page.js +new file mode 100644 +index 0000000000..52dd810322 +--- /dev/null ++++ b/test/e2e/app-dir/edge-action-body-size-limit/app/plain/page.js +@@ -0,0 +1,12 @@ ++import Form from './form' ++ ++export const runtime = 'edge' ++ ++async function action(payload) { ++ 'use server' ++ return payload.length ++} ++ ++export default function Page() { ++ return ++} +diff --git a/test/e2e/app-dir/edge-action-body-size-limit/edge-action-body-size-limit.test.ts b/test/e2e/app-dir/edge-action-body-size-limit/edge-action-body-size-limit.test.ts +new file mode 100644 +index 0000000000..9d6424da50 +--- /dev/null ++++ b/test/e2e/app-dir/edge-action-body-size-limit/edge-action-body-size-limit.test.ts +@@ -0,0 +1,32 @@ ++import { nextTestSetup } from 'e2e-utils' ++import { createRequestTracker } from 'e2e-utils/request-tracker' ++ ++describe('Server Action body size limits in the Edge runtime', () => { ++ const { next } = nextTestSetup({ ++ files: __dirname, ++ skipDeployment: true, ++ }) ++ ++ async function submit(route: string, button: string) { ++ const browser = await next.browser(route) ++ const requestTracker = createRequestTracker(browser) ++ const [, response] = await requestTracker.captureResponse( ++ () => browser.elementByCss(button).click(), ++ { request: { method: 'POST', pathname: route } } ++ ) ++ return response.status() ++ } ++ ++ describe.each([ ++ ['non-multipart', '/plain'], ++ ['multipart', '/multipart'], ++ ])('%s actions', (_encoding, route) => { ++ it('accepts a request below the configured limit', async () => { ++ expect(await submit(route, '#under-limit')).toBe(200) ++ }) ++ ++ it('rejects a request above the configured limit', async () => { ++ expect(await submit(route, '#over-limit')).toBeGreaterThanOrEqual(400) ++ }) ++ }) ++}) +diff --git a/test/e2e/app-dir/edge-action-body-size-limit/next.config.js b/test/e2e/app-dir/edge-action-body-size-limit/next.config.js +new file mode 100644 +index 0000000000..e47fe521c0 +--- /dev/null ++++ b/test/e2e/app-dir/edge-action-body-size-limit/next.config.js +@@ -0,0 +1,6 @@ ++/** @type {import('next').NextConfig} */ ++module.exports = { ++ experimental: { ++ serverActions: { bodySizeLimit: '2mb' }, ++ }, ++} diff --git a/nextjs-edge-action-body-size-limit/tests/test.sh b/nextjs-edge-action-body-size-limit/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..801d4cd33c21a12b001a4cb1be40fc105c7e8868 --- /dev/null +++ b/nextjs-edge-action-body-size-limit/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/edge-action-body-size-limit/edge-action-body-size-limit.test.ts' --exclude='test/e2e/app-dir/edge-action-body-size-limit/edge-action-body-size-limit.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/edge-action-body-size-limit/edge-action-body-size-limit.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/edge-action-body-size-limit/edge-action-body-size-limit.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/edge-action-body-size-limit/edge-action-body-size-limit.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-webpack '"'"'test/e2e/app-dir/edge-action-body-size-limit/edge-action-body-size-limit.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm --filter next build && pnpm test-dev-webpack '"'"'test/e2e/app-dir/edge-action-body-size-limit/edge-action-body-size-limit.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 <, + parentParams: Params, + rootParamKeys: readonly string[], +@@ -622,9 +630,27 @@ async function callGenerateStaticParams( + rootParams, + } + +- return workUnitAsyncStorage.run(workUnitStore, generateStaticParams, { +- params: parentParams, +- }) ++ const generatedParams: unknown = await workUnitAsyncStorage.run( ++ workUnitStore, ++ generateStaticParams, ++ { params: parentParams } ++ ) ++ ++ if (!Array.isArray(generatedParams)) { ++ throw new Error( ++ `Invalid value returned from generateStaticParams for "${page}". Expected an array, but received type ${getValueType(generatedParams)}. See more info here: https://nextjs.org/docs/messages/generate-static-params` ++ ) ++ } ++ ++ for (const [index, params] of generatedParams.entries()) { ++ if (!isPlainObject(params)) { ++ throw new Error( ++ `Invalid value at index ${index} returned from generateStaticParams for "${page}". Expected an object, but received type ${getValueType(params)}. See more info here: https://nextjs.org/docs/messages/generate-static-params` ++ ) ++ } ++ } ++ ++ return generatedParams + } + + /** +@@ -695,6 +721,7 @@ export async function generateRouteStaticParams( + // Process each parent parameter combination + for (const parentParams of params) { + const result = await callGenerateStaticParams( ++ store.page, + current.generateStaticParams, + parentParams, + rootParamKeys, +@@ -716,6 +743,7 @@ export async function generateRouteStaticParams( + } else { + // No parent params, call generateStaticParams with empty object + const result = await callGenerateStaticParams( ++ store.page, + current.generateStaticParams, + {}, + rootParamKeys, diff --git a/nextjs-generate-static-params-validation/solution/solve.sh b/nextjs-generate-static-params-validation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-generate-static-params-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-generate-static-params-validation/tests/Dockerfile b/nextjs-generate-static-params-validation/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..00d506765b9d7520025e3d2032dbf462683bb865 --- /dev/null +++ b/nextjs-generate-static-params-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 'corepack enable && corepack prepare pnpm@10.33.0 --activate && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-generate-static-params-validation/tests/test.patch b/nextjs-generate-static-params-validation/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..e687b10636999dcc4385060958902c9991cc90f6 --- /dev/null +++ b/nextjs-generate-static-params-validation/tests/test.patch @@ -0,0 +1,174 @@ +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js +new file mode 100644 +index 00000000..425b4fe5 +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js +@@ -0,0 +1,7 @@ ++export function generateStaticParams() { ++ return [{}] ++} ++ ++export default function Page() { ++ return

    empty object

    ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js +new file mode 100644 +index 00000000..750eb927 +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js +@@ -0,0 +1,7 @@ ++export default function Layout({ children }) { ++ return ( ++ ++ {children} ++ ++ ) ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js +new file mode 100644 +index 00000000..7cbbd64c +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js +@@ -0,0 +1,7 @@ ++export function generateStaticParams() { ++ return { slug: 'first' } ++} ++ ++export default function Page() { ++ return

    non-array

    ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js +new file mode 100644 +index 00000000..750eb927 +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js +@@ -0,0 +1,7 @@ ++export default function Layout({ children }) { ++ return ( ++ ++ {children} ++ ++ ) ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js +new file mode 100644 +index 00000000..26be227b +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js +@@ -0,0 +1,7 @@ ++export function generateStaticParams() { ++ return [null] ++} ++ ++export default function Page() { ++ return

    non-object entry

    ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js +new file mode 100644 +index 00000000..750eb927 +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js +@@ -0,0 +1,7 @@ ++export default function Layout({ children }) { ++ return ( ++ ++ {children} ++ ++ ) ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js +new file mode 100644 +index 00000000..f9ef3566 +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js +@@ -0,0 +1,7 @@ ++export function generateStaticParams() { ++ return ['first'] ++} ++ ++export default function Page() { ++ return

    primitive entry

    ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js b/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js +new file mode 100644 +index 00000000..750eb927 +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js +@@ -0,0 +1,7 @@ ++export default function Layout({ children }) { ++ return ( ++ ++ {children} ++ ++ ) ++} +diff --git a/test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.test.ts b/test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.test.ts +new file mode 100644 +index 00000000..90dc0f1d +--- /dev/null ++++ b/test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.test.ts +@@ -0,0 +1,64 @@ ++import { generateRouteStaticParams } from '../../../../packages/next/src/build/static-paths/app' ++import { generateStaticParams as emptyObjectParams } from './fixtures/empty-object/app/[[...slug]]/page' ++import { generateStaticParams as nonArrayParams } from './fixtures/non-array/app/[slug]/page' ++import { generateStaticParams as nonObjectEntryParams } from './fixtures/non-object-entry/app/[slug]/page' ++import { generateStaticParams as primitiveEntryParams } from './fixtures/primitive-entry/app/[slug]/page' ++ ++async function callGenerateStaticParams(generateStaticParams: () => unknown) { ++ return generateRouteStaticParams( ++ [ ++ { ++ config: undefined, ++ generateStaticParams: generateStaticParams as never, ++ createEmptyParamsError: undefined, ++ }, ++ ], ++ { fetchCache: undefined, page: '/[slug]' }, ++ false, ++ [] ++ ) ++} ++ ++async function expectInvalidShape( ++ generateStaticParams: () => unknown, ++ expectedShape: 'array' | 'object' ++) { ++ try { ++ await callGenerateStaticParams(generateStaticParams) ++ } catch (error) { ++ expect(error).toBeInstanceOf(Error) ++ expect((error as Error).message).toMatch(/generateStaticParams/i) ++ expect((error as Error).message).toMatch(new RegExp(expectedShape, 'i')) ++ return ++ } ++ ++ throw new Error( ++ `Expected generateStaticParams to reject a non-${expectedShape}` ++ ) ++} ++ ++describe('generateStaticParams return value validation', () => { ++ it.each([ ++ ['object', nonArrayParams], ++ ['null', () => null], ++ ['primitive', () => 'slug'], ++ ])( ++ 'rejects the %s return value instead of an array', ++ async (_description, generateStaticParams) => { ++ await expectInvalidShape(generateStaticParams, 'array') ++ } ++ ) ++ ++ it.each([ ++ ['null', nonObjectEntryParams], ++ ['primitive', primitiveEntryParams], ++ ])('rejects a %s array entry', async (_description, generateStaticParams) => { ++ await expectInvalidShape(generateStaticParams, 'object') ++ }) ++ ++ it('continues to accept an empty parameter object', async () => { ++ await expect(callGenerateStaticParams(emptyObjectParams)).resolves.toEqual([ ++ {}, ++ ]) ++ }) ++}) diff --git a/nextjs-generate-static-params-validation/tests/test.sh b/nextjs-generate-static-params-validation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a4c838b1bd9bd34fe2d1511bc69ccb6cc56204d3 --- /dev/null +++ b/nextjs-generate-static-params-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/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js' --exclude='test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js/*' --exclude='test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.test.ts' --exclude='test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.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/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js' 'test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js' 'test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.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/generate-static-params-invalid/fixtures/empty-object/app/[[...slug]]/page.js' '/app/test/e2e/app-dir/generate-static-params-invalid/fixtures/empty-object/app/layout.js' '/app/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/[slug]/page.js' '/app/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-array/app/layout.js' '/app/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/[slug]/page.js' '/app/test/e2e/app-dir/generate-static-params-invalid/fixtures/non-object-entry/app/layout.js' '/app/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/[slug]/page.js' '/app/test/e2e/app-dir/generate-static-params-invalid/fixtures/primitive-entry/app/layout.js' '/app/test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'pnpm test-start-webpack '"'"'test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm test-start-webpack '"'"'test/e2e/app-dir/generate-static-params-invalid/generate-static-params-invalid.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 < { + expect(await fetchedData.textContent()).toContain('api response') + }) + ++ if (isNextDev) { ++ it('lets dev-server requests through during instant scope', async () => { ++ const page = await openPage(next, '/') ++ ++ await instant(page, async () => { ++ await page.click('#link-to-client-fetch') ++ ++ // The out-of-band fetch to /api/data is blocked by the lock ++ const loading = page.locator('[data-testid="fetched-data-loading"]') ++ await loading.waitFor({ state: 'visible' }) ++ ++ // But dev-server requests (hot-reloader middleware endpoints like the ++ // error overlay and source maps) bypass the lock and resolve while the ++ // scope is still active. Without the bypass this evaluate would hang ++ // until the scope ends. ++ const status = await page.evaluate(() => ++ fetch('/__nextjs_server_status').then((res) => res.status) ++ ) ++ expect(status).toBe(200) ++ ++ // The blocked fetch still hasn't resolved ++ const fetchedData = page.locator('[data-testid="fetched-data"]') ++ expect(await fetchedData.count()).toBe(0) ++ }) ++ }) ++ } ++ + it('clears cookie even when callback throws', async () => { + const page = await openPage(next, '/') + diff --git a/nextjs-instant-dev-fetch-lock/tests/test.sh b/nextjs-instant-dev-fetch-lock/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f2a06955c36a50cac1069454e0dfe2a76e7c784 --- /dev/null +++ b/nextjs-instant-dev-fetch-lock/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/instant-navigation-testing-api/instant-navigation-testing-api.test.ts' --exclude='test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.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/instant-navigation-testing-api/instant-navigation-testing-api.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.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/instant-navigation-testing-api/instant-navigation-testing-api.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-webpack '"'"'test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts'"'"' --testNamePattern='"'"'lets dev-server requests through during instant scope'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm build && pnpm test-dev-webpack '"'"'test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts'"'"' --testNamePattern='"'"'lets dev-server requests through during instant scope'"'"''; 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 < Some(lightningcss::css_modules::Config { + pattern: Pattern { diff --git a/nextjs-lightningcss-custom-media/solution/solve.sh b/nextjs-lightningcss-custom-media/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-lightningcss-custom-media/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-lightningcss-custom-media/tests/Dockerfile b/nextjs-lightningcss-custom-media/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..80903f5efe4c35d8b5bc80453b908548dfb89276 --- /dev/null +++ b/nextjs-lightningcss-custom-media/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' \ + && 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-lightningcss-custom-media/tests/test.patch b/nextjs-lightningcss-custom-media/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..2bd6bbd1ee930ac416bc1c951a792d472654c5d2 --- /dev/null +++ b/nextjs-lightningcss-custom-media/tests/test.patch @@ -0,0 +1,81 @@ +diff --git a/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css b/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css +new file mode 100644 +index 00000000..743b745f +--- /dev/null ++++ b/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css +@@ -0,0 +1,11 @@ ++@custom-media --narrow (max-width: 960px); ++ ++.box { ++ color: blue; ++} ++ ++@media (--narrow) { ++ .box { ++ color: red; ++ } ++} +diff --git a/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx b/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx +new file mode 100644 +index 00000000..f4949f6d +--- /dev/null ++++ b/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx +@@ -0,0 +1,5 @@ ++import styles from './page.module.css' ++ ++export default function Page() { ++ return
    Custom media
    ++} +diff --git a/test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts b/test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts +index ec5ec389..8173b8b6 100644 +--- a/test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts ++++ b/test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts +@@ -23,7 +23,7 @@ describe('experimental-lightningcss-features', () => { + describe('include', () => { + const { next } = nextTestSetup({ + files: __dirname, +- dependencies: { lightningcss: '^1.23.0' }, ++ dependencies: { lightningcss: '1.33.0' }, + // Chrome 123 supports light-dark() natively — using it here proves that + // the `include` flag forces transpilation regardless of browser support. + packageJson: { +@@ -52,10 +52,38 @@ describe('experimental-lightningcss-features', () => { + }) + }) + ++ describe('custom-media-queries', () => { ++ const { next } = nextTestSetup({ ++ files: __dirname, ++ dependencies: { lightningcss: '1.33.0' }, ++ packageJson: { ++ browserslist: ['chrome 123'], ++ }, ++ nextConfig: { ++ experimental: { ++ useLightningcss: true, ++ lightningCssFeatures: { ++ include: ['custom-media-queries'], ++ }, ++ }, ++ }, ++ }) ++ ++ it('should substitute @custom-media when custom-media-queries is included', async () => { ++ const html = await next.render('/custom-media') ++ expect(html).toContain('Custom media') ++ ++ const css = await collectPageCss(next, '/custom-media') ++ expect(css).not.toContain('@custom-media') ++ expect(css).not.toContain('--narrow') ++ expect(css).toMatch(/max-width:\s*960px|width\s*<=\s*960px/) ++ }) ++ }) ++ + describe('exclude', () => { + const { next } = nextTestSetup({ + files: __dirname, +- dependencies: { lightningcss: '^1.23.0' }, ++ dependencies: { lightningcss: '1.33.0' }, + // Chrome 100 does NOT support light-dark() natively, so lightningcss would + // normally transpile it. Using `exclude: ['light-dark']` should prevent that. + packageJson: { diff --git a/nextjs-lightningcss-custom-media/tests/test.sh b/nextjs-lightningcss-custom-media/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..716f4f5585d223f6280fa1a2cc7ec9bde9fd0d0a --- /dev/null +++ b/nextjs-lightningcss-custom-media/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/experimental-lightningcss-features/experimental-lightningcss-features.test.ts' --exclude='test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts/*' --exclude='test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css' --exclude='test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css/*' --exclude='test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx' --exclude='test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx/*' /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/experimental-lightningcss-features/experimental-lightningcss-features.test.ts' 'test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css' 'test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts' 'test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css' 'test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx' >/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/experimental-lightningcss-features/experimental-lightningcss-features.test.ts' '/app/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.module.css' '/app/test/e2e/app-dir/experimental-lightningcss-features/app/custom-media/page.tsx'; 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-start-webpack '"'"'test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm --filter next build && pnpm test-start-webpack '"'"'test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.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 < +-> & { +- images: Required +- typescript: TypeScriptConfig +- configFile: string | undefined +- configFileName: string +- // Normalized by config.ts: the `default` profile is backfilled to be complete +- // (see `ResolvedCacheLifeProfiles`), unlike the optional/partial user input. +- // Omitted from the base so this is a clean replacement, not an intersection. +- cacheLife: ResolvedCacheLifeProfiles +- // override NextConfigComplete.experimental.htmlLimitedBots to string +- // because it's not defined in NextConfigComplete.experimental +- htmlLimitedBots: string | undefined +- experimental: ExperimentalConfig & { +- // Normalized by config.ts: true and partial objects become resolved objects +- prefetchInlining?: PrefetchInliningConfig +- // Normalized by config.ts: defaulted to 90% of staticPageGenerationTimeout +- useCacheTimeout: number +- // Normalized by config.ts `finalizeConfig`: defaulted to `'warning'` +- instantInsights: { validationLevel: ValidationLevel } +- // Normalized by finalized config with a default and the expected type +- turbopackMemoryEvictionMode: MemoryEvictionMode ++ Omit< ++ NextConfig, ++ | 'configFile' ++ | 'cacheLife' ++ | 'expireTime' ++ | 'output' ++ | 'modularizeImports' ++ | 'allowedDevOrigins' ++ | 'adapterPath' ++ > ++> & ++ // Don't apply `Required<>` for these properties. They really can be undefined in the finalized config. ++ Pick< ++ NextConfig, ++ | 'cacheLife' ++ | 'expireTime' ++ | 'output' ++ | 'modularizeImports' ++ | 'allowedDevOrigins' ++ | 'adapterPath' ++ > & { ++ images: Required ++ typescript: TypeScriptConfig ++ configFile: string | undefined ++ configFileName: string ++ // Normalized by config.ts: the `default` profile is backfilled to be complete ++ // (see `ResolvedCacheLifeProfiles`), unlike the optional/partial user input. ++ // Omitted from the base so this is a clean replacement, not an intersection. ++ cacheLife: ResolvedCacheLifeProfiles ++ // override NextConfigComplete.experimental.htmlLimitedBots to string ++ // because it's not defined in NextConfigComplete.experimental ++ htmlLimitedBots: string | undefined ++ experimental: ExperimentalConfig & { ++ // Normalized by config.ts: true and partial objects become resolved objects ++ prefetchInlining?: PrefetchInliningConfig ++ // Normalized by config.ts: defaulted to 90% of staticPageGenerationTimeout ++ useCacheTimeout: number ++ // Normalized by config.ts `finalizeConfig`: defaulted to `'warning'` ++ instantInsights: { validationLevel: ValidationLevel } ++ // Normalized by finalized config with a default and the expected type ++ turbopackMemoryEvictionMode: MemoryEvictionMode ++ } ++ // The root directory of the distDir. In development mode, this is the parent directory of `distDir` ++ // since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't ++ // traverse into the output directory. ++ distDirRoot: string ++ // The repository root, regardless of overwritten outputFileTracingRoot or turbopack.root. ++ repoRoot: string + } +- // The root directory of the distDir. In development mode, this is the parent directory of `distDir` +- // since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't +- // traverse into the output directory. +- distDirRoot: string +- // The repository root, regardless of overwritten outputFileTracingRoot or turbopack.root. +- repoRoot: string +-} + + export type I18NDomains = readonly DomainLocale[] + +@@ -2294,14 +2313,14 @@ export interface NextConfigRuntime { + agentRules: NextConfigComplete['agentRules'] + htmlLimitedBots: NextConfigComplete['htmlLimitedBots'] + assetPrefix: NextConfigComplete['assetPrefix'] +- output: NextConfigComplete['output'] ++ output?: NextConfigComplete['output'] + crossOrigin: NextConfigComplete['crossOrigin'] + trailingSlash: NextConfigComplete['trailingSlash'] + images: NextConfigComplete['images'] + reactMaxHeadersLength: NextConfigComplete['reactMaxHeadersLength'] + cacheLife: NextConfigComplete['cacheLife'] + basePath: NextConfigComplete['basePath'] +- expireTime: NextConfigComplete['expireTime'] ++ expireTime?: NextConfigComplete['expireTime'] + generateEtags: NextConfigComplete['generateEtags'] + poweredByHeader: NextConfigComplete['poweredByHeader'] + cacheHandler: NextConfigComplete['cacheHandler'] diff --git a/nextjs-next-config-complete-optionality/solution/solve.sh b/nextjs-next-config-complete-optionality/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-next-config-complete-optionality/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-next-config-complete-optionality/tests/Dockerfile b/nextjs-next-config-complete-optionality/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3b384e06f1e83dcfcd491cdec9010fbb2685a0de --- /dev/null +++ b/nextjs-next-config-complete-optionality/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 && NEXT_TELEMETRY_DISABLED=1 pnpm build --filter=next' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-next-config-complete-optionality/tests/test.patch b/nextjs-next-config-complete-optionality/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..eb8980ac18214655bebb86d9daf83e571167cf95 --- /dev/null +++ b/nextjs-next-config-complete-optionality/tests/test.patch @@ -0,0 +1,71 @@ +diff --git a/packages/next/src/server/config-shared-types.test.ts b/packages/next/src/server/config-shared-types.test.ts +new file mode 100644 +index 0000000000..fa5134a42f +--- /dev/null ++++ b/packages/next/src/server/config-shared-types.test.ts +@@ -0,0 +1,65 @@ ++import { spawnSync } from 'node:child_process' ++import path from 'node:path' ++import type { NextConfigComplete } from './config-shared' ++ ++type IsOptional = {} extends Pick ? true : false ++ ++type OptionalConfigKey = ++ | 'expireTime' ++ | 'output' ++ | 'modularizeImports' ++ | 'allowedDevOrigins' ++ | 'adapterPath' ++ ++const optionalConfigKeys: { ++ [K in OptionalConfigKey]: IsOptional ++} = { ++ expireTime: true, ++ output: true, ++ modularizeImports: true, ++ allowedDevOrigins: true, ++ adapterPath: true, ++} ++ ++const normalizedConfigKeys: { ++ [K in 'distDir' | 'images' | 'experimental' | 'cacheLife']: IsOptional< ++ NextConfigComplete, ++ K ++ > ++} = { ++ distDir: false, ++ images: false, ++ experimental: false, ++ cacheLife: false, ++} ++ ++describe('NextConfigComplete type', () => { ++ it('matches the optional and normalized config contract', () => { ++ expect(optionalConfigKeys).toEqual({ ++ expireTime: true, ++ output: true, ++ modularizeImports: true, ++ allowedDevOrigins: true, ++ adapterPath: true, ++ }) ++ expect(normalizedConfigKeys).toEqual({ ++ distDir: false, ++ images: false, ++ experimental: false, ++ cacheLife: false, ++ }) ++ ++ const result = spawnSync( ++ 'pnpm', ++ ['--filter', 'next', 'run', 'typescript'], ++ { ++ cwd: path.resolve(__dirname, '../../../..'), ++ encoding: 'utf8', ++ timeout: 180_000, ++ } ++ ) ++ ++ if (result.error) throw result.error ++ expect(result.status).toBe(0) ++ }, 200_000) ++}) diff --git a/nextjs-next-config-complete-optionality/tests/test.sh b/nextjs-next-config-complete-optionality/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7052aa942fa5155149c1f16ff8b21ec83acc7284 --- /dev/null +++ b/nextjs-next-config-complete-optionality/tests/test.sh @@ -0,0 +1,98 @@ +#!/bin/bash +set -uo pipefail +mkdir -p /logs/verifier +patch_applied=1 +fail_to_pass=0 +pass_to_pass=0 +deterministic=0 +setup_completed=0 +fail_to_pass_exit_code=-1 +fail_to_pass_repeat_exit_code=-1 +pass_to_pass_exit_code=-1 +verifier_cache="" + +kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; } +# Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs), +# so a single registry connection reset must not be misread as a dead test. Retry +# only infrastructure-style failures with backoff; real assertion failures fail fast. +run_verifier_command() { + local logfile + logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)" + local attempt=1 + local status=1 + while [ "$attempt" -le 3 ]; do + : > "$logfile" + runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1 + status=$? + if [ "$status" -eq 0 ]; then + break + fi + if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then + sleep "$((10 * attempt))" + attempt=$((attempt + 1)) + continue + fi + break + done + cat "$logfile" + rm -f "$logfile" + kill_verifier_processes + return "$status" +} +protect_held_out_path() { + local path="$1" + chown -R root:root -- "$path" + chmod -R a-w,go+rX -- "$path" +} + +if [ ! -f /opt/selfbench/agent.patch ]; then + patch_applied=0 +elif [ -s /opt/selfbench/agent.patch ]; then + git -C /app apply --binary --whitespace=nowarn --exclude='packages/next/src/server/config-shared-types.test.ts' --exclude='packages/next/src/server/config-shared-types.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0 +fi + +if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + kill_verifier_processes + git -C /app restore --source=HEAD --staged --worktree -- 'packages/next/src/server/config-shared-types.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'packages/next/src/server/config-shared-types.test.ts' >/dev/null 2>&1 || true + git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0 + if [ "$patch_applied" -eq 1 ]; then + for protected_path in '/app/packages/next/src/server/config-shared-types.test.ts'; do protect_held_out_path "$protected_path"; done + fi + rm -f /tests/test.patch +fi + +if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then + cd '/app/.' + verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)" + cp -a /opt/uv-cache/. "$verifier_cache"/ + chown -R verifier:verifier "$verifier_cache" + if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/server/config-shared-types.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/server/config-shared-types.test.ts'"'"''; then + fail_to_pass_repeat_exit_code=0 + deterministic=1 + else + fail_to_pass_repeat_exit_code=$? + fi + else + fail_to_pass_exit_code=$? + fi + if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/server/app-render/types.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 <(headers, { ++ get(target, prop, receiver) { ++ return ReflectAdapter.get(target, prop, receiver) ++ }, ++ }) ++ } ++ + /** + * Merges a header value into a string. This stores multiple values as an + * array, so we need to merge them into a string. +diff --git a/packages/next/src/server/web/spec-extension/adapters/request-cookies.ts b/packages/next/src/server/web/spec-extension/adapters/request-cookies.ts +index 2120d7e5ab..aaa8488fd5 100644 +--- a/packages/next/src/server/web/spec-extension/adapters/request-cookies.ts ++++ b/packages/next/src/server/web/spec-extension/adapters/request-cookies.ts +@@ -48,6 +48,18 @@ export class RequestCookiesAdapter { + }, + }) + } ++ ++ /** ++ * @param cookies ++ * @returns A fresh object identity backed by the original value ++ */ ++ public static fresh(cookies: ReadonlyRequestCookies): ReadonlyRequestCookies { ++ return new Proxy(cookies, { ++ get(target, prop, receiver) { ++ return ReflectAdapter.get(target, prop, receiver) ++ }, ++ }) ++ } + } + + const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies') diff --git a/nextjs-pr-96085/solution/solve.sh b/nextjs-pr-96085/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-pr-96085/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-96085/tests/Dockerfile b/nextjs-pr-96085/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9c7c844f68862fd99b466d97996ea60fc7c77060 --- /dev/null +++ b/nextjs-pr-96085/tests/Dockerfile @@ -0,0 +1,42 @@ +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive \ + UV_LINK_MODE=copy \ + UV_CACHE_DIR=/opt/uv-cache \ + UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \ + UV_PYTHON_BIN_DIR=/usr/local/bin \ + RUSTUP_HOME=/usr/local/rustup \ + CARGO_HOME=/usr/local/cargo \ + COREPACK_HOME=/opt/corepack \ + PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \ + && rm -rf /var/lib/apt/lists/* +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright +RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \ + && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \ + && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \ + && mkdir -p /opt/corepack && chmod 755 /opt/corepack \ + && corepack enable +COPY repo.tar.gz /tmp/repo.tar.gz +RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \ + && git -C /app init -q \ + && git -C /app config user.email selfbench@local \ + && git -C /app config user.name selfbench \ + && git -C /app add -A \ + && git -C /app commit -qm base +RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \ + && cd '/app/.' \ + && bash -lc 'corepack enable && corepack install && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build && pnpm exec playwright install --with-deps chromium' \ + && chmod -R a+rwX /opt/uv-cache + +RUN useradd --create-home --shell /bin/bash verifier \ + && chown -R verifier:verifier /app /opt/uv-cache \ + && mkdir -p /opt/selfbench \ + && chmod 700 /opt/selfbench \ + && mkdir -p /home/verifier/.cache/uv \ + && chown -R verifier:verifier /home/verifier/.cache +ENV UV_CACHE_DIR=/home/verifier/.cache/uv \ + UV_NO_BUILD_ISOLATION=1 +COPY test.patch test.sh /tests/ +RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh +WORKDIR /app diff --git a/nextjs-pr-96085/tests/test.patch b/nextjs-pr-96085/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..1d80f147fd511dc45116fa2cbdf50b40dfecbafd --- /dev/null +++ b/nextjs-pr-96085/tests/test.patch @@ -0,0 +1,248 @@ +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/error.tsx b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/error.tsx +new file mode 100644 +index 00000000..7d696a30 +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/error.tsx +@@ -0,0 +1,5 @@ ++'use client' ++ ++export default function DynamicError() { ++ return
    Failed to render dynamic content
    ++} +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx +new file mode 100644 +index 00000000..108ce3f0 +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx +@@ -0,0 +1,66 @@ ++import { Suspense } from 'react' ++import { headers } from 'next/headers' ++import { connection } from 'next/server' ++ ++export const instant = { ++ unstable_samples: [{ headers: [['host', 'test-host']] }], ++} ++export const prefetch = 'partial' ++ ++export default function Page() { ++ return ( ++
    ++

    This page gates its dynamic content on connection().

    ++ Loading 1...}> ++ ++ ++
    ++ ) ++} ++ ++async function RuntimePrefetchable() { ++ const headersStore = await headers() ++ const headerValue = headersStore.get('host') === null ? 'missing' : 'present' ++ return ( ++
    ++
    {`Header: ${headerValue}`}
    ++ Loading 2...
    }> ++ ++ ++ ++ ) ++} ++ ++// A module-level cache keyed on the identity of the headers object (like ++// `dedupe()` from the Flags SDK, or any per-request memoization that treats ++// the headers object as "the request"), gating its data on `connection()` so ++// it only produces data during actual navigations, never during (runtime) ++// prefetches. ++// ++// A request can be rendered by multiple passes with different semantics for ++// `connection()`: the prospective and final prerenders of a runtime prefetch, ++// or a navigation's dynamic render and the runtime prerender that is spawned ++// from it to refresh the client's prefetch cache. In prerenders the ++// connection() promise hangs and is rejected when the pass is aborted; during ++// navigations it resolves. Each render pass resolves `await headers()` to a ++// distinct object, which scopes identity-keyed memoization like this cache to ++// a single pass: a promise created under one pass's semantics is never ++// consumed by another pass. ++const requestDataCache = new WeakMap>() ++async function getRequestData(): Promise { ++ const headersStore = await headers() ++ let dataPromise = requestDataCache.get(headersStore) ++ if (dataPromise === undefined) { ++ dataPromise = (async () => { ++ await connection() ++ return 'request data' ++ })() ++ requestDataCache.set(headersStore, dataPromise) ++ } ++ return dataPromise ++} ++ ++async function Dynamic() { ++ const data = await getRequestData() ++ return
    Dynamic content: {data}
    ++} +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx +new file mode 100644 +index 00000000..c36226d9 +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx +@@ -0,0 +1,9 @@ ++import { ReactNode } from 'react' ++ ++export default function RootLayout({ children }: { children: ReactNode }) { ++ return ( ++ ++ {children} ++ ++ ) ++} +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx +new file mode 100644 +index 00000000..ff594c24 +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx +@@ -0,0 +1,14 @@ ++import { LinkAccordion } from '../components/link-accordion' ++ ++export default function Page() { ++ return ( ++
    ++

    Index

    ++
      ++
    • ++ Dynamic page ++
    • ++
    ++
    ++ ) ++} +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx b/test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx +new file mode 100644 +index 00000000..1b57ffef +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx +@@ -0,0 +1,31 @@ ++'use client' ++ ++import Link from 'next/link' ++import { useState } from 'react' ++ ++export function LinkAccordion({ ++ href, ++ children, ++}: { ++ href: string ++ children: React.ReactNode ++}) { ++ const [isVisible, setIsVisible] = useState(false) ++ return ( ++ <> ++ setIsVisible(!isVisible)} ++ data-link-accordion={href} ++ /> ++ {isVisible ? ( ++ ++ {children} ++ ++ ) : ( ++ <>{children} (link is hidden) ++ )} ++ ++ ) ++} +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts b/test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts +new file mode 100644 +index 00000000..dfffdd92 +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts +@@ -0,0 +1,60 @@ ++import { nextTestSetup } from 'e2e-utils' ++import { retry } from 'next-test-utils' ++import type * as Playwright from 'playwright' ++import { createRouterAct } from 'router-act' ++ ++describe('module-level caches keyed on the headers object', () => { ++ const { next, isNextDev } = nextTestSetup({ ++ files: __dirname, ++ }) ++ ++ if (isNextDev) { ++ // Runtime prefetching only happens in production builds. ++ it('is skipped in dev', () => {}) ++ return ++ } ++ ++ it('renders dynamic content on navigation even when the spawned runtime prerender populated the cache first', async () => { ++ const cliOutputStart = next.cliOutput.length ++ ++ let page: Playwright.Page ++ const browser = await next.browser('/', { ++ beforePageLoad(p: Playwright.Page) { ++ page = p ++ }, ++ }) ++ const act = createRouterAct(page) ++ ++ // Reveal the link, triggering the runtime prefetch. ++ await act( ++ async () => { ++ const linkToggle = await browser.elementByCss( ++ 'input[data-link-accordion="/dynamic"]' ++ ) ++ await linkToggle.click() ++ }, ++ { includes: 'Header:' } ++ ) ++ ++ // Navigate. The navigation request also spawns a runtime prerender to ++ // refresh the client's prefetch cache, which reaches the module-level ++ // cache before the stage-gated dynamic render of the navigation does. ++ // Because each render pass resolves `headers()` to a distinct object, the ++ // hanging connection() promise it memoizes is keyed to the prerender pass ++ // only: the navigation's dynamic render misses the cache, creates its own ++ // promise, and connection() resolves, so the dynamic content renders. ++ await browser.elementByCss('a[href="/dynamic"]').click() ++ ++ await retry(async () => { ++ expect(await browser.elementById('dynamic-content').text()).toBe( ++ 'Dynamic content: request data' ++ ) ++ }) ++ expect(await browser.hasElementByCssSelector('#dynamic-error')).toBe(false) ++ ++ // The rejection of the prerender pass's hanging promise stays within the ++ // pass that created it, so nothing is reported to onRequestError either. ++ const cliOutput = next.cliOutput.slice(cliOutputStart) ++ expect(cliOutput).not.toContain('[instrumentation] onRequestError:') ++ }) ++}) +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts b/test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts +new file mode 100644 +index 00000000..a4eaac62 +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts +@@ -0,0 +1,5 @@ ++import { type Instrumentation } from 'next' ++ ++export const onRequestError: Instrumentation.onRequestError = (err) => { ++ console.log(`[instrumentation] onRequestError:${(err as Error).message}`) ++} +diff --git a/test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.ts b/test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.ts +new file mode 100644 +index 00000000..c7ffd9f8 +--- /dev/null ++++ b/test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.ts +@@ -0,0 +1,10 @@ ++import type { NextConfig } from 'next' ++ ++const nextConfig: NextConfig = { ++ cacheComponents: true, ++ experimental: { ++ cachedNavigations: true, ++ }, ++} ++ ++export default nextConfig diff --git a/nextjs-pr-96085/tests/test.sh b/nextjs-pr-96085/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..73b69e467910411465fc5bb9002132b8390ca100 --- /dev/null +++ b/nextjs-pr-96085/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/segment-cache/headers-keyed-caches/app/dynamic/error.tsx' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/error.tsx/*' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx/*' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx/*' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx/*' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx/*' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts/*' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts/*' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.ts' --exclude='test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.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/segment-cache/headers-keyed-caches/app/dynamic/error.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/error.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts' 'test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.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/segment-cache/headers-keyed-caches/app/dynamic/error.tsx' '/app/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/dynamic/page.tsx' '/app/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/layout.tsx' '/app/test/e2e/app-dir/segment-cache/headers-keyed-caches/app/page.tsx' '/app/test/e2e/app-dir/segment-cache/headers-keyed-caches/components/link-accordion.tsx' '/app/test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts' '/app/test/e2e/app-dir/segment-cache/headers-keyed-caches/instrumentation.ts' '/app/test/e2e/app-dir/segment-cache/headers-keyed-caches/next.config.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-start-turbo '"'"'test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm --filter next build && pnpm test-start-turbo '"'"'test/e2e/app-dir/segment-cache/headers-keyed-caches/headers-keyed-caches.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-start-turbo '"'"'test/e2e/app-dir/segment-cache/dynamic-on-hover/dynamic-on-hover.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 { next } = nextTestSetup({ + files: __dirname, + dependencies: { + nanoid: '4.0.1', +- 'server-only': 'latest', ++ 'server-only': '0.0.1', + }, + }) + + it('should support formData and redirect without JS', async () => { +- let responseCode: number | undefined ++ let actionResponse: Response | undefined + const browser = await next.browser('/server', { + disableJavaScript: true, + beforePageLoad(page) { + page.on('response', (response) => { + const url = new URL(response.url()) +- const status = response.status() +- if (url.pathname.includes('/server')) { +- responseCode = status ++ if ( ++ url.pathname === '/server' && ++ response.request().method() === 'POST' ++ ) { ++ actionResponse = response + } + }) + }, +@@ -34,7 +37,10 @@ describe('app-dir action progressive enhancement', () => { + ) + }) + +- expect(responseCode).toBe(303) ++ expect(actionResponse).toBeDefined() ++ expect(actionResponse!.status()).toBe(303) ++ const headers = await actionResponse!.allHeaders() ++ expect(headers.location).toBe('/header?name=test&hidden-info=hi') + }) + + it('should support actions from client without JS', async () => { +diff --git a/test/e2e/app-dir/app-basepath/index.test.ts b/test/e2e/app-dir/app-basepath/index.test.ts +index 736b6688..466a1865 100644 +--- a/test/e2e/app-dir/app-basepath/index.test.ts ++++ b/test/e2e/app-dir/app-basepath/index.test.ts +@@ -6,7 +6,7 @@ describe('app dir - basepath', () => { + const { next, isNextDev } = nextTestSetup({ + files: __dirname, + dependencies: { +- sass: 'latest', ++ sass: '1.54.0', + }, + }) + +@@ -156,7 +156,12 @@ describe('app dir - basepath', () => { + + expect(request.url()).toEqual(`${next.url}${initialPagePath}`) + expect(request.method()).toEqual('POST') +- expect(response.status()).toEqual(303) ++ expect(response.status()).toEqual(200) ++ ++ const headers = await response.allHeaders() ++ expect(headers['x-action-redirect']).toBeDefined() ++ expect(headers.location).toBeUndefined() ++ expect(headers['content-type']).toContain('text/x-component') + } + ) + +@@ -204,7 +209,10 @@ describe('app dir - basepath', () => { + expect(secondRequest.url()).toEqual(`${next.url}${destinationPagePath}`) + expect(secondRequest.method()).toEqual('GET') + +- expect(firstResponse.status()).toEqual(303) ++ expect(firstResponse.status()).toEqual(200) ++ const headers = await firstResponse.allHeaders() ++ expect(headers['x-action-redirect']).toBeDefined() ++ expect(headers.location).toBeUndefined() + // Since this is an external request to a resource outside of NextJS + // we expect to see a separate request resolving the external URL. + expect(secondResponse.status()).toEqual(200) diff --git a/nextjs-server-action-client-redirect-status/tests/test.sh b/nextjs-server-action-client-redirect-status/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cc76c600d474fb4f3769831f271ea7cf9fbbc88f --- /dev/null +++ b/nextjs-server-action-client-redirect-status/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/app-basepath/index.test.ts' --exclude='test/e2e/app-dir/app-basepath/index.test.ts/*' --exclude='test/e2e/app-dir/actions/app-action-progressive-enhancement.test.ts' --exclude='test/e2e/app-dir/actions/app-action-progressive-enhancement.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/app-basepath/index.test.ts' 'test/e2e/app-dir/actions/app-action-progressive-enhancement.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/app-basepath/index.test.ts' 'test/e2e/app-dir/actions/app-action-progressive-enhancement.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/app-basepath/index.test.ts' '/app/test/e2e/app-dir/actions/app-action-progressive-enhancement.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-turbo '"'"'test/e2e/app-dir/app-basepath/index.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'pnpm --filter next build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/app-basepath/index.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-turbo '"'"'test/e2e/app-dir/actions/app-action-progressive-enhancement.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 <, + worker_threads: Option, + +- turbopack_minify: Option, ++ turbopack_minify: Option, + turbopack_module_ids: Option, + turbopack_plugin_runtime_strategy: Option, + turbopack_source_maps: Option, +@@ -1640,6 +1640,47 @@ impl ReactRemoveProperties { + } + } + ++/// `experimental.turbopackMinify`, either a single value for all output or a ++/// per-environment configuration. ++#[derive( ++ Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode, ++)] ++#[serde(untagged)] ++pub enum TurbopackMinify { ++ Boolean(bool), ++ Config { ++ server: Option, ++ client: Option, ++ edge: Option, ++ }, ++} ++ ++impl TurbopackMinify { ++ /// The configured value for browser output. ++ fn client(&self) -> Option { ++ match self { ++ Self::Boolean(enabled) => Some(*enabled), ++ Self::Config { client, .. } => *client, ++ } ++ } ++ ++ /// The configured value for Node.js server output. ++ fn server(&self) -> Option { ++ match self { ++ Self::Boolean(enabled) => Some(*enabled), ++ Self::Config { server, .. } => *server, ++ } ++ } ++ ++ /// The configured value for edge output. ++ fn edge(&self) -> Option { ++ match self { ++ Self::Boolean(enabled) => Some(*enabled), ++ Self::Config { edge, .. } => *edge, ++ } ++ } ++} ++ + #[derive( + Clone, Debug, PartialEq, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Encode, Decode, + )] +@@ -2524,12 +2565,43 @@ impl NextConfig { + }) + } + ++ /// Whether to minify browser output. + #[turbo_tasks::function] +- pub async fn turbo_minify(&self, mode: Vc) -> Result> { +- let minify = self.experimental.turbopack_minify; +- Ok(Vc::cell( +- minify.unwrap_or(matches!(*mode.await?, NextMode::Build)), +- )) ++ pub async fn turbo_client_minify(&self, mode: Vc) -> Result> { ++ let default = matches!(*mode.await?, NextMode::Build); ++ let minify = self ++ .experimental ++ .turbopack_minify ++ .as_ref() ++ .and_then(TurbopackMinify::client); ++ Ok(Vc::cell(minify.unwrap_or(default))) ++ } ++ ++ /// Whether to minify Node.js server output. `turbopackMinify` takes ++ /// precedence over `serverMinification`, which can only opt out. ++ #[turbo_tasks::function] ++ pub async fn turbo_server_minify(&self, mode: Vc) -> Result> { ++ let default = matches!(*mode.await?, NextMode::Build) ++ && self.experimental.server_minification.unwrap_or(true); ++ let minify = self ++ .experimental ++ .turbopack_minify ++ .as_ref() ++ .and_then(TurbopackMinify::server); ++ Ok(Vc::cell(minify.unwrap_or(default))) ++ } ++ ++ /// Whether to minify edge output. `serverMinification` only covers the ++ /// Node.js server, matching webpack. ++ #[turbo_tasks::function] ++ pub async fn turbo_edge_minify(&self, mode: Vc) -> Result> { ++ let default = matches!(*mode.await?, NextMode::Build); ++ let minify = self ++ .experimental ++ .turbopack_minify ++ .as_ref() ++ .and_then(TurbopackMinify::edge); ++ Ok(Vc::cell(minify.unwrap_or(default))) + } + + #[turbo_tasks::function] +diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts +index 7dd555bb08..0bda67765c 100644 +--- a/packages/next/src/server/config-schema.ts ++++ b/packages/next/src/server/config-schema.ts +@@ -374,7 +374,16 @@ export const experimentalSchema = { + turbopackPluginRuntimeStrategy: z + .enum(['workerThreads', 'childProcesses']) + .optional(), +- turbopackMinify: z.boolean().optional(), ++ turbopackMinify: z ++ .union([ ++ z.boolean(), ++ z.strictObject({ ++ server: z.boolean().optional(), ++ client: z.boolean().optional(), ++ edge: z.boolean().optional(), ++ }), ++ ]) ++ .optional(), + turbopackFileSystemCacheForDev: z.boolean().optional(), + turbopackFileSystemCacheForBuild: z.boolean().optional(), + turbopackSeedCacheFromWorktree: z.boolean().optional(), +diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts +index b6f3f31312..836ee5f318 100644 +--- a/packages/next/src/server/config-shared.ts ++++ b/packages/next/src/server/config-shared.ts +@@ -769,8 +769,18 @@ export interface ExperimentalConfig { + + /** + * Enable minification. Defaults to true in build mode and false in dev mode. ++ * ++ * Pass an object to configure each environment separately, e.g. ++ * `{ server: false, client: true }`. The `server` option takes precedence ++ * over `experimental.serverMinification`. ++ * ++ * We don't recommend disabling minification in production. Disabling it ++ * increases server function size, slows down cold starts, and leads to ++ * degraded performance. + */ +- turbopackMinify?: boolean ++ turbopackMinify?: ++ | boolean ++ | { server?: boolean; client?: boolean; edge?: boolean } + + /** + * Enable support for `with {type: "bytes"}` for ESM imports. +@@ -1153,6 +1163,9 @@ export interface ExperimentalConfig { + + /** + * enables the minification of server code. ++ * ++ * Under Turbopack this is overridden by `experimental.turbopackMinify` when ++ * that option specifies a `server` value. + */ + serverMinification?: boolean + + /** diff --git a/nextjs-turbopack-nested-promises/environment/Dockerfile b/nextjs-turbopack-nested-promises/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4935b71fb3e10488cafec4a813c4deacba322dea --- /dev/null +++ b/nextjs-turbopack-nested-promises/environment/Dockerfile @@ -0,0 +1,45 @@ +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 +RUN useradd --create-home --shell /bin/bash agent +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 'set -e; fixture='"'"'turbopack/crates/turbopack-tests/tests/execution/turbopack/basic/async-nested-promise'"'"'; created=0; cleanup() { if [ "$created" -eq 1 ]; then rm -f "$fixture/input/index.js"; fi; if [ -d "$fixture/input" ]; then chmod a+rwx "$fixture"; chmod a+rx "$fixture/input"; fi; }; trap cleanup EXIT; corepack enable; corepack prepare pnpm@10.33.0 --activate; pnpm install --frozen-lockfile; mkdir -p "$fixture/input"; if [ ! -e "$fixture/input/index.js" ]; then : > "$fixture/input/index.js"; created=1; fi; chmod a+rwx "$fixture"; chmod a+rx "$fixture/input"; cargo test --locked --profile=release-with-assertions -p turbopack-tests --test execution --no-run' \ + && 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-nested-promises/solution/gold.patch b/nextjs-turbopack-nested-promises/solution/gold.patch new file mode 100644 index 0000000000000000000000000000000000000000..9b9f53b911f4b901869cfbeec89dbf5bd00ccbc0 --- /dev/null +++ b/nextjs-turbopack-nested-promises/solution/gold.patch @@ -0,0 +1,61 @@ +diff --git a/turbopack/crates/turbopack-ecmascript/src/analyzer/jsvalue/normalize.rs b/turbopack/crates/turbopack-ecmascript/src/analyzer/jsvalue/normalize.rs +index 438a2d6733..3dfb6823a3 100644 +--- a/turbopack/crates/turbopack-ecmascript/src/analyzer/jsvalue/normalize.rs ++++ b/turbopack/crates/turbopack-ecmascript/src/analyzer/jsvalue/normalize.rs +@@ -80,6 +80,11 @@ impl<'a> JsValue<'a> { + } + } + } ++ JsValue::Promise(_, inner) | JsValue::Awaited(_, inner) => { ++ if resolve_promises(inner) { ++ self.update_total_nodes(); ++ } ++ } + JsValue::Concat(_, v) => { + // TODO(kdy1): Remove duplicate + let taken = take(v); +@@ -186,4 +191,44 @@ impl<'a> JsValue<'a> { + } + } + ++/// Replaces `value` with what awaiting it produces, returning whether it changed. ++/// ++/// ```text ++/// Promise> -> null ++/// Promise> -> null | 0 ++/// c ? Promise : Promise<0> -> c ? null : 0 ++/// null -> null ++/// ``` ++pub(crate) fn resolve_promises<'a>(value: &mut JsValue<'a>) -> bool { ++ match value { ++ JsValue::Promise(_, inner) => { ++ let mut inner = take(&mut **inner); ++ resolve_promises(&mut inner); ++ *value = inner; ++ true ++ } ++ // Awaiting a branching value awaits whichever branch is taken, so the promises are inside ++ // the branches rather than around them. ++ JsValue::Tenary(_, _, cons, alt) => { ++ let modified = resolve_promises(cons) | resolve_promises(alt); ++ if modified { ++ value.update_total_nodes(); ++ } ++ modified ++ } ++ JsValue::Alternatives { values, .. } => { ++ let mut modified = false; ++ for alternative in values.iter_mut() { ++ modified |= resolve_promises(alternative); ++ } ++ if modified { ++ let values = take(values); ++ *value = JsValue::alternatives(values); ++ } ++ modified ++ } ++ _ => false, ++ } ++} ++ + // Similarity diff --git a/nextjs-turbopack-nested-promises/solution/solve.sh b/nextjs-turbopack-nested-promises/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-turbopack-nested-promises/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-nested-promises/tests/Dockerfile b/nextjs-turbopack-nested-promises/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cfdc223e412c96157c61aeff6c191ffa2761ef12 --- /dev/null +++ b/nextjs-turbopack-nested-promises/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 'set -e; fixture='"'"'turbopack/crates/turbopack-tests/tests/execution/turbopack/basic/async-nested-promise'"'"'; created=0; cleanup() { if [ "$created" -eq 1 ]; then rm -f "$fixture/input/index.js"; fi; if [ -d "$fixture/input" ]; then chmod a+rwx "$fixture"; chmod a+rx "$fixture/input"; fi; }; trap cleanup EXIT; corepack enable; corepack prepare pnpm@10.33.0 --activate; pnpm install --frozen-lockfile; mkdir -p "$fixture/input"; if [ ! -e "$fixture/input/index.js" ]; then : > "$fixture/input/index.js"; created=1; fi; chmod a+rwx "$fixture"; chmod a+rx "$fixture/input"; cargo test --locked --profile=release-with-assertions -p turbopack-tests --test execution --no-run' \ + && 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-nested-promises/tests/test.patch b/nextjs-turbopack-nested-promises/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..477f42941ce66536484572996bfc4214104cbf49 --- /dev/null +++ b/nextjs-turbopack-nested-promises/tests/test.patch @@ -0,0 +1,105 @@ +diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/basic/async-nested-promise/input/index.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/basic/async-nested-promise/input/index.js +new file mode 100644 +index 00000000..c2107dae +--- /dev/null ++++ b/turbopack/crates/turbopack-tests/tests/execution/turbopack/basic/async-nested-promise/input/index.js +@@ -0,0 +1,99 @@ ++// An async function that returns a promise-returning call without awaiting it resolves to the ++// inner value, not to a promise. Modelling that as `Promise>` made awaiting it strip ++// only one layer, so the result still looked like a promise — always truthy — and guards on it ++// were folded away along with the code after them. ++// ++// Each guard below calls a concrete wrapper rather than a parameter, so the analyzer can ++// resolve the call and the folding is actually exercised. ++ ++async function findRow() { ++ return null ++} ++ ++// Returns the promise from `findRow` without awaiting it. ++async function findRowWrapped() { ++ return findRow() ++} ++ ++async function findRowWrappedTwice() { ++ return findRowWrapped() ++} ++ ++async function findRowConditional(useFirst) { ++ return useFirst ? findRow() : findRowWrapped() ++} ++ ++async function classifyWrapped() { ++ const row = await findRowWrapped() ++ if (row) { ++ return 'found' ++ } ++ return 'missing' ++} ++ ++async function classifyWrappedTwice() { ++ const row = await findRowWrappedTwice() ++ if (row) { ++ return 'found' ++ } ++ return 'missing' ++} ++ ++// `useFirst` stays an unresolved argument, so the ternary survives analysis instead of ++// folding to one branch. ++async function classifyConditional(useFirst) { ++ const row = await findRowConditional(useFirst) ++ if (row) { ++ return 'found' ++ } ++ return 'missing' ++} ++ ++it('should not take a guard on an awaited nested promise', async () => { ++ const row = await findRowWrapped() ++ expect(row).toBe(null) ++ if (row) { ++ throw new Error('guard on an awaited nested promise should not be taken') ++ } ++}) ++ ++it('should keep the code after a guard that always returns', async () => { ++ expect(await classifyWrapped()).toBe('missing') ++}) ++ ++it('should collapse more than one level of nesting', async () => { ++ expect(await findRowWrappedTwice()).toBe(null) ++ expect(await classifyWrappedTwice()).toBe('missing') ++}) ++ ++it('should collapse promises nested inside branches', async () => { ++ expect(await findRowConditional(true)).toBe(null) ++ expect(await findRowConditional(false)).toBe(null) ++ expect(await classifyConditional(true)).toBe('missing') ++ expect(await classifyConditional(false)).toBe('missing') ++}) ++ ++it('should still treat an un-awaited promise as truthy', async () => { ++ const promise = findRowWrapped() ++ let taken = false ++ if (promise) { ++ taken = true ++ } ++ expect(taken).toBe(true) ++ expect(await promise).toBe(null) ++}) ++ ++// A union of promises with no enclosing async function: `await` has to unwrap each branch. ++async function classifyBareAlternatives(useFirst) { ++ const pending = useFirst ? findRow() : findRowWrapped() ++ const row = await pending ++ if (row) { ++ return 'found' ++ } ++ return 'missing' ++} ++ ++it('should distribute await over a union of promises', async () => { ++ expect(await classifyBareAlternatives(true)).toBe('missing') ++ expect(await classifyBareAlternatives(false)).toBe('missing') ++}) diff --git a/nextjs-turbopack-nested-promises/tests/test.sh b/nextjs-turbopack-nested-promises/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b55d4e842cc3dbd1ba2aee77d2e8d7588f03368c --- /dev/null +++ b/nextjs-turbopack-nested-promises/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/basic/async-nested-promise/input/index.js' --exclude='turbopack/crates/turbopack-tests/tests/execution/turbopack/basic/async-nested-promise/input/index.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/basic/async-nested-promise/input/index.js' 2>/dev/null || true + git -C /app clean -fd -- 'turbopack/crates/turbopack-tests/tests/execution/turbopack/basic/async-nested-promise/input/index.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/basic/async-nested-promise/input/index.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 --profile=release-with-assertions -p turbopack-tests --test execution '"'"'test_tests__execution__turbopack__basic__async_nested_promise__input__index_js'"'"' -- --exact'; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'cargo test --locked --profile=release-with-assertions -p turbopack-tests --test execution '"'"'test_tests__execution__turbopack__basic__async_nested_promise__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 --profile=release-with-assertions -p turbopack-tests --test execution '"'"'test_tests__execution__turbopack__basic__async_lazy_init__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 < = +diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts +index 1d996b52cb..27d09fefd1 100644 +--- a/packages/next/src/server/config-shared.ts ++++ b/packages/next/src/server/config-shared.ts +@@ -169,10 +169,12 @@ export type TurbopackRuleCondition = + * - `'typescript'` - Process as TypeScript module + * - `'css'` - Process as CSS file + * - `'css-module'` - Process as CSS module ++ * - `'json'` - Parse as JSON and export it + * - `'wasm'` - Process as WebAssembly module +- * - `'raw'` - Return raw file contents as a string ++ * - `'raw'` - Export file contents as a string (an alias of `'text'`) + * - `'node'` - Process as native Node.js addon +- * - `'bytes'` - Inline file contents as bytes in JavaScript ++ * - `'bytes'` - Export file contents as a `Uint8Array` ++ * - `'text'` - Export file contents as a string + * + * @see [Module Types](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#module-types) + */ +@@ -182,6 +184,7 @@ export type TurbopackModuleType = + | 'typescript' + | 'css' + | 'css-module' ++ | 'json' + | 'wasm' + | 'raw' + | 'node' +diff --git a/turbopack/crates/turbopack-ecmascript/src/references/async_module.rs b/turbopack/crates/turbopack-ecmascript/src/references/async_module.rs +index 9ada6180f5..9b8ceb3e4e 100644 +--- a/turbopack/crates/turbopack-ecmascript/src/references/async_module.rs ++++ b/turbopack/crates/turbopack-ecmascript/src/references/async_module.rs +@@ -151,7 +151,9 @@ impl AsyncModule { + } + } + ReferencedAsset::External(..) => None, +- ReferencedAsset::None | ReferencedAsset::Unresolvable => None, ++ ReferencedAsset::NonPlaceable(_) ++ | ReferencedAsset::None ++ | ReferencedAsset::Unresolvable => None, + }) + }) + .try_flat_join() +diff --git a/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs b/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs +index 7dc0f0b590..5dd2fb8402 100644 +--- a/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs ++++ b/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs +@@ -19,7 +19,10 @@ use turbo_tasks::{ + use turbo_tasks_fs::FileSystemPath; + use turbopack_core::{ + chunk::{ChunkingContext, ChunkingType, ModuleChunkItemIdExt}, +- issue::{Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString}, ++ issue::{ ++ Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString, ++ code_gen::CodeGenerationIssue, ++ }, + loader::{ResolvedWebpackLoaderItem, WebpackLoaderItem}, + module::{Module, ModuleSideEffects}, + module_graph::binding_usage_info::ModuleExportUsageInfo, +@@ -59,6 +62,11 @@ use crate::{ + pub enum ReferencedAsset { + Some(ResolvedVc>), + External(RcStr, ExternalType), ++ /// The request resolved to a module that can't be placed in an ECMAScript ++ /// chunk (e.g. a stylesheet or a raw module), so it has no bindings to ++ /// import. Importing it for its side effects is fine, reading a binding off ++ /// it is not. ++ NonPlaceable(ResolvedVc>), + None, + Unresolvable, + } +@@ -316,6 +324,34 @@ impl ReferencedAsset { + import_source, + }) + } ++ ReferencedAsset::NonPlaceable(module) => { ++ // The module exists but has no ECMAScript bindings, so there is ++ // nothing this identifier could refer to. Report it instead of ++ // silently evaluating to `undefined`. ++ CodeGenerationIssue { ++ severity: IssueSeverity::Error, ++ title: StyledString::Text(rcstr!("non-ecmascript placeable asset")) ++ .resolved_cell(), ++ message: StyledString::Text( ++ format!( ++ "{} has no ECMAScript exports, so {} can't be read from it. It can \ ++ only be imported for its side effects.", ++ module.ident().to_string().await?, ++ match &export { ++ Some(export) => format!("the export {export:?}"), ++ None => "a namespace".to_string(), ++ } ++ ) ++ .into(), ++ ) ++ .resolved_cell(), ++ path: module.ident().await?.path.clone(), ++ source: None, ++ } ++ .resolved_cell() ++ .emit(); ++ None ++ } + ReferencedAsset::None | ReferencedAsset::Unresolvable => None, + }) + } +@@ -338,6 +374,7 @@ impl ReferencedAsset { + if result.is_unresolvable() { + return Ok(ReferencedAsset::Unresolvable); + } ++ let mut non_placeable = None; + for (_, result) in result.primary.iter() { + match result { + ModuleResolveResultItem::External { +@@ -351,12 +388,16 @@ impl ReferencedAsset { + { + return Ok(ReferencedAsset::Some(placeable)); + } ++ non_placeable = non_placeable.or(Some(*module)); + } + // TODO ignore should probably be handled differently + _ => {} + } + } +- Ok(ReferencedAsset::None) ++ Ok(match non_placeable { ++ Some(module) => ReferencedAsset::NonPlaceable(module), ++ None => ReferencedAsset::None, ++ }) + } + } + +@@ -740,7 +781,9 @@ impl EsmAssetReference { + stmt, + )); + } +- ReferencedAsset::None => {} ++ // A module without ECMAScript bindings (e.g. a stylesheet) may still ++ // be imported for its side effects, which needs no code generation. ++ ReferencedAsset::None | ReferencedAsset::NonPlaceable(_) => {} + _ => { + let mut result = vec![]; + +diff --git a/turbopack/crates/turbopack-ecmascript/src/references/esm/url.rs b/turbopack/crates/turbopack-ecmascript/src/references/esm/url.rs +index ffc958c9e4..351f872f55 100644 +--- a/turbopack/crates/turbopack-ecmascript/src/references/esm/url.rs ++++ b/turbopack/crates/turbopack-ecmascript/src/references/esm/url.rs +@@ -216,7 +216,9 @@ impl UrlAssetReferenceCodeGen { + request + ) + } +- ReferencedAsset::None | ReferencedAsset::Unresolvable => {} ++ ReferencedAsset::NonPlaceable(_) ++ | ReferencedAsset::None ++ | ReferencedAsset::Unresolvable => {} + } + } + UrlRewriteBehavior::Full => { +@@ -333,7 +335,9 @@ impl UrlAssetReferenceCodeGen { + request + ) + } +- ReferencedAsset::None | ReferencedAsset::Unresolvable => {} ++ ReferencedAsset::NonPlaceable(_) ++ | ReferencedAsset::None ++ | ReferencedAsset::Unresolvable => {} + } + } + UrlRewriteBehavior::None => { +diff --git a/turbopack/crates/turbopack/src/module_options/module_rule.rs b/turbopack/crates/turbopack/src/module_options/module_rule.rs +index 8d21b30cfe..e38279d69b 100644 +--- a/turbopack/crates/turbopack/src/module_options/module_rule.rs ++++ b/turbopack/crates/turbopack/src/module_options/module_rule.rs +@@ -12,7 +12,7 @@ use turbopack_core::{ + use turbopack_css::CssModuleType; + use turbopack_ecmascript::{ + EcmascriptInputTransforms, EcmascriptOptions, bytes_source_transform::BytesSourceTransform, +- json_source_transform::JsonSourceTransform, ++ json_source_transform::JsonSourceTransform, text_source_transform::TextSourceTransform, + }; + use turbopack_wasm::source::WebAssemblySourceType; + +@@ -193,11 +193,17 @@ pub enum ConfiguredModuleType { + /// Implemented as a source transform, not a ModuleType. + Json, + Wasm, ++ /// An alias of [`ConfiguredModuleType::Text`]. + Raw, + Node, + /// Converts any file to an ES module exporting its contents as a Uint8Array. + /// Implemented as a source transform, not a ModuleType. + Bytes, ++ /// Converts any file to an ES module exporting its contents as a string. ++ /// Implemented as a source transform, not a ModuleType. ++ /// ++ /// `Raw` is an alias of this. ++ Text, + } + + impl ConfiguredModuleType { +@@ -214,9 +220,10 @@ impl ConfiguredModuleType { + "raw" => ConfiguredModuleType::Raw, + "node" => ConfiguredModuleType::Node, + "bytes" => ConfiguredModuleType::Bytes, ++ "text" => ConfiguredModuleType::Text, + _ => bail!( + "Unknown module type: {type_str:?}. Valid types are: asset, ecmascript, \ +- typescript, css, css-module, json, wasm, raw, node, bytes" ++ typescript, css, css-module, json, wasm, raw, node, bytes, text" + ), + }) + } +@@ -242,6 +249,15 @@ impl ConfiguredModuleType { + BytesSourceTransform::new().to_resolved().await?, + )])) + } ++ // `raw` has always been documented as returning the contents as a string, so it ++ // is an alias of `text` rather than a way to get an opaque module. ++ ConfiguredModuleType::Text | ConfiguredModuleType::Raw => { ++ // Same as `Bytes`: a source transform that produces .mjs, which is then ++ // picked up by the standard Ecmascript rules. ++ ModuleRuleEffect::SourceTransforms(ResolvedVc::cell(vec![ResolvedVc::upcast( ++ TextSourceTransform::new().to_resolved().await?, ++ )])) ++ } + ConfiguredModuleType::Asset => { + ModuleRuleEffect::ModuleType(ModuleType::StaticUrlJs { tag: None }) + } +@@ -278,7 +294,6 @@ impl ConfiguredModuleType { + ConfiguredModuleType::Wasm => ModuleRuleEffect::ModuleType(ModuleType::WebAssembly { + source_ty: WebAssemblySourceType::Binary, + }), +- ConfiguredModuleType::Raw => ModuleRuleEffect::ModuleType(ModuleType::Raw), + ConfiguredModuleType::Node => ModuleRuleEffect::ModuleType(ModuleType::NodeAddon), + }) + } diff --git a/nextjs-turbopack-text-rules-non-esm-imports/solution/solve.sh b/nextjs-turbopack-text-rules-non-esm-imports/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b23b1455c5a01d637a3985c89514ac2b453ecec2 --- /dev/null +++ b/nextjs-turbopack-text-rules-non-esm-imports/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-text-rules-non-esm-imports/tests/Dockerfile b/nextjs-turbopack-text-rules-non-esm-imports/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4c6475d9bd45708e89676194222a73d072bd5d7 --- /dev/null +++ b/nextjs-turbopack-text-rules-non-esm-imports/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 && export PATH="$HOME/.cargo/bin:$PATH" && pnpm install --frozen-lockfile && pnpm 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-turbopack-text-rules-non-esm-imports/tests/test.patch b/nextjs-turbopack-text-rules-non-esm-imports/tests/test.patch new file mode 100644 index 0000000000000000000000000000000000000000..9c5ac3234324325282faf99d7d2a58bfef7c5250 --- /dev/null +++ b/nextjs-turbopack-text-rules-non-esm-imports/tests/test.patch @@ -0,0 +1,344 @@ +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/alias/alpha.md b/test/e2e/app-dir/import-meta-glob-text-type/app/alias/alpha.md +new file mode 100644 +index 0000000000..9f12eba37f +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/alias/alpha.md +@@ -0,0 +1,3 @@ ++# alpha ++ ++some markdown +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/alias/alpha.mdx b/test/e2e/app-dir/import-meta-glob-text-type/app/alias/alpha.mdx +new file mode 100644 +index 0000000000..9f12eba37f +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/alias/alpha.mdx +@@ -0,0 +1,3 @@ ++# alpha ++ ++some markdown +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/alias/page.tsx b/test/e2e/app-dir/import-meta-glob-text-type/app/alias/page.tsx +new file mode 100644 +index 0000000000..5e83310902 +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/alias/page.tsx +@@ -0,0 +1,15 @@ ++// `alpha.md` is loaded by a `type: 'raw'` rule, `alpha.mdx` by a `type: 'text'` ++// rule. The files have identical contents, so the imports must be identical. ++// @ts-expect-error -- untyped module ++import * as rawNamespace from './alpha.md' ++// @ts-expect-error -- untyped module ++import text from './alpha.mdx' ++ ++export default function Page() { ++ return ( ++ <> ++

    {JSON.stringify(rawNamespace.default)}

    ++

    {String(rawNamespace.default === text)}

    ++ ++ ) ++} +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/json/page.tsx b/test/e2e/app-dir/import-meta-glob-text-type/app/json/page.tsx +new file mode 100644 +index 0000000000..c9e2a1b0b7 +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/json/page.tsx +@@ -0,0 +1,6 @@ ++// @ts-expect-error -- custom extension configured as JSON ++import values from './values.data' ++ ++export default function Page() { ++ return

    {JSON.stringify(values)}

    ++} +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/json/values.data b/test/e2e/app-dir/import-meta-glob-text-type/app/json/values.data +new file mode 100644 +index 0000000000..60b1c51cc9 +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/json/values.data +@@ -0,0 +1 @@ ++{ "answer": 42, "label": "configured json" } +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/layout.tsx b/test/e2e/app-dir/import-meta-glob-text-type/app/layout.tsx +new file mode 100644 +index 0000000000..888614deda +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/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/import-meta-glob-text-type/app/page.tsx b/test/e2e/app-dir/import-meta-glob-text-type/app/page.tsx +new file mode 100644 +index 0000000000..ff7159d914 +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/page.tsx +@@ -0,0 +1,3 @@ ++export default function Page() { ++ return

    hello world

    ++} +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/content/delta.rst b/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/content/delta.rst +new file mode 100644 +index 0000000000..c5fedbf747 +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/content/delta.rst +@@ -0,0 +1 @@ ++delta contents +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/content/gamma.rst b/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/content/gamma.rst +new file mode 100644 +index 0000000000..6be4b3a4dd +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/content/gamma.rst +@@ -0,0 +1 @@ ++gamma contents +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/page.tsx b/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/page.tsx +new file mode 100644 +index 0000000000..268541cd24 +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/raw-alias/page.tsx +@@ -0,0 +1,17 @@ ++// Same as `/raw`, but the rule matching `?raw` is spelled `type: 'raw'`. ++const texts = import.meta.glob('./content/*.rst', { ++ query: '?raw', ++ eager: true, ++}) as Record ++ ++export default function Page() { ++ return ( ++
      ++ {Object.keys(texts).map((key) => ( ++
    • ++ {texts[key].default.trim()} ++
    • ++ ))} ++
    ++ ) ++} +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/raw/content/delta.txt b/test/e2e/app-dir/import-meta-glob-text-type/app/raw/content/delta.txt +new file mode 100644 +index 0000000000..c5fedbf747 +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/raw/content/delta.txt +@@ -0,0 +1 @@ ++delta contents +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/raw/content/gamma.txt b/test/e2e/app-dir/import-meta-glob-text-type/app/raw/content/gamma.txt +new file mode 100644 +index 0000000000..6be4b3a4dd +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/raw/content/gamma.txt +@@ -0,0 +1 @@ ++gamma contents +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/app/raw/page.tsx b/test/e2e/app-dir/import-meta-glob-text-type/app/raw/page.tsx +new file mode 100644 +index 0000000000..38d0cae6bf +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/app/raw/page.tsx +@@ -0,0 +1,16 @@ ++const texts = import.meta.glob('./content/*.txt', { ++ query: '?raw', ++ eager: true, ++}) as Record ++ ++export default function Page() { ++ return ( ++
      ++ {Object.keys(texts).map((key) => ( ++
    • ++ {texts[key].default.trim()} ++
    • ++ ))} ++
    ++ ) ++} +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/import-meta-glob-text-type.test.ts b/test/e2e/app-dir/import-meta-glob-text-type/import-meta-glob-text-type.test.ts +new file mode 100644 +index 0000000000..b450a9f69d +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/import-meta-glob-text-type.test.ts +@@ -0,0 +1,57 @@ ++import { nextTestSetup } from 'e2e-utils' ++ ++// `turbopack.rules` is a Turbopack-only feature; skip under webpack ++const testFn = ++ process.env.IS_WEBPACK_TEST || process.env.NEXT_RSPACK ++ ? describe.skip ++ : describe ++ ++testFn('turbopack `text` / `raw` module types', () => { ++ const { next, skipped } = nextTestSetup({ ++ files: __dirname, ++ skipDeployment: true, ++ }) ++ ++ if (skipped) return ++ ++ it('should load matched files as strings through a `?raw` rule', async () => { ++ const $ = await next.render$('/raw') ++ const items: Record = {} ++ $('li').each((_, el) => { ++ items[$(el).attr('data-path')!] = $(el).text() ++ }) ++ ++ expect(items).toEqual({ ++ './content/delta.txt': 'delta contents', ++ './content/gamma.txt': 'gamma contents', ++ }) ++ }) ++ ++ it('should treat `raw` and `text` the same in a `?raw` rule', async () => { ++ const $ = await next.render$('/raw-alias') ++ const items: Record = {} ++ $('li').each((_, el) => { ++ items[$(el).attr('data-path')!] = $(el).text() ++ }) ++ ++ expect(items).toEqual({ ++ './content/delta.rst': 'delta contents', ++ './content/gamma.rst': 'gamma contents', ++ }) ++ }) ++ ++ it('should parse files configured with the `json` module type', async () => { ++ const $ = await next.render$('/json') ++ expect(JSON.parse($('#json').text())).toEqual({ ++ answer: 42, ++ label: 'configured json', ++ }) ++ }) ++ ++ it('should treat `raw` and `text` the same for a plain import', async () => { ++ const $ = await next.render$('/alias') ++ ++ expect(JSON.parse($('#raw').text())).toBe('# alpha\n\nsome markdown\n') ++ expect($('#equal').text()).toBe('true') ++ }) ++}) +diff --git a/test/e2e/app-dir/import-meta-glob-text-type/next.config.js b/test/e2e/app-dir/import-meta-glob-text-type/next.config.js +new file mode 100644 +index 0000000000..1b7213358d +--- /dev/null ++++ b/test/e2e/app-dir/import-meta-glob-text-type/next.config.js +@@ -0,0 +1,18 @@ ++/** ++ * @type {import('next').NextConfig} ++ */ ++const nextConfig = { ++ turbopack: { ++ rules: { ++ // Turbopack has no built-in `?raw` handling, the query is matched by a ++ // rule. `raw` and `text` are aliases, both load the file as a string. ++ '*.txt': { condition: { query: '?raw' }, type: 'text' }, ++ '*.rst': { condition: { query: '?raw' }, type: 'raw' }, ++ '*.md': { type: 'raw' }, ++ '*.mdx': { type: 'text' }, ++ '*.data': { type: 'json' }, ++ }, ++ }, ++} ++ ++module.exports = nextConfig +diff --git a/test/production/app-dir/turbopack-non-placeable-import/app/api/addon/route.ts b/test/production/app-dir/turbopack-non-placeable-import/app/api/addon/route.ts +new file mode 100644 +index 0000000000..d08bbf8132 +--- /dev/null ++++ b/test/production/app-dir/turbopack-non-placeable-import/app/api/addon/route.ts +@@ -0,0 +1,7 @@ ++// A module that cannot be placed in an ECMAScript chunk can still be imported ++// for its side effects. No binding from the native addon is read here. ++import '../../../lib/fake.node' ++ ++export function GET() { ++ return Response.json({ ok: true }) ++} +diff --git a/test/production/app-dir/turbopack-non-placeable-import/app/layout.tsx b/test/production/app-dir/turbopack-non-placeable-import/app/layout.tsx +new file mode 100644 +index 0000000000..888614deda +--- /dev/null ++++ b/test/production/app-dir/turbopack-non-placeable-import/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/turbopack-non-placeable-import/app/page.tsx b/test/production/app-dir/turbopack-non-placeable-import/app/page.tsx +new file mode 100644 +index 0000000000..ff7159d914 +--- /dev/null ++++ b/test/production/app-dir/turbopack-non-placeable-import/app/page.tsx +@@ -0,0 +1,3 @@ ++export default function Page() { ++ return

    hello world

    ++} +diff --git a/test/production/app-dir/turbopack-non-placeable-import/lib/fake.node b/test/production/app-dir/turbopack-non-placeable-import/lib/fake.node +new file mode 100644 +index 0000000000..12082b7a46 +--- /dev/null ++++ b/test/production/app-dir/turbopack-non-placeable-import/lib/fake.node +@@ -0,0 +1 @@ ++ELF not-a-real-addon +diff --git a/test/production/app-dir/turbopack-non-placeable-import/native.d.ts b/test/production/app-dir/turbopack-non-placeable-import/native.d.ts +new file mode 100644 +index 0000000000..c740c71866 +--- /dev/null ++++ b/test/production/app-dir/turbopack-non-placeable-import/native.d.ts +@@ -0,0 +1,4 @@ ++declare module '*.node' { ++ const exports: Record ++ export = exports ++} +diff --git a/test/production/app-dir/turbopack-non-placeable-import/next.config.js b/test/production/app-dir/turbopack-non-placeable-import/next.config.js +new file mode 100644 +index 0000000000..807126e4cf +--- /dev/null ++++ b/test/production/app-dir/turbopack-non-placeable-import/next.config.js +@@ -0,0 +1,6 @@ ++/** ++ * @type {import('next').NextConfig} ++ */ ++const nextConfig = {} ++ ++module.exports = nextConfig +diff --git a/test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.test.ts b/test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.test.ts +new file mode 100644 +index 0000000000..d6cee22959 +--- /dev/null ++++ b/test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.test.ts +@@ -0,0 +1,32 @@ ++import { nextTestSetup } from 'e2e-utils' ++ ++describe('imports of modules with no ECMAScript exports', () => { ++ const { next, isTurbopack } = nextTestSetup({ ++ files: __dirname, ++ skipStart: true, ++ }) ++ ++ if (!isTurbopack) { ++ it('is turbopack-only', () => {}) ++ return ++ } ++ ++ it('allows side-effect imports but rejects reads of bindings', async () => { ++ const sideEffectBuild = await next.build() ++ expect(sideEffectBuild.exitCode).toBe(0) ++ ++ await next.patchFile( ++ 'app/api/addon/route.ts', ++ `import * as addon from '../../../lib/fake.node' ++ ++export function GET() { ++ return Response.json({ type: typeof addon }) ++} ++` ++ ) ++ ++ const bindingBuild = await next.build() ++ expect(bindingBuild.exitCode).not.toBe(0) ++ expect(bindingBuild.cliOutput).toContain('fake.node') ++ }) ++}) diff --git a/nextjs-turbopack-text-rules-non-esm-imports/tests/test.sh b/nextjs-turbopack-text-rules-non-esm-imports/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cba766c7d8d449eb89a525fc7f4affd435a7a345 --- /dev/null +++ b/nextjs-turbopack-text-rules-non-esm-imports/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/import-meta-glob-text-type/import-meta-glob-text-type.test.ts' --exclude='test/e2e/app-dir/import-meta-glob-text-type/import-meta-glob-text-type.test.ts/*' --exclude='test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.test.ts' --exclude='test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.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/import-meta-glob-text-type/import-meta-glob-text-type.test.ts' 'test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.test.ts' 2>/dev/null || true + git -C /app clean -fd -- 'test/e2e/app-dir/import-meta-glob-text-type/import-meta-glob-text-type.test.ts' 'test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.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/import-meta-glob-text-type/import-meta-glob-text-type.test.ts' '/app/test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.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 'export PATH="$HOME/.cargo/bin:$PATH"; pnpm swc-build-native && ANALYZE=1 pnpm build && TURBOPACK_BUILD=1 pnpm test-start-turbo '"'"'test/e2e/app-dir/import-meta-glob-text-type/import-meta-glob-text-type.test.ts'"'"' '"'"'test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.test.ts'"'"''; then + fail_to_pass_exit_code=0 + fail_to_pass=1 + if run_verifier_command 'export PATH="$HOME/.cargo/bin:$PATH"; pnpm swc-build-native && ANALYZE=1 pnpm build && TURBOPACK_BUILD=1 pnpm test-start-turbo '"'"'test/e2e/app-dir/import-meta-glob-text-type/import-meta-glob-text-type.test.ts'"'"' '"'"'test/production/app-dir/turbopack-non-placeable-import/turbopack-non-placeable-import.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 'export PATH="$HOME/.cargo/bin:$PATH"; pnpm swc-build-native && ANALYZE=1 pnpm build && TURBOPACK_BUILD=1 pnpm test-start-turbo '"'"'test/e2e/turbopack-import-with-type/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 <