avyvar commited on
Commit
94786da
·
verified ·
1 Parent(s): b2cad4f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. nextjs-95738-assets-hash-salt/environment/Dockerfile +45 -0
  2. nextjs-95738-assets-hash-salt/solution/gold.patch +494 -0
  3. nextjs-95738-assets-hash-salt/solution/solve.sh +3 -0
  4. nextjs-95738-assets-hash-salt/tests/Dockerfile +43 -0
  5. nextjs-95738-assets-hash-salt/tests/test.patch +61 -0
  6. nextjs-95738-assets-hash-salt/tests/test.sh +98 -0
  7. nextjs-95799-async-route-init-errors/environment/Dockerfile +44 -0
  8. nextjs-95799-async-route-init-errors/solution/gold.patch +52 -0
  9. nextjs-95799-async-route-init-errors/solution/solve.sh +3 -0
  10. nextjs-95799-async-route-init-errors/tests/Dockerfile +42 -0
  11. nextjs-95799-async-route-init-errors/tests/test.patch +142 -0
  12. nextjs-95799-async-route-init-errors/tests/test.sh +98 -0
  13. nextjs-95946-file-sourcemaps/environment/Dockerfile +44 -0
  14. nextjs-95946-file-sourcemaps/solution/gold.patch +196 -0
  15. nextjs-95946-file-sourcemaps/solution/solve.sh +3 -0
  16. nextjs-95946-file-sourcemaps/tests/Dockerfile +42 -0
  17. nextjs-95946-file-sourcemaps/tests/test.patch +115 -0
  18. nextjs-95946-file-sourcemaps/tests/test.sh +98 -0
  19. nextjs-95967-single-learn-more-links/environment/Dockerfile +44 -0
  20. nextjs-95967-single-learn-more-links/solution/gold.patch +297 -0
  21. nextjs-95967-single-learn-more-links/solution/solve.sh +3 -0
  22. nextjs-95967-single-learn-more-links/tests/Dockerfile +42 -0
  23. nextjs-95967-single-learn-more-links/tests/test.patch +276 -0
  24. nextjs-95967-single-learn-more-links/tests/test.sh +98 -0
  25. nextjs-96022-dev-use-cache-invalidation/environment/Dockerfile +44 -0
  26. nextjs-96022-dev-use-cache-invalidation/solution/gold.patch +547 -0
  27. nextjs-96022-dev-use-cache-invalidation/solution/solve.sh +3 -0
  28. nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile +42 -0
  29. nextjs-96022-dev-use-cache-invalidation/tests/test.patch +61 -0
  30. nextjs-96022-dev-use-cache-invalidation/tests/test.sh +98 -0
  31. nextjs-byte-budgeted-lru-keys/environment/Dockerfile +44 -0
  32. nextjs-byte-budgeted-lru-keys/solution/gold.patch +117 -0
  33. nextjs-byte-budgeted-lru-keys/solution/solve.sh +3 -0
  34. nextjs-byte-budgeted-lru-keys/tests/Dockerfile +42 -0
  35. nextjs-byte-budgeted-lru-keys/tests/test.patch +243 -0
  36. nextjs-byte-budgeted-lru-keys/tests/test.sh +98 -0
  37. nextjs-byte-exact-binary-fetch-cache-keys/tests/Dockerfile +42 -0
  38. nextjs-byte-exact-binary-fetch-cache-keys/tests/test.patch +258 -0
  39. nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh +98 -0
  40. nextjs-cache-short-expire-dev/environment/Dockerfile +44 -0
  41. nextjs-cache-short-expire-dev/solution/gold.patch +303 -0
  42. nextjs-cache-short-expire-dev/solution/solve.sh +3 -0
  43. nextjs-cache-short-expire-dev/tests/Dockerfile +42 -0
  44. nextjs-cache-short-expire-dev/tests/test.patch +246 -0
  45. nextjs-cache-short-expire-dev/tests/test.sh +98 -0
  46. nextjs-cna-tailwind-turbopack/environment/Dockerfile +44 -0
  47. nextjs-cna-tailwind-turbopack/solution/gold.patch +61 -0
  48. nextjs-cna-tailwind-turbopack/solution/solve.sh +3 -0
  49. nextjs-cna-tailwind-turbopack/tests/Dockerfile +42 -0
  50. nextjs-cna-tailwind-turbopack/tests/test.patch +342 -0
nextjs-95738-assets-hash-salt/environment/Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ 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
21
+ RUN useradd --create-home --shell /bin/bash agent
22
+ COPY repo.tar.gz /tmp/repo.tar.gz
23
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
24
+ && git -C /app init -q \
25
+ && git -C /app config user.email selfbench@local \
26
+ && git -C /app config user.name selfbench \
27
+ && git -C /app add -A \
28
+ && git -C /app commit -qm base
29
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
30
+ && cd '/app/.' \
31
+ && 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' \
32
+ && chmod -R a+rwX /opt/uv-cache
33
+ RUN git -C /app reset --hard -q HEAD \
34
+ && git -C /app clean -fdq \
35
+ && mkdir -p /opt/selfbench \
36
+ && cp -a /app/.git /opt/selfbench/base.git \
37
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
38
+ && chown -R root:root /opt/selfbench \
39
+ && chmod 700 /opt/selfbench \
40
+ && mkdir -p /home/agent/.cache/uv \
41
+ && chown -R agent:agent /home/agent/.cache
42
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
43
+ UV_NO_BUILD_ISOLATION=1
44
+ USER agent
45
+ WORKDIR /app
nextjs-95738-assets-hash-salt/solution/gold.patch ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/crates/next-api/src/next_server_nft.rs b/crates/next-api/src/next_server_nft.rs
2
+ index 56d1b83ac6cb085133a6c20068764d7df26e8859..972cd0ad6597cdcc3812cbe158fb396604dd5af8 100644
3
+ --- a/crates/next-api/src/next_server_nft.rs
4
+ +++ b/crates/next-api/src/next_server_nft.rs
5
+ @@ -115,12 +115,15 @@ impl Asset for ServerNftJsonAsset {
6
+ )
7
+ .connect();
8
+
9
+ + let hash_salt = this.project.next_config().output_hash_salt();
10
+ +
11
+ let mut server_output_assets = traced_modules_for_entries(
12
+ module_graph,
13
+ Modules::empty(),
14
+ self.entries(),
15
+ Some(self.ignores()),
16
+ None,
17
+ + hash_salt,
18
+ )
19
+ .await?
20
+ .iter()
21
+ @@ -133,7 +136,7 @@ impl Asset for ServerNftJsonAsset {
22
+ .await?
23
+ .context("NFT module has no content")?
24
+ .content()
25
+ - .hash(HashAlgorithm::Xxh3Hash128Hex)
26
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
27
+ .await?,
28
+ ))
29
+ })
30
+ @@ -150,7 +153,7 @@ impl Asset for ServerNftJsonAsset {
31
+ .context("failed to compute relative path for server NFT JSON")?,
32
+ module_path
33
+ .read()
34
+ - .hash(HashAlgorithm::Xxh3Hash128Hex)
35
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
36
+ .await?,
37
+ ));
38
+
39
+ @@ -170,7 +173,9 @@ impl Asset for ServerNftJsonAsset {
40
+ base_dir
41
+ .get_relative_path_to(file)
42
+ .context("failed to compute relative path for server NFT JSON")?,
43
+ - file.read().hash(HashAlgorithm::Xxh3Hash128Hex).await?,
44
+ + file.read()
45
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
46
+ + .await?,
47
+ ))
48
+ }
49
+ }
50
+ diff --git a/crates/next-api/src/nft.rs b/crates/next-api/src/nft.rs
51
+ index ef8162bd3984eb2e1d010ed904a8ee017d994399..f09e23c000afe2a8186b131dac85d677f66b925a 100644
52
+ --- a/crates/next-api/src/nft.rs
53
+ +++ b/crates/next-api/src/nft.rs
54
+ @@ -67,6 +67,7 @@ pub async fn trace_endpoint(
55
+ async {
56
+ let project_path = project.project_path().owned().await?;
57
+ let next_config = project.next_config();
58
+ + let hash_salt = next_config.output_hash_salt();
59
+
60
+ let output_file_tracing_includes = next_config
61
+ .output_file_tracing_includes(project_path.clone())
62
+ @@ -83,10 +84,11 @@ pub async fn trace_endpoint(
63
+ .await?
64
+ .map(|v| *v),
65
+ Some(next_config.config_file_path(project_path.clone())),
66
+ + hash_salt,
67
+ )
68
+ .await?;
69
+
70
+ - let module_data = traced_module_data_for_graph(*module_graph, traced_entries)
71
+ + let module_data = traced_module_data_for_graph(*module_graph, traced_entries, hash_salt)
72
+ .to_resolved()
73
+ .await?;
74
+ let module_paths = module_data.await?.idents;
75
+ @@ -271,10 +273,11 @@ pub async fn traced_modules_for_entries(
76
+ traced_entries: Vc<Modules>,
77
+ exclude_glob: Option<Vc<Glob>>,
78
+ forbidden_path: Option<Vc<FileSystemPath>>,
79
+ + hash_salt: Vc<RcStr>,
80
+ ) -> Result<Vc<Modules>> {
81
+ let exclude_glob_and_module_idents = if let Some(exclude_glob) = exclude_glob {
82
+ let exclude_glob = exclude_glob.await?;
83
+ - let data = traced_module_data_for_graph(module_graph, traced_entries).await?;
84
+ + let data = traced_module_data_for_graph(module_graph, traced_entries, hash_salt).await?;
85
+ Some((exclude_glob, data.idents.await?))
86
+ } else {
87
+ None
88
+ @@ -379,6 +382,7 @@ pub struct TracedModuleData {
89
+ pub async fn traced_module_data_for_graph(
90
+ module_graph: Vc<ModuleGraph>,
91
+ traced_entries: Vc<Modules>,
92
+ + hash_salt: Vc<RcStr>,
93
+ ) -> Result<Vc<TracedModuleData>> {
94
+ // This function is very similar to traced_modules_for_entries, but doesn't apply the glob and
95
+ // is executed only once for the whole graph.
96
+ @@ -420,7 +424,7 @@ pub async fn traced_module_data_for_graph(
97
+ .await?
98
+ .context("NFT module has no content")?
99
+ .content()
100
+ - .hash(HashAlgorithm::Xxh3Hash128Hex)
101
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
102
+ .await?,
103
+ ),
104
+ ))
105
+ diff --git a/crates/next-api/src/nft_json.rs b/crates/next-api/src/nft_json.rs
106
+ index 957b3c834621bf201f20a967e0774edfe3df0138..6d003c8adcf509a0549ee5db542a4311be7742fc 100644
107
+ --- a/crates/next-api/src/nft_json.rs
108
+ +++ b/crates/next-api/src/nft_json.rs
109
+ @@ -119,6 +119,7 @@ impl Asset for NftJsonAsset {
110
+ let output_root_ref = this.project.output_fs().root().await?;
111
+ let project_root_ref = this.project.project_fs().root().await?;
112
+ let next_config = this.project.next_config();
113
+ + let hash_salt = next_config.output_hash_salt();
114
+
115
+ let client_root = this.project.client_fs().root();
116
+ let client_root = client_root.owned().await?;
117
+ @@ -173,7 +174,11 @@ impl Asset for NftJsonAsset {
118
+ let (referenced_chunk_path, hash) = match referenced {
119
+ AssetOrModule::Asset(v) => (
120
+ Either::Left(v.path().await?),
121
+ - Either::Left(v.content().hash(HashAlgorithm::Xxh3Hash128Hex).await?),
122
+ + Either::Left(
123
+ + v.content()
124
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
125
+ + .await?,
126
+ + ),
127
+ ),
128
+ AssetOrModule::Module(v) => {
129
+ let ident = module_data
130
+ @@ -235,7 +240,10 @@ impl Asset for NftJsonAsset {
131
+ Ok((
132
+ relative_path,
133
+ Either::Left(
134
+ - file_path.read().hash(HashAlgorithm::Xxh3Hash128Hex).await?,
135
+ + file_path
136
+ + .read()
137
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
138
+ + .await?,
139
+ ),
140
+ ))
141
+ })
142
+ @@ -266,7 +274,10 @@ impl Asset for NftJsonAsset {
143
+ // non-adapter consumers (which includes output:standalone) don't experience a breaking
144
+ // change, but instead we just add it as a separate field that only build-complete
145
+ // reads.
146
+ - let entry_hash = chunk.content().hash(HashAlgorithm::Xxh3Hash128Hex).await?;
147
+ + let entry_hash = chunk
148
+ + .content()
149
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
150
+ + .await?;
151
+ let json = json!({
152
+ "version": 1,
153
+ "files": files,
154
+ diff --git a/crates/next-api/src/paths.rs b/crates/next-api/src/paths.rs
155
+ index 3898419e8425863bb31e9895c915fc91ec21db08..b21dc5b98ea3f153e8120a7685a481799f5c793b 100644
156
+ --- a/crates/next-api/src/paths.rs
157
+ +++ b/crates/next-api/src/paths.rs
158
+ @@ -46,7 +46,7 @@ async fn asset_path(
159
+ } else {
160
+ asset
161
+ .content()
162
+ - .hash(HashAlgorithm::Xxh3Hash128Hex)
163
+ + .hash(no_hash_salt(), HashAlgorithm::Xxh3Hash128Hex)
164
+ .owned()
165
+ .await?
166
+ };
167
+ diff --git a/crates/next-api/src/routes_hashes_manifest.rs b/crates/next-api/src/routes_hashes_manifest.rs
168
+ index 4fa51d728cc36039370e500053cfe505ff0a25e0..00cd2feaafeeaac8523673448fd147d32113c1f5 100644
169
+ --- a/crates/next-api/src/routes_hashes_manifest.rs
170
+ +++ b/crates/next-api/src/routes_hashes_manifest.rs
171
+ @@ -5,7 +5,7 @@ use turbo_tasks::{FxIndexMap, FxIndexSet, ResolvedVc, TryFlatJoinIterExt, TryJoi
172
+ use turbo_tasks_fs::{FileContent, FileSystemPath};
173
+ use turbo_tasks_hash::{DeterministicHash, HashAlgorithm, Xxh3Hash64Hasher, hash_xxh3_hash64};
174
+ use turbopack_core::{
175
+ - asset::{Asset, AssetContent},
176
+ + asset::{Asset, AssetContent, no_hash_salt},
177
+ module::{Module, Modules},
178
+ module_graph::{GraphTraversalAction, ModuleGraph},
179
+ output::{
180
+ @@ -62,7 +62,7 @@ pub async fn endpoints_outputs(endpoints: Vc<Endpoints>) -> Result<Vc<OutputAsse
181
+ }
182
+
183
+ #[turbo_tasks::function]
184
+ -pub async fn outputs_hash(outputs: Vc<OutputAssets>) -> Result<Vc<u64>> {
185
+ +pub async fn outputs_hash(outputs: Vc<OutputAssets>, hash_salt: Vc<RcStr>) -> Result<Vc<u64>> {
186
+ let output_assets = expand_output_assets(
187
+ outputs
188
+ .await?
189
+ @@ -73,7 +73,11 @@ pub async fn outputs_hash(outputs: Vc<OutputAssets>) -> Result<Vc<u64>> {
190
+ .await?;
191
+ let outputs_hashes = output_assets
192
+ .iter()
193
+ - .map(|asset| asset.content().hash(HashAlgorithm::Xxh3Hash128Hex))
194
+ + .map(|asset| {
195
+ + asset
196
+ + .content()
197
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
198
+ + })
199
+ .try_join()
200
+ .await?;
201
+
202
+ @@ -121,7 +125,11 @@ pub async fn endpoints_entry_modules(
203
+ }
204
+
205
+ #[turbo_tasks::function]
206
+ -pub async fn sources_hash(module_graph: Vc<ModuleGraph>, modules: Vc<Modules>) -> Result<Vc<u64>> {
207
+ +pub async fn sources_hash(
208
+ + module_graph: Vc<ModuleGraph>,
209
+ + modules: Vc<Modules>,
210
+ + hash_salt: Vc<RcStr>,
211
+ +) -> Result<Vc<u64>> {
212
+ let modules = modules.await?;
213
+
214
+ let mut all_modules = FxIndexSet::default();
215
+ @@ -144,7 +152,11 @@ pub async fn sources_hash(module_graph: Vc<ModuleGraph>, modules: Vc<Modules>) -
216
+ .try_flat_join()
217
+ .await?
218
+ .into_iter()
219
+ - .map(|source| source.content().hash(HashAlgorithm::Xxh3Hash128Hex))
220
+ + .map(|source| {
221
+ + source
222
+ + .content()
223
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
224
+ + })
225
+ .try_join()
226
+ .await?;
227
+
228
+ @@ -181,6 +193,7 @@ impl RoutesHashesManifestAsset {
229
+ impl Asset for RoutesHashesManifestAsset {
230
+ #[turbo_tasks::function]
231
+ async fn content(&self) -> Result<Vc<AssetContent>> {
232
+ + let hash_salt = no_hash_salt();
233
+ let module_graphs = self.project.whole_app_module_graphs().await?;
234
+ let base_module_graph = *module_graphs.base;
235
+ let full_module_graph = *module_graphs.full;
236
+ @@ -195,8 +208,9 @@ impl Asset for RoutesHashesManifestAsset {
237
+ sources_hash(
238
+ full_module_graph,
239
+ endpoint_entry_modules(base_module_graph, *entry.endpoint),
240
+ + hash_salt,
241
+ ),
242
+ - outputs_hash(endpoint_outputs(*entry.endpoint)),
243
+ + outputs_hash(endpoint_outputs(*entry.endpoint), hash_salt),
244
+ )
245
+ } else {
246
+ let endpoints = Vc::cell(primary.iter().map(|entry| entry.endpoint).collect());
247
+ @@ -204,8 +218,9 @@ impl Asset for RoutesHashesManifestAsset {
248
+ sources_hash(
249
+ full_module_graph,
250
+ endpoints_entry_modules(base_module_graph, endpoints),
251
+ + hash_salt,
252
+ ),
253
+ - outputs_hash(endpoints_outputs(endpoints)),
254
+ + outputs_hash(endpoints_outputs(endpoints), hash_salt),
255
+ )
256
+ };
257
+ entrypoint_hashes.insert(key.as_str(), entry);
258
+ diff --git a/crates/next-api/src/server_actions.rs b/crates/next-api/src/server_actions.rs
259
+ index 050b35070e15c736eae4302a83b8d6411b89361d..7e666eefdfba1618c92bc4a95281e3b297b6a8b0 100644
260
+ --- a/crates/next-api/src/server_actions.rs
261
+ +++ b/crates/next-api/src/server_actions.rs
262
+ @@ -231,11 +231,11 @@ impl Asset for ServerActionManifestAsset {
263
+
264
+ let actions_value = self.actions.await?;
265
+ let async_module_info = self.module_graph.async_module_info();
266
+ - let durable_use_cache_entries = *self
267
+ - .project
268
+ - .next_config()
269
+ + let next_config = self.project.next_config();
270
+ + let durable_use_cache_entries = *next_config
271
+ .enable_durable_use_cache_entries(self.project.next_mode())
272
+ .await?;
273
+ + let hash_salt = next_config.output_hash_salt();
274
+
275
+ let loader_id = self.chunk_item.id().await?;
276
+ let loader_id = match &loader_id {
277
+ @@ -279,6 +279,7 @@ impl Asset for ServerActionManifestAsset {
278
+ *self.module_graph,
279
+ **module,
280
+ *self.chunking_context,
281
+ + hash_salt,
282
+ )
283
+ .await?,
284
+ )
285
+ @@ -361,6 +362,7 @@ async fn compute_subtree_content_hash(
286
+ module_graph: ResolvedVc<ModuleGraph>,
287
+ entry: ResolvedVc<Box<dyn Module>>,
288
+ chunking_context: Vc<Box<dyn ChunkingContext>>,
289
+ + hash_salt: Vc<RcStr>,
290
+ ) -> Result<Vc<RcStr>> {
291
+ let span = tracing::info_span!(
292
+ "compute use-cache code hash",
293
+ @@ -408,8 +410,14 @@ async fn compute_subtree_content_hash(
294
+ .map(async |m| Ok(format!(
295
+ " '{}': {}",
296
+ m.ident_string().await?,
297
+ - module_hash(*module_graph, chunking_context, async_module_info, **m)
298
+ - .await?
299
+ + module_hash(
300
+ + *module_graph,
301
+ + chunking_context,
302
+ + async_module_info,
303
+ + **m,
304
+ + hash_salt
305
+ + )
306
+ + .await?
307
+ )))
308
+ .try_join()
309
+ .await?
310
+ @@ -419,7 +427,15 @@ async fn compute_subtree_content_hash(
311
+
312
+ let hashes = modules
313
+ .into_iter()
314
+ - .map(|m| module_hash(*module_graph, chunking_context, async_module_info, *m))
315
+ + .map(|m| {
316
+ + module_hash(
317
+ + *module_graph,
318
+ + chunking_context,
319
+ + async_module_info,
320
+ + *m,
321
+ + hash_salt,
322
+ + )
323
+ + })
324
+ .try_join()
325
+ .await?;
326
+
327
+ @@ -448,6 +464,7 @@ async fn module_hash(
328
+ chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
329
+ async_module_info: ResolvedVc<AsyncModulesInfo>,
330
+ m: ResolvedVc<Box<dyn Module>>,
331
+ + hash_salt: Vc<RcStr>,
332
+ ) -> Result<Vc<RcStr>> {
333
+ let ident = m.ident();
334
+ let ident_value = ident.await?;
335
+ @@ -484,7 +501,7 @@ async fn module_hash(
336
+ .await?
337
+ .with_context(|| format!("failed to get source for module {ident_str}"))?
338
+ .content()
339
+ - .hash(HashAlgorithm::Xxh3Hash128Hex)
340
+ + .hash(hash_salt, HashAlgorithm::Xxh3Hash128Hex)
341
+ .await?;
342
+ Ok(Vc::cell(RcStr::from(deterministic_hash(
343
+ "",
344
+ diff --git a/packages/next/src/build/adapter/build-complete.ts b/packages/next/src/build/adapter/build-complete.ts
345
+ index f38163fba9b2e14c170321155ee2300b071ea428..06b283db29ff09ffd8bec8e4d1fb3da6d7d03a89 100644
346
+ --- a/packages/next/src/build/adapter/build-complete.ts
347
+ +++ b/packages/next/src/build/adapter/build-complete.ts
348
+ @@ -1046,7 +1046,8 @@ export async function handleBuildComplete({
349
+ existingOutput.assetsHashes,
350
+ path.relative(repoRoot, pageFile),
351
+ pageFile,
352
+ - bundler
353
+ + bundler,
354
+ + config.experimental.outputHashSalt || ''
355
+ )
356
+ continue
357
+ }
358
+ @@ -2170,6 +2171,7 @@ async function getSharedNodeAssets({
359
+ const pagesSharedNodeAssetsHashes: Record<string, string> = {}
360
+ const appPagesSharedNodeAssets: Record<string, string> = {}
361
+ const appPagesSharedNodeAssetsHashes: Record<string, string> = {}
362
+ + const salt = config.experimental.outputHashSalt || ''
363
+
364
+ const moduleTypes = ['app-page', 'pages'] as const
365
+
366
+ @@ -2201,7 +2203,8 @@ async function getSharedNodeAssets({
367
+ pagesSharedNodeAssetsHashes,
368
+ rootRelativeFilePath,
369
+ path.join(repoRoot, rootRelativeFilePath),
370
+ - bundler
371
+ + bundler,
372
+ + salt
373
+ )
374
+ } else {
375
+ await pushAsset(
376
+ @@ -2209,7 +2212,8 @@ async function getSharedNodeAssets({
377
+ appPagesSharedNodeAssetsHashes,
378
+ rootRelativeFilePath,
379
+ path.join(repoRoot, rootRelativeFilePath),
380
+ - bundler
381
+ + bundler,
382
+ + salt
383
+ )
384
+ }
385
+ }
386
+ @@ -2226,7 +2230,8 @@ async function getSharedNodeAssets({
387
+ sharedNodeAssetsHashes,
388
+ path.relative(repoRoot, setupNodeStubPath),
389
+ require.resolve('next/dist/build/adapter/setup-node-env.external'),
390
+ - bundler
391
+ + bundler,
392
+ + salt
393
+ )
394
+
395
+ // Turbopack handles this automatically and these files are listed in the nft.json files.
396
+ @@ -2315,7 +2320,8 @@ async function getSharedNodeAssets({
397
+ sharedNodeAssetsHashes,
398
+ path.relative(repoRoot, absoluteFilePath),
399
+ absoluteFilePath,
400
+ - bundler
401
+ + bundler,
402
+ + salt
403
+ )
404
+ }
405
+ }
406
+ @@ -2338,6 +2344,7 @@ async function getSharedNodeAssets({
407
+ fileOutputPath,
408
+ path.join(distDir, 'server', 'instrumentation.js'),
409
+ bundler,
410
+ + salt,
411
+ instrumentationEntryHash
412
+ )
413
+ }
414
+ @@ -2352,7 +2359,8 @@ async function getSharedNodeAssets({
415
+ sharedNodeAssetsHashes,
416
+ fileOutputPath,
417
+ filePath,
418
+ - bundler
419
+ + bundler,
420
+ + salt
421
+ )
422
+ }
423
+
424
+ @@ -2372,13 +2380,14 @@ async function pushAsset(
425
+ targetFilePath: string,
426
+ sourceFilePath: string,
427
+ bundler: Bundler,
428
+ + salt: string,
429
+ hashOverride?: string
430
+ ) {
431
+ if (!(targetFilePath in assets)) {
432
+ assets[targetFilePath] = sourceFilePath
433
+ if (bundler === Bundler.Turbopack) {
434
+ assetsHashes[targetFilePath] =
435
+ - hashOverride ?? (await hashFile(sourceFilePath))
436
+ + hashOverride ?? (await hashFile(salt, sourceFilePath))
437
+ }
438
+ }
439
+ }
440
+ @@ -2411,8 +2420,9 @@ async function loadNFT(
441
+ return { entryHash }
442
+ }
443
+
444
+ -async function hashFile(filePath: string): Promise<string> {
445
+ +async function hashFile(salt: string, filePath: string): Promise<string> {
446
+ const hash = crypto.createHash('sha256')
447
+ + hash.update(salt)
448
+ try {
449
+ // Try symlink first, since readFile just transparently resolves those (or fails if it's a
450
+ // directory symlink).
451
+ diff --git a/turbopack/crates/turbo-tasks-fs/src/lib.rs b/turbopack/crates/turbo-tasks-fs/src/lib.rs
452
+ index 5546fc1001e90e436b64a529388c67ec86457933..d99202da6518e2f28e852554fdcb881bb75a1912 100644
453
+ --- a/turbopack/crates/turbo-tasks-fs/src/lib.rs
454
+ +++ b/turbopack/crates/turbo-tasks-fs/src/lib.rs
455
+ @@ -2531,9 +2531,12 @@ impl FileContent {
456
+ }
457
+
458
+ #[turbo_tasks::function]
459
+ - pub fn hash(&self, algorithm: HashAlgorithm) -> Vc<RcStr> {
460
+ - // no_hash_salt
461
+ - Vc::cell(RcStr::from(deterministic_hash("", self, algorithm)))
462
+ + pub async fn hash(&self, salt: Vc<RcStr>, algorithm: HashAlgorithm) -> Result<Vc<RcStr>> {
463
+ + Ok(Vc::cell(RcStr::from(deterministic_hash(
464
+ + &salt.await?,
465
+ + self,
466
+ + algorithm,
467
+ + ))))
468
+ }
469
+
470
+ /// Converts this [`FileContent`] into a [`PersistedFileContent`] by cloning.
471
+ diff --git a/turbopack/crates/turbopack-core/src/asset.rs b/turbopack/crates/turbopack-core/src/asset.rs
472
+ index 65cf0e7ecb3f1721ed80cfc7b99a825220a6ab65..860dd6bf169a58a817467dea8dd8e9d0607751b3 100644
473
+ --- a/turbopack/crates/turbopack-core/src/asset.rs
474
+ +++ b/turbopack/crates/turbopack-core/src/asset.rs
475
+ @@ -131,14 +131,14 @@ impl AssetContent {
476
+ }
477
+
478
+ #[turbo_tasks::function]
479
+ - pub fn hash(&self, algorithm: HashAlgorithm) -> Vc<RcStr> {
480
+ - match self {
481
+ - AssetContent::File(content) => content.hash(algorithm),
482
+ + pub async fn hash(&self, salt: Vc<RcStr>, algorithm: HashAlgorithm) -> Result<Vc<RcStr>> {
483
+ + Ok(match self {
484
+ + AssetContent::File(content) => content.hash(salt, algorithm),
485
+ AssetContent::Redirect { target, link_type } => Vc::cell(RcStr::from(
486
+ // no_hash_salt
487
+ - deterministic_hash("", (target, link_type), algorithm),
488
+ + deterministic_hash(&salt.await?, (target, link_type), algorithm),
489
+ )),
490
+ - }
491
+ + })
492
+ }
493
+
494
+ /// Compared to [AssetContent::hash], this hashes only the bytes of the file content and
nextjs-95738-assets-hash-salt/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-95738-assets-hash-salt/tests/Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ 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
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && 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' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+
33
+ RUN useradd --create-home --shell /bin/bash verifier \
34
+ && chown -R verifier:verifier /app /opt/uv-cache \
35
+ && mkdir -p /opt/selfbench \
36
+ && chmod 700 /opt/selfbench \
37
+ && mkdir -p /home/verifier/.cache/uv \
38
+ && chown -R verifier:verifier /home/verifier/.cache
39
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
40
+ UV_NO_BUILD_ISOLATION=1
41
+ COPY test.patch test.sh /tests/
42
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
43
+ WORKDIR /app
nextjs-95738-assets-hash-salt/tests/test.patch ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/production/deterministic-build/adapter-content-hashes.test.ts b/test/production/deterministic-build/adapter-content-hashes.test.ts
2
+ index ece2fe51b9893389cecc4b03b59a781c0a80f552..d14d53680c89ed9e23da1fb3eed1db5e2b9c72ec 100644
3
+ --- a/test/production/deterministic-build/adapter-content-hashes.test.ts
4
+ +++ b/test/production/deterministic-build/adapter-content-hashes.test.ts
5
+ @@ -61,6 +61,56 @@ import { FILES } from './files'
6
+ outputs.pagesApi.forEach(validateOutput)
7
+ outputs.appRoutes.forEach(validateOutput)
8
+ })
9
+ +
10
+ + it('hashes respect NEXT_HASH_SALT', async () => {
11
+ + const {
12
+ + outputs: outputs1,
13
+ + }: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON(
14
+ + 'build-complete.json'
15
+ + )
16
+ +
17
+ + await next.stop()
18
+ + next.env.NEXT_HASH_SALT = 'something-else'
19
+ + await next.build()
20
+ +
21
+ + const {
22
+ + outputs: outputs2,
23
+ + }: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON(
24
+ + 'build-complete.json'
25
+ + )
26
+ +
27
+ + let functions1 = Object.fromEntries(
28
+ + [
29
+ + ...outputs1.pages,
30
+ + ...outputs1.pagesApi,
31
+ + ...outputs1.appPages,
32
+ + ...outputs1.appRoutes,
33
+ + ].map((output) => [output.pathname, output.assetsHashes])
34
+ + )
35
+ + let functions2 = Object.fromEntries(
36
+ + [
37
+ + ...outputs2.pages,
38
+ + ...outputs2.pagesApi,
39
+ + ...outputs2.appPages,
40
+ + ...outputs2.appRoutes,
41
+ + ].map((output) => [output.pathname, output.assetsHashes])
42
+ + )
43
+ +
44
+ + for (const pathname in functions1) {
45
+ + const function1 = functions1[pathname]
46
+ + const function2 = functions2[pathname]
47
+ + for (const file in function1) {
48
+ + const hash1 = function1[file]
49
+ + const hash2 = function2[file]
50
+ + expect(hash1).toBeString()
51
+ + if (hash1 === hash2) {
52
+ + throw new Error(
53
+ + `Hash for ${pathname} file ${file} did not change with NEXT_HASH_SALT: ${hash1}`
54
+ + )
55
+ + }
56
+ + }
57
+ + }
58
+ + })
59
+ })
60
+ }
61
+ )
nextjs-95738-assets-hash-salt/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/production/deterministic-build/adapter-content-hashes.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/production/deterministic-build/adapter-content-hashes.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/production/deterministic-build/adapter-content-hashes.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ 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
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ 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
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ 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
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-95799-async-route-init-errors/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && NEXT_TELEMETRY_DISABLED=1 pnpm build' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-95799-async-route-init-errors/solution/gold.patch ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/server/route-modules/app-route/module.ts b/packages/next/src/server/route-modules/app-route/module.ts
2
+ index 3718f09b25..d8c4820dd4 100644
3
+ --- a/packages/next/src/server/route-modules/app-route/module.ts
4
+ +++ b/packages/next/src/server/route-modules/app-route/module.ts
5
+ @@ -235,6 +235,9 @@ export class AppRouteRouteModule extends RouteModule<
6
+ // Non-null while an async userland module (top-level await) is loading.
7
+ // ensureUserland() awaits this before the first request is handled.
8
+ private _pendingUserland: Promise<void> | null = null
9
+ + // Init error from an async userland module, rethrown by ensureUserland().
10
+ + private _initError: unknown = null
11
+ + private _hasInitError = false
12
+ // Synchronous per-request userland getter for Turbopack dev mode.
13
+ // Called on every request to pick up server HMR updates.
14
+ private readonly _getUserland?: () => AppRouteUserlandModule
15
+ @@ -252,7 +255,12 @@ export class AppRouteRouteModule extends RouteModule<
16
+ this._pendingUserland = result.then((mod) => {
17
+ this._userland = mod
18
+ this._pendingUserland = null
19
+ - this._initFromUserland()
20
+ + try {
21
+ + this._initFromUserland()
22
+ + } catch (err) {
23
+ + this._initError = err
24
+ + this._hasInitError = true
25
+ + }
26
+ })
27
+ } else {
28
+ this._userland = result
29
+ @@ -275,6 +283,9 @@ export class AppRouteRouteModule extends RouteModule<
30
+ if (this._pendingUserland) {
31
+ await this._pendingUserland
32
+ }
33
+ + if (this._hasInitError) {
34
+ + throw this._initError
35
+ + }
36
+ }
37
+
38
+ constructor({
39
+ @@ -312,7 +323,12 @@ export class AppRouteRouteModule extends RouteModule<
40
+ this._pendingUserland = result.then((mod) => {
41
+ this._userland = mod
42
+ this._pendingUserland = null
43
+ - this._initFromUserland()
44
+ + try {
45
+ + this._initFromUserland()
46
+ + } catch (err) {
47
+ + this._initError = err
48
+ + this._hasInitError = true
49
+ + }
50
+ })
51
+ } else {
52
+ this._userland = result
nextjs-95799-async-route-init-errors/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-95799-async-route-init-errors/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && NEXT_TELEMETRY_DISABLED=1 pnpm build' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-95799-async-route-init-errors/tests/test.patch ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ new file mode 100644
3
+ index 00000000..b26a97fd
4
+ --- /dev/null
5
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/api/data/route.ts
6
+ @@ -0,0 +1,6 @@
7
+ +// Top-level await makes this an async module.
8
+ +await Promise.resolve()
9
+ +
10
+ +export async function GET() {
11
+ + return Response.json({ ok: true })
12
+ +}
13
+ 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
14
+ new file mode 100644
15
+ index 00000000..888614de
16
+ --- /dev/null
17
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/layout.tsx
18
+ @@ -0,0 +1,8 @@
19
+ +import { ReactNode } from 'react'
20
+ +export default function Root({ children }: { children: ReactNode }) {
21
+ + return (
22
+ + <html>
23
+ + <body>{children}</body>
24
+ + </html>
25
+ + )
26
+ +}
27
+ 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
28
+ new file mode 100644
29
+ index 00000000..ff7159d9
30
+ --- /dev/null
31
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/app/page.tsx
32
+ @@ -0,0 +1,3 @@
33
+ +export default function Page() {
34
+ + return <p>hello world</p>
35
+ +}
36
+ 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
37
+ new file mode 100644
38
+ index 00000000..fecf9218
39
+ --- /dev/null
40
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/invalid/next.config.js
41
+ @@ -0,0 +1,8 @@
42
+ +/**
43
+ + * @type {import('next').NextConfig}
44
+ + */
45
+ +const nextConfig = {
46
+ + output: 'export',
47
+ +}
48
+ +
49
+ +module.exports = nextConfig
50
+ 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
51
+ new file mode 100644
52
+ index 00000000..c60b6bb7
53
+ --- /dev/null
54
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/api/data/route.ts
55
+ @@ -0,0 +1,8 @@
56
+ +// Top-level await makes this an async module.
57
+ +await Promise.resolve()
58
+ +
59
+ +export const dynamic = 'force-static'
60
+ +
61
+ +export async function GET() {
62
+ + return Response.json({ ok: true })
63
+ +}
64
+ 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
65
+ new file mode 100644
66
+ index 00000000..888614de
67
+ --- /dev/null
68
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/layout.tsx
69
+ @@ -0,0 +1,8 @@
70
+ +import { ReactNode } from 'react'
71
+ +export default function Root({ children }: { children: ReactNode }) {
72
+ + return (
73
+ + <html>
74
+ + <body>{children}</body>
75
+ + </html>
76
+ + )
77
+ +}
78
+ 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
79
+ new file mode 100644
80
+ index 00000000..ff7159d9
81
+ --- /dev/null
82
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/app/page.tsx
83
+ @@ -0,0 +1,3 @@
84
+ +export default function Page() {
85
+ + return <p>hello world</p>
86
+ +}
87
+ 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
88
+ new file mode 100644
89
+ index 00000000..fecf9218
90
+ --- /dev/null
91
+ +++ b/test/production/app-dir/output-export-async-route-module/fixtures/valid/next.config.js
92
+ @@ -0,0 +1,8 @@
93
+ +/**
94
+ + * @type {import('next').NextConfig}
95
+ + */
96
+ +const nextConfig = {
97
+ + output: 'export',
98
+ +}
99
+ +
100
+ +module.exports = nextConfig
101
+ 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
102
+ new file mode 100644
103
+ index 00000000..0c8ac29a
104
+ --- /dev/null
105
+ +++ b/test/production/app-dir/output-export-async-route-module/output-export-async-route-module.test.ts
106
+ @@ -0,0 +1,36 @@
107
+ +import { join } from 'path'
108
+ +import { nextTestSetup } from 'e2e-utils'
109
+ +
110
+ +describe('output-export-async-route-module', () => {
111
+ + describe('invalid route', () => {
112
+ + const { next } = nextTestSetup({
113
+ + files: join(__dirname, 'fixtures', 'invalid'),
114
+ + skipStart: true,
115
+ + })
116
+ +
117
+ + // The route module uses top-level await, so its `output: 'export'`
118
+ + // validation runs after the module settles instead of throwing during
119
+ + // require(). The resulting error must still fail the build.
120
+ + it('fails the build when an async route module is not statically exportable', async () => {
121
+ + const { exitCode, cliOutput } = await next.build()
122
+ + expect(cliOutput).toContain(
123
+ + 'not configured on route "/api/data" with "output: export"'
124
+ + )
125
+ + expect(exitCode).toEqual(expect.any(Number))
126
+ + expect(exitCode).not.toBe(0)
127
+ + })
128
+ + })
129
+ +
130
+ + describe('valid route', () => {
131
+ + const { next } = nextTestSetup({
132
+ + files: join(__dirname, 'fixtures', 'valid'),
133
+ + skipStart: true,
134
+ + })
135
+ +
136
+ + it('exports an async route module that is statically exportable', async () => {
137
+ + const { exitCode } = await next.build()
138
+ + expect(exitCode).toBe(0)
139
+ + expect(await next.readFile('out/api/data')).toBe('{"ok":true}')
140
+ + })
141
+ + })
142
+ +})
nextjs-95799-async-route-init-errors/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ 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
59
+ 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
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ 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
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ 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
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ 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
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'true'; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-95946-file-sourcemaps/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build && pnpm exec playwright install --with-deps chromium' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-95946-file-sourcemaps/solution/gold.patch ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/server/dev/hot-reloader-turbopack.ts b/packages/next/src/server/dev/hot-reloader-turbopack.ts
2
+ index 0fb2cb77bb..6c76ac9af4 100644
3
+ --- a/packages/next/src/server/dev/hot-reloader-turbopack.ts
4
+ +++ b/packages/next/src/server/dev/hot-reloader-turbopack.ts
5
+ @@ -1,7 +1,9 @@
6
+ import type { Socket } from 'net'
7
+ import { mkdir, writeFile } from 'fs/promises'
8
+ +import { realpathSync } from 'fs'
9
+ import * as inspector from 'inspector'
10
+ -import { join, extname, relative } from 'path'
11
+ +import { join, extname, relative, isAbsolute } from 'path'
12
+ +import { fileURLToPath, pathToFileURL } from 'url'
13
+
14
+ import ws from 'next/dist/compiled/ws'
15
+
16
+ @@ -84,6 +86,7 @@ import type { ModernSourceMapPayload } from '../lib/source-maps'
17
+ import { isDeferredEntry } from '../../build/entries'
18
+ import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
19
+ import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'
20
+ +import { setBundlerFindSourceMapURLImplementation } from '../lib/source-maps'
21
+ import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
22
+ import {
23
+ formatIssue,
24
+ @@ -279,6 +282,47 @@ function getSourceMapFromTurbopack(
25
+ }
26
+ }
27
+
28
+ +function getSourceMapURLFromTurbopack(
29
+ + distDir: string,
30
+ + scriptNameOrSourceURL: string
31
+ +): string | null {
32
+ + // React invokes this with the raw stack-frame filename, which arrives
33
+ + // either as an absolute filesystem path or as a `file:` URL. Anything else
34
+ + // (`file:` URLs with a query are eval'd server HMR modules carrying inline
35
+ + // source maps, `webpack-internal://`, `node:internal/...`, `<anonymous>`,
36
+ + // ...) is not something we have an emitted source map for.
37
+ + let scriptPath = scriptNameOrSourceURL
38
+ + if (scriptNameOrSourceURL.startsWith('file://')) {
39
+ + if (scriptNameOrSourceURL.includes('?')) {
40
+ + return null
41
+ + }
42
+ + try {
43
+ + scriptPath = fileURLToPath(scriptNameOrSourceURL)
44
+ + } catch {
45
+ + return null
46
+ + }
47
+ + }
48
+ + if (!isAbsolute(scriptPath)) {
49
+ + return null
50
+ + }
51
+ +
52
+ + // Only chunks emitted into `distDir` have an on-disk source map to point at.
53
+ + const relativePath = relative(distDir, scriptPath)
54
+ + if (
55
+ + relativePath.startsWith('..') ||
56
+ + // On Windows an absolute path on a different drive is returned unchanged
57
+ + // rather than as a `..`-prefixed relative path.
58
+ + isAbsolute(relativePath)
59
+ + ) {
60
+ + return null
61
+ + }
62
+ +
63
+ + // The emitted source map lives next to its chunk with a `.map` suffix (see
64
+ + // `SourceMapAsset::path`). Encode through `pathToFileURL` so any special
65
+ + // characters in the path are escaped into a well-formed `file:` URL.
66
+ + return pathToFileURL(scriptPath + '.map').href
67
+ +}
68
+ +
69
+ export async function createHotReloaderTurbopack(
70
+ opts: SetupOpts & { isSrcDir: boolean },
71
+ serverFields: ServerFields,
72
+ @@ -410,6 +454,14 @@ export async function createHotReloaderTurbopack(
73
+ getSourceMapFromTurbopack.bind(null, project)
74
+ )
75
+
76
+ + let canonicalDistDir = distDir
77
+ + try {
78
+ + canonicalDistDir = realpathSync(distDir)
79
+ + } catch {}
80
+ + setBundlerFindSourceMapURLImplementation(
81
+ + getSourceMapURLFromTurbopack.bind(null, canonicalDistDir)
82
+ + )
83
+ +
84
+ // Set up code frame renderer using native bindings
85
+ const { installCodeFrameSupport } =
86
+ require('../lib/install-code-frame') as typeof import('../lib/install-code-frame')
87
+ @@ -417,6 +469,7 @@ export async function createHotReloaderTurbopack(
88
+
89
+ opts.onDevServerCleanup?.(async () => {
90
+ setBundlerFindSourceMapImplementation(() => undefined)
91
+ + setBundlerFindSourceMapURLImplementation(() => null)
92
+ await project.onExit()
93
+ await lockfile?.unlock()
94
+ })
95
+ diff --git a/packages/next/src/server/lib/source-maps.ts b/packages/next/src/server/lib/source-maps.ts
96
+ index 40b3a2204c..10f8a4880b 100644
97
+ --- a/packages/next/src/server/lib/source-maps.ts
98
+ +++ b/packages/next/src/server/lib/source-maps.ts
99
+ @@ -158,6 +158,36 @@ export function filterStackFrameDEV(
100
+ }
101
+ }
102
+
103
+ +// `scriptNameOrSourceURL` is what React forwards from the stack frame: the
104
+ +// script's `getScriptNameOrSourceURL()`, which for the server chunks we can
105
+ +// map is an absolute filesystem path, not a URL. The returned value is the
106
+ +// source map's URL (`file:` or `data:`).
107
+ +type FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null
108
+ +// Find the URL of a source map using the bundler's API.
109
+ +// Shared via `globalThis` because this module is compiled both into the server
110
+ +// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`
111
+ +// (where the dev server registers the implementation), and each copy has its own
112
+ +// module state.
113
+ +const bundlerFindSourceMapURLSymbol = Symbol.for(
114
+ + 'next.server.bundlerFindSourceMapURL'
115
+ +)
116
+ +
117
+ +export function setBundlerFindSourceMapURLImplementation(
118
+ + findSourceMapURLImplementation: FindSourceMapURL
119
+ +): void {
120
+ + ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =
121
+ + findSourceMapURLImplementation
122
+ +}
123
+ +
124
+ +function bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {
125
+ + const implementation: FindSourceMapURL | undefined = (globalThis as any)[
126
+ + bundlerFindSourceMapURLSymbol
127
+ + ]
128
+ + return implementation === undefined
129
+ + ? null
130
+ + : implementation(scriptNameOrSourceURL)
131
+ +}
132
+ +
133
+ const invalidSourceMap = Symbol('invalid-source-map')
134
+ const sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(
135
+ 512 * 1024 * 1024,
136
+ @@ -172,6 +202,19 @@ const sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(
137
+ export function findSourceMapURLDEV(
138
+ scriptNameOrSourceURL: string
139
+ ): string | null {
140
+ + try {
141
+ + const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)
142
+ + if (bundlerSourceMapURL !== null) {
143
+ + return bundlerSourceMapURL
144
+ + }
145
+ + } catch (cause) {
146
+ + console.error(
147
+ + `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`
148
+ + )
149
+ + }
150
+ +
151
+ + // No bundler implementation (e.g. Webpack): inline the source map Node.js
152
+ + // knows as a `data:` URL.
153
+ let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)
154
+ if (sourceMapURL === undefined) {
155
+ let sourceMapPayload: ModernSourceMapPayload | undefined
156
+ diff --git a/packages/next/src/server/patch-error-inspect.ts b/packages/next/src/server/patch-error-inspect.ts
157
+ index be16e4727b..2aa0025d1e 100644
158
+ --- a/packages/next/src/server/patch-error-inspect.ts
159
+ +++ b/packages/next/src/server/patch-error-inspect.ts
160
+ @@ -181,7 +181,10 @@ function getSourcemappedFrameIfPossible(
161
+ let sourceMapConsumer: SyncSourceMapConsumer
162
+ let sourceMapPayload: ModernSourceMapPayload
163
+ if (sourceMapCacheEntry === undefined) {
164
+ - let sourceURL = frame.file
165
+ + // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)
166
+ + // have their positions padded to match the underlying chunk, so they
167
+ + // resolve via the chunk's source map.
168
+ + let sourceURL = devirtualizeReactServerURL(frame.file)
169
+ // e.g. "/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js"
170
+ // or "C:\Users\foo\APP\.next\server\chunks\ssr\[root-of-the-server]__2934a0._.js"
171
+ // will be keyed by Node.js as "file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js".
172
+ @@ -189,8 +192,8 @@ function getSourcemappedFrameIfPossible(
173
+ //
174
+ // But frame.file might also be "webpack-internal:///(rsc)/./app/bad-sourcemap/page.js" or
175
+ // "<anonymous>" or "node:internal/process/task_queues" here
176
+ - if (path.isAbsolute(frame.file)) {
177
+ - sourceURL = url.pathToFileURL(frame.file).toString()
178
+ + if (path.isAbsolute(sourceURL)) {
179
+ + sourceURL = url.pathToFileURL(sourceURL).toString()
180
+ }
181
+ let maybeSourceMapPayload: ModernSourceMapPayload | undefined
182
+ try {
183
+ @@ -228,10 +231,9 @@ function getSourcemappedFrameIfPossible(
184
+ // is sufficient to compute relative paths but is actually wrong (the
185
+ // chunk and sourcemap have different content hashes). We are using the
186
+ // node API to read the sourcemap and it doesn't give us access to the
187
+ - // URI. Devirtualize `about://React/Server/file:///path/to/chunk.js?4` to
188
+ - // `file:///path/to/chunk.js` so that relative `sources` in the source map
189
+ - // resolve against the real chunk URL, not the virtual one.
190
+ - const sourceMapURL = devirtualizeReactServerURL(sourceURL) + '.map'
191
+ + // URI. `sourceURL` is already devirtualized so that relative `sources`
192
+ + // resolve against the real chunk URL, not React's virtual one.
193
+ + const sourceMapURL = sourceURL + '.map'
194
+ sourceMapConsumer = new SyncSourceMapConsumer(
195
+ sourceMapPayload,
196
+ // @ts-expect-error: our typings don't include this parameter but it is here.
nextjs-95946-file-sourcemaps/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-95946-file-sourcemaps/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build && pnpm exec playwright install --with-deps chromium' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-95946-file-sourcemaps/tests/test.patch ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ index be03cedc70..f59cd54945 100644
3
+ --- a/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts
4
+ +++ b/test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts
5
+ @@ -229,6 +229,21 @@ describe('app-dir - server source maps - fake frame source maps', () => {
6
+ }).toEqual({ url: script.url, hasSourceMap: true })
7
+ }
8
+
9
+ + if (isTurbopack) {
10
+ + // The resolver silently falls back to inlining `data:` URLs, so a
11
+ + // defect in the `file:` URL derivation keeps all behavior-based
12
+ + // assertions green. Only this assertion catches it.
13
+ + for (const script of fakeScripts) {
14
+ + expect({
15
+ + url: script.url,
16
+ + sourceMapURL: script.sourceMapURL,
17
+ + }).toEqual({
18
+ + url: script.url,
19
+ + sourceMapURL: expect.stringMatching(/^file:/),
20
+ + })
21
+ + }
22
+ + }
23
+ +
24
+ // Resolve each source map like a debugger frontend and map the
25
+ // padded `_()` call position of each fake function back to its
26
+ // original source, like clicking the frame in a debugger would.
27
+ @@ -282,6 +297,88 @@ describe('app-dir - server source maps - fake frame source maps', () => {
28
+ session.close()
29
+ }
30
+ })
31
+ +
32
+ + it('fake stack frames from nested Flight requests are resolvable by an attached debugger', async () => {
33
+ + // Rendering this page produces fake frame scripts whose frame
34
+ + // filenames are `file:` URLs rather than file paths.
35
+ + await next.render('/rsc-error-throw-cached')
36
+ +
37
+ + const target = await findServerInspectorTarget()
38
+ + const session = await CDPSession.connect(target.webSocketDebuggerUrl)
39
+ + try {
40
+ + const evalScripts: {
41
+ + scriptId: string
42
+ + url: string
43
+ + sourceMapURL: string
44
+ + }[] = []
45
+ + session.onEvent = (method, params) => {
46
+ + if (method === 'Debugger.scriptParsed' && params.hasSourceURL) {
47
+ + evalScripts.push({
48
+ + scriptId: params.scriptId,
49
+ + url: params.url,
50
+ + sourceMapURL: params.sourceMapURL ?? '',
51
+ + })
52
+ + }
53
+ + }
54
+ + await session.send('Debugger.enable', { maxScriptsCacheSize: 1 })
55
+ +
56
+ + await retry(async () => {
57
+ + expect(
58
+ + evalScripts.filter((script) =>
59
+ + script.url.startsWith('about://React/Cache/')
60
+ + ).length
61
+ + ).toBeGreaterThan(0)
62
+ + })
63
+ +
64
+ + // React emits a fake frame script under `about://React/` with a
65
+ + // source map, or, when no source map could be found for it, under
66
+ + // the frame's raw filename without one.
67
+ + const fakeScripts = evalScripts.filter(
68
+ + (script) =>
69
+ + script.url.startsWith('about://React/') ||
70
+ + (script.url.startsWith('file:') && script.sourceMapURL === '')
71
+ + )
72
+ + const mappedSources = new Set<string>()
73
+ + for (const script of fakeScripts) {
74
+ + expect({
75
+ + url: script.url,
76
+ + hasSourceMap: script.sourceMapURL !== '',
77
+ + }).toEqual({ url: script.url, hasSourceMap: true })
78
+ +
79
+ + const { sourceMap, mapURL } = await resolveSourceMapLikeADebugger(
80
+ + session,
81
+ + script.url,
82
+ + script.sourceMapURL
83
+ + )
84
+ + const { scriptSource } = await session.send(
85
+ + 'Debugger.getScriptSource',
86
+ + { scriptId: script.scriptId }
87
+ + )
88
+ + const callIndex = scriptSource.indexOf('_()')
89
+ + if (callIndex === -1) continue
90
+ + const line = scriptSource.slice(0, callIndex).split('\n').length
91
+ + const column =
92
+ + callIndex - (scriptSource.lastIndexOf('\n', callIndex) + 1)
93
+ +
94
+ + const consumer = new SourceMap(sourceMap)
95
+ + const original = consumer.findEntry(line - 1, column)
96
+ + if (original.originalSource !== undefined) {
97
+ + mappedSources.add(
98
+ + mapURL === null
99
+ + ? original.originalSource
100
+ + : new URL(original.originalSource, mapURL).href
101
+ + )
102
+ + }
103
+ + }
104
+ +
105
+ + const testDirURL = url.pathToFileURL(fs.realpathSync(next.testDir))
106
+ + expect([...mappedSources]).toContain(
107
+ + `${testDirURL.href}/app/rsc-error-throw-cached/page.js`
108
+ + )
109
+ + } finally {
110
+ + session.close()
111
+ + }
112
+ + })
113
+ } else {
114
+ it('server chunk source maps are resolvable by an attached debugger', async () => {
115
+ await next.render('/rsc-error-log')
nextjs-95946-file-sourcemaps/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ 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
59
+ git -C /app clean -fd -- 'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ 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
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm build && pnpm test-dev-turbo '"'"'test/e2e/app-dir/server-source-maps/fake-frame-source-maps.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ 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
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-95967-single-learn-more-links/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm build --filter=next' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-95967-single-learn-more-links/solution/gold.patch ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/next-devtools/dev-overlay/container/errors.tsx b/packages/next/src/next-devtools/dev-overlay/container/errors.tsx
2
+ index 38294ad223..3fd4d073de 100644
3
+ --- a/packages/next/src/next-devtools/dev-overlay/container/errors.tsx
4
+ +++ b/packages/next/src/next-devtools/dev-overlay/container/errors.tsx
5
+ @@ -441,9 +441,9 @@ export function getBlockingRouteErrorDetails(
6
+ }
7
+
8
+ const isBlockingPageLoadError =
9
+ - message.includes('/blocking-prerender-runtime#') ||
10
+ - message.includes('/blocking-prerender-dynamic#') ||
11
+ - message.includes('/instant-shell-url-data#')
12
+ + message.includes('/blocking-prerender-runtime') ||
13
+ + message.includes('/blocking-prerender-dynamic') ||
14
+ + message.includes('/instant-shell-url-data')
15
+ if (isBlockingPageLoadError) {
16
+ return {
17
+ type: 'blocking-route',
18
+ diff --git a/packages/next/src/server/app-render/blocking-route-messages.ts b/packages/next/src/server/app-render/blocking-route-messages.ts
19
+ index 7cc4164862..ea60a1fb0e 100644
20
+ --- a/packages/next/src/server/app-render/blocking-route-messages.ts
21
+ +++ b/packages/next/src/server/app-render/blocking-route-messages.ts
22
+ @@ -4,9 +4,8 @@ export function createRuntimeBodyError(route: string): Error {
23
+ `\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` accessed outside of \`<Suspense>\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` +
24
+ `Ways to fix this:\n` +
25
+ ` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
26
+ - ` https://nextjs.org/docs/messages/blocking-prerender-runtime#wrap-in-or-move-into-suspense\n` +
27
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
28
+ - ` https://nextjs.org/docs/messages/blocking-prerender-runtime#allow-blocking-route`
29
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
30
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-runtime`
31
+ )
32
+ }
33
+
34
+ @@ -16,11 +15,9 @@ export function createDynamicBodyError(route: string): Error {
35
+ `\`fetch(...)\` or \`connection()\` accessed outside of \`<Suspense>\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` +
36
+ `Ways to fix this:\n` +
37
+ ` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
38
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` +
39
+ ` - [cache] Cache the data access with \`"use cache"\` (does not apply to \`connection()\`)\n` +
40
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` +
41
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
42
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route`
43
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
44
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
45
+ )
46
+ }
47
+
48
+ @@ -30,9 +27,8 @@ export function createRuntimeBodyErrorInNavigation(route: string): Error {
49
+ `\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` accessed outside of \`<Suspense>\` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.\n\n` +
50
+ `Ways to fix this:\n` +
51
+ ` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
52
+ - ` https://nextjs.org/docs/messages/blocking-prerender-runtime#wrap-in-or-move-into-suspense\n` +
53
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
54
+ - ` https://nextjs.org/docs/messages/blocking-prerender-runtime#allow-blocking-route`
55
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
56
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-runtime`
57
+ )
58
+ }
59
+
60
+ @@ -42,9 +38,8 @@ export function createLinkBodyErrorInNavigation(route: string): Error {
61
+ `\`params\` or \`searchParams\` accessed outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` +
62
+ `Ways to fix this:\n` +
63
+ ` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
64
+ - ` https://nextjs.org/docs/messages/instant-shell-url-data#wrap-in-or-move-into-suspense\n` +
65
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
66
+ - ` https://nextjs.org/docs/messages/instant-shell-url-data#allow-blocking-route`
67
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
68
+ + `Learn more: https://nextjs.org/docs/messages/instant-shell-url-data`
69
+ )
70
+ }
71
+
72
+ @@ -54,11 +49,9 @@ export function createDynamicBodyErrorInNavigation(route: string): Error {
73
+ `\`fetch(...)\` or \`connection()\` accessed outside of \`<Suspense>\` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.\n\n` +
74
+ `Ways to fix this:\n` +
75
+ ` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
76
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` +
77
+ ` - [cache] Cache the data access with \`"use cache"\` (does not apply to \`connection()\`)\n` +
78
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` +
79
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
80
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route`
81
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
82
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
83
+ )
84
+ }
85
+
86
+ @@ -73,11 +66,9 @@ export function createDynamicOrRuntimeBodyError(route: string): Error {
87
+ `\`fetch(...)\`, \`cookies()\`, \`headers()\`, \`params\`, \`searchParams\`, or \`connection()\` accessed outside of \`<Suspense>\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\n\n` +
88
+ `Ways to fix this:\n` +
89
+ ` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
90
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#wrap-in-or-move-into-suspense\n` +
91
+ ` - [cache] For uncached data (\`fetch\`, database calls): cache the access with \`"use cache"\` (does not apply to \`connection()\`)\n` +
92
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#cache-the-component-or-data\n` +
93
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
94
+ - ` https://nextjs.org/docs/messages/blocking-prerender-dynamic#allow-blocking-route`
95
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
96
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
97
+ )
98
+ }
99
+
100
+ @@ -87,9 +78,8 @@ export function createLinkMetadataError(route: string): Error {
101
+ `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` +
102
+ `Ways to fix this:\n` +
103
+ ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
104
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` +
105
+ - ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n` +
106
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic`
107
+ + ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n\n` +
108
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime`
109
+ )
110
+ }
111
+
112
+ @@ -99,9 +89,8 @@ export function createRuntimeMetadataError(route: string): Error {
113
+ `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` +
114
+ `Ways to fix this:\n` +
115
+ ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
116
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` +
117
+ - ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n` +
118
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic`
119
+ + ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n\n` +
120
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime`
121
+ )
122
+ }
123
+
124
+ @@ -111,9 +100,8 @@ export function createDynamicMetadataError(route: string): Error {
125
+ `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` +
126
+ `Ways to fix this:\n` +
127
+ ` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (does not apply to \`connection()\`)\n` +
128
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#cache-the-metadata\n` +
129
+ - ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n` +
130
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#mark-the-route-as-dynamic`
131
+ + ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n\n` +
132
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic`
133
+ )
134
+ }
135
+
136
+ @@ -123,9 +111,8 @@ export function createLinkViewportError(route: string): Error {
137
+ `\`params\` or \`searchParams\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` +
138
+ `Ways to fix this:\n` +
139
+ ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
140
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` +
141
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
142
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route`
143
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
144
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime`
145
+ )
146
+ }
147
+
148
+ @@ -135,9 +122,8 @@ export function createRuntimeViewportError(route: string): Error {
149
+ `\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` +
150
+ `Ways to fix this:\n` +
151
+ ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
152
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` +
153
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
154
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route`
155
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
156
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime`
157
+ )
158
+ }
159
+
160
+ @@ -147,9 +133,8 @@ export function createDynamicViewportError(route: string): Error {
161
+ `\`fetch(...)\` or \`connection()\` in \`generateViewport()\` prevents the page from being prerendered, leading to a slower user experience.\n\n` +
162
+ `Ways to fix this:\n` +
163
+ ` - [cache] Cache the viewport data with \`"use cache"\` in \`generateViewport()\` (does not apply to \`connection()\`)\n` +
164
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\n` +
165
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
166
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route`
167
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
168
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic`
169
+ )
170
+ }
171
+
172
+ @@ -164,11 +149,9 @@ export function createDynamicOrRuntimeViewportError(route: string): Error {
173
+ `This prevents the page from being prerendered, leading to a slower user experience. Unlike metadata, viewport cannot be streamed behind \`<Suspense>\` because it affects the initial page load.\n\n` +
174
+ `Ways to fix this:\n` +
175
+ ` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
176
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\n` +
177
+ ` - [cache] For uncached data (\`fetch\`, database calls): cache the viewport with \`"use cache"\` in \`generateViewport()\` (does not apply to \`connection()\`)\n` +
178
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\n` +
179
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
180
+ - ` https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route`
181
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
182
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime`
183
+ )
184
+ }
185
+
186
+ @@ -183,11 +166,9 @@ export function createDynamicOrRuntimeMetadataError(route: string): Error {
187
+ `This route's metadata is blocked, but the rest of its content can be prerendered.\n\n` +
188
+ `Ways to fix this:\n` +
189
+ ` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
190
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\n` +
191
+ ` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (does not apply to \`connection()\`)\n` +
192
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#cache-the-metadata\n` +
193
+ - ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n` +
194
+ - ` https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic#mark-the-route-as-dynamic`
195
+ + ` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n\n` +
196
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime`
197
+ )
198
+ }
199
+
200
+ diff --git a/packages/next/src/server/app-render/sync-io-messages.ts b/packages/next/src/server/app-render/sync-io-messages.ts
201
+ index d65037c58d..b41ef8e909 100644
202
+ --- a/packages/next/src/server/app-render/sync-io-messages.ts
203
+ +++ b/packages/next/src/server/app-render/sync-io-messages.ts
204
+ @@ -18,18 +18,12 @@ const SYNC_IO_RUNTIME_DOCS: Record<SyncIOApiType, string> = {
205
+ crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto',
206
+ }
207
+
208
+ -function elapsedTimeBullet(type: SyncIOApiType, docsUrl: string): string {
209
+ +function elapsedTimeBullet(type: SyncIOApiType): string {
210
+ return type === 'time'
211
+ - ? `\n - [measure] If the value is for telemetry, use a timing API such as \`performance.now()\`\n ${docsUrl}#for-telemetry-use-a-timing-api`
212
+ + ? `\n - [measure] If the value is for telemetry, use a timing API such as \`performance.now()\``
213
+ : ''
214
+ }
215
+
216
+ -const CACHE_ANCHOR: Record<SyncIOApiType, string> = {
217
+ - random: '#cache-the-random-value',
218
+ - time: '#cache-the-timestamp',
219
+ - crypto: '#cache-the-generated-value',
220
+ -}
221
+ -
222
+ function createSyncIOErrorImpl(
223
+ route: string,
224
+ expression: string,
225
+ @@ -40,10 +34,11 @@ function createSyncIOErrorImpl(
226
+ `Route "${route}": Next.js encountered the unstable value ${expression} while prerendering.\n\n` +
227
+ `This value can change between renders, so it must be either prerendered or computed later.\n\n` +
228
+ `Ways to fix this:\n` +
229
+ - ` - [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` +
230
+ - ` - [cache] Prerender and cache the value with \`"use cache"\`\n ${docsUrl}${CACHE_ANCHOR[type]}\n` +
231
+ - ` - [client] Render the value on the client with \`"use client"\`\n ${docsUrl}#render-on-the-client` +
232
+ - elapsedTimeBullet(type, docsUrl)
233
+ + ` - [dynamic] Render at request time by adding a dynamic data access (e.g. \`await connection()\`) before this call\n` +
234
+ + ` - [cache] Prerender and cache the value with \`"use cache"\`\n` +
235
+ + ` - [client] Render the value on the client with \`"use client"\`` +
236
+ + elapsedTimeBullet(type) +
237
+ + `\n\nLearn more: ${docsUrl}`
238
+ )
239
+ }
240
+
241
+ @@ -78,8 +73,9 @@ export function createSyncIOClientError(
242
+ `Route "${route}": Next.js encountered the unstable value ${expression} in a Client Component.\n\n` +
243
+ `This value would be evaluated during the prerender, instead of recomputed on each visit.\n\n` +
244
+ `Ways to fix this:\n` +
245
+ - ` - [stream] Wrap the Client Component in \`<Suspense fallback={...}>\`\n ${docsUrl}#wrap-in-or-move-into-suspense\n` +
246
+ - ` - [defer] Move the read into a \`useEffect\` or event handler\n ${docsUrl}#move-into-effect-or-event-handler` +
247
+ - elapsedTimeBullet(type, docsUrl)
248
+ + ` - [stream] Wrap the Client Component in \`<Suspense fallback={...}>\`\n` +
249
+ + ` - [defer] Move the read into a \`useEffect\` or event handler` +
250
+ + elapsedTimeBullet(type) +
251
+ + `\n\nLearn more: ${docsUrl}`
252
+ )
253
+ }
254
+ diff --git a/packages/next/src/server/dynamic-rendering-utils.ts b/packages/next/src/server/dynamic-rendering-utils.ts
255
+ index 4158512e7f..91dcb37339 100644
256
+ --- a/packages/next/src/server/dynamic-rendering-utils.ts
257
+ +++ b/packages/next/src/server/dynamic-rendering-utils.ts
258
+ @@ -42,9 +42,8 @@ export class ClientHookDynamicError extends Error {
259
+ `This blocks prerendering because the value is only available at runtime.\n\n` +
260
+ `Ways to fix this:\n` +
261
+ ` - [stream] Wrap the component in \`<Suspense fallback={...}>\` so the hook value streams in after prerendering\n` +
262
+ - ` https://nextjs.org/docs/messages/blocking-prerender-client-hook#wrap-in-or-move-into-suspense\n` +
263
+ - ` - [block] Set \`export const instant = false\` to allow a blocking route\n` +
264
+ - ` https://nextjs.org/docs/messages/blocking-prerender-client-hook#allow-blocking-route`
265
+ + ` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
266
+ + `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`
267
+ )
268
+ }
269
+ }
270
+ diff --git a/packages/next/src/shared/lib/instant-messages.ts b/packages/next/src/shared/lib/instant-messages.ts
271
+ index b53b6a41ac..ce620c8738 100644
272
+ --- a/packages/next/src/shared/lib/instant-messages.ts
273
+ +++ b/packages/next/src/shared/lib/instant-messages.ts
274
+ @@ -11,9 +11,8 @@ export function createUnrenderedSegmentError(
275
+ `\n\n${label}:\n${missingFiles.map((p) => ` ${p}`).join('\n')}` +
276
+ `\n\nWays to fix this:` +
277
+ `\n - [render] Render the dropped segment` +
278
+ - `\n https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment` +
279
+ `\n - [ignore] Set \`export const instant = false\` to opt the dropped segment out of instant-navigation validation` +
280
+ - `\n https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment`
281
+ + `\n\nLearn more: https://nextjs.org/docs/messages/instant-unrendered-segment`
282
+ }
283
+ return new Error(message)
284
+ }
285
+ @@ -24,10 +23,8 @@ export function createLinkPrefetchPartialError(pathname: string): Error {
286
+ `This will lead to slower, more expensive prefetches.\n\n` +
287
+ `Ways to fix this:\n` +
288
+ ` - [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` +
289
+ - ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#opt-into-partial-prefetching\n` +
290
+ ` - [disable] Remove \`prefetch={true}\` from the <Link> to use the default prefetch\n` +
291
+ - ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#use-the-default-prefetch\n` +
292
+ - ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n` +
293
+ - ` https://nextjs.org/docs/messages/instant-link-prefetch-partial#disable-validation-on-this-route`
294
+ + ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n\n` +
295
+ + `Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial`
296
+ )
297
+ }
nextjs-95967-single-learn-more-links/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-95967-single-learn-more-links/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm build --filter=next' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-95967-single-learn-more-links/tests/test.patch ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ new file mode 100644
3
+ index 00000000..5b889dba
4
+ --- /dev/null
5
+ +++ b/packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts
6
+ @@ -0,0 +1,270 @@
7
+ +import {
8
+ + createDynamicBodyError,
9
+ + createDynamicBodyErrorInNavigation,
10
+ + createDynamicMetadataError,
11
+ + createDynamicOrRuntimeBodyError,
12
+ + createDynamicOrRuntimeMetadataError,
13
+ + createDynamicOrRuntimeViewportError,
14
+ + createDynamicViewportError,
15
+ + createLinkBodyErrorInNavigation,
16
+ + createLinkMetadataError,
17
+ + createLinkViewportError,
18
+ + createRuntimeBodyError,
19
+ + createRuntimeBodyErrorInNavigation,
20
+ + createRuntimeMetadataError,
21
+ + createRuntimeViewportError,
22
+ +} from '../../../server/app-render/blocking-route-messages'
23
+ +import {
24
+ + createSyncIOClientError,
25
+ + createSyncIOError,
26
+ + createSyncIORuntimeError,
27
+ + type SyncIOApiType,
28
+ +} from '../../../server/app-render/sync-io-messages'
29
+ +import { ClientHookDynamicError } from '../../../server/dynamic-rendering-utils'
30
+ +import {
31
+ + createLinkPrefetchPartialError,
32
+ + createUnrenderedSegmentError,
33
+ +} from '../../../shared/lib/instant-messages'
34
+ +import { getCards } from '../components/instant/instant-guidance-data'
35
+ +import { getBlockingRouteErrorDetails } from './errors'
36
+ +
37
+ +const ROUTE = '/insight-test'
38
+ +
39
+ +type MessageCase = {
40
+ + name: string
41
+ + error: () => Error
42
+ + docs: string | string[]
43
+ + labels: string[]
44
+ + context?: string[]
45
+ +}
46
+ +
47
+ +function expectSingleLearnMoreLink({
48
+ + error,
49
+ + docs,
50
+ + labels,
51
+ + context = [ROUTE],
52
+ +}: MessageCase): void {
53
+ + const message = error().message
54
+ + const urls = message.match(/https:\/\/[^\s]+/g) ?? []
55
+ + const allowedDocs = Array.isArray(docs) ? docs : [docs]
56
+ + const renderedLabels = Array.from(
57
+ + message.matchAll(/^\s*-\s*\[([a-z]+)\]/gm),
58
+ + (match) => match[1]
59
+ + )
60
+ + const learnMoreLines = Array.from(
61
+ + message.matchAll(/^Learn more: (https:\/\/[^\s]+)$/gm),
62
+ + (match) => match[1]
63
+ + )
64
+ +
65
+ + expect(renderedLabels).toEqual(labels)
66
+ + expect(learnMoreLines).toHaveLength(1)
67
+ + expect(allowedDocs).toContain(learnMoreLines[0])
68
+ + expect(urls).toEqual(learnMoreLines)
69
+ + expect(learnMoreLines[0]).not.toContain('#')
70
+ + expect(message).toMatch(/\n\nLearn more: https:\/\/[^\s]+\n?$/)
71
+ + for (const value of context) {
72
+ + expect(message).toContain(value)
73
+ + }
74
+ +}
75
+ +
76
+ +const blockingRouteCases: MessageCase[] = [
77
+ + {
78
+ + name: 'runtime body',
79
+ + error: () => createRuntimeBodyError(ROUTE),
80
+ + docs: 'https://nextjs.org/docs/messages/blocking-prerender-runtime',
81
+ + labels: ['stream', 'block'],
82
+ + },
83
+ + {
84
+ + name: 'dynamic body',
85
+ + error: () => createDynamicBodyError(ROUTE),
86
+ + docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic',
87
+ + labels: ['stream', 'cache', 'block'],
88
+ + },
89
+ + {
90
+ + name: 'runtime body during navigation',
91
+ + error: () => createRuntimeBodyErrorInNavigation(ROUTE),
92
+ + docs: 'https://nextjs.org/docs/messages/blocking-prerender-runtime',
93
+ + labels: ['stream', 'block'],
94
+ + },
95
+ + {
96
+ + name: 'URL body during navigation',
97
+ + error: () => createLinkBodyErrorInNavigation(ROUTE),
98
+ + docs: 'https://nextjs.org/docs/messages/instant-shell-url-data',
99
+ + labels: ['stream', 'block'],
100
+ + },
101
+ + {
102
+ + name: 'dynamic body during navigation',
103
+ + error: () => createDynamicBodyErrorInNavigation(ROUTE),
104
+ + docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic',
105
+ + labels: ['stream', 'cache', 'block'],
106
+ + },
107
+ + {
108
+ + name: 'combined dynamic and runtime body',
109
+ + error: () => createDynamicOrRuntimeBodyError(ROUTE),
110
+ + docs: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic',
111
+ + labels: ['stream', 'cache', 'block'],
112
+ + },
113
+ + {
114
+ + name: 'URL metadata',
115
+ + error: () => createLinkMetadataError(ROUTE),
116
+ + docs:
117
+ + 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
118
+ + labels: ['static', 'dynamic'],
119
+ + },
120
+ + {
121
+ + name: 'runtime metadata',
122
+ + error: () => createRuntimeMetadataError(ROUTE),
123
+ + docs:
124
+ + 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
125
+ + labels: ['static', 'dynamic'],
126
+ + },
127
+ + {
128
+ + name: 'dynamic metadata',
129
+ + error: () => createDynamicMetadataError(ROUTE),
130
+ + docs:
131
+ + 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic',
132
+ + labels: ['cache', 'dynamic'],
133
+ + },
134
+ + {
135
+ + name: 'combined dynamic and runtime metadata',
136
+ + error: () => createDynamicOrRuntimeMetadataError(ROUTE),
137
+ + docs: [
138
+ + 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
139
+ + 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic',
140
+ + ],
141
+ + labels: ['static', 'cache', 'dynamic'],
142
+ + },
143
+ + {
144
+ + name: 'URL viewport',
145
+ + error: () => createLinkViewportError(ROUTE),
146
+ + docs:
147
+ + 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
148
+ + labels: ['static', 'block'],
149
+ + },
150
+ + {
151
+ + name: 'runtime viewport',
152
+ + error: () => createRuntimeViewportError(ROUTE),
153
+ + docs:
154
+ + 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
155
+ + labels: ['static', 'block'],
156
+ + },
157
+ + {
158
+ + name: 'dynamic viewport',
159
+ + error: () => createDynamicViewportError(ROUTE),
160
+ + docs:
161
+ + 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic',
162
+ + labels: ['cache', 'block'],
163
+ + },
164
+ + {
165
+ + name: 'combined dynamic and runtime viewport',
166
+ + error: () => createDynamicOrRuntimeViewportError(ROUTE),
167
+ + docs: [
168
+ + 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
169
+ + 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic',
170
+ + ],
171
+ + labels: ['static', 'cache', 'block'],
172
+ + },
173
+ +]
174
+ +
175
+ +const syncIoTypes: SyncIOApiType[] = ['time', 'random', 'crypto']
176
+ +const syncIoDocs: Record<SyncIOApiType, string> = {
177
+ + time: 'https://nextjs.org/docs/messages/blocking-prerender-current-time',
178
+ + random: 'https://nextjs.org/docs/messages/blocking-prerender-random',
179
+ + crypto: 'https://nextjs.org/docs/messages/blocking-prerender-crypto',
180
+ +}
181
+ +
182
+ +const syncIoCases: MessageCase[] = syncIoTypes.flatMap((type) => {
183
+ + const measure = type === 'time' ? ['measure'] : []
184
+ + return [
185
+ + {
186
+ + name: `${type} prerender`,
187
+ + error: () => createSyncIOError(ROUTE, `${type}()`, type),
188
+ + docs: syncIoDocs[type],
189
+ + labels: ['dynamic', 'cache', 'client', ...measure],
190
+ + context: [ROUTE, `${type}()`],
191
+ + },
192
+ + {
193
+ + name: `${type} runtime prerender`,
194
+ + error: () => createSyncIORuntimeError(ROUTE, `${type}()`, type),
195
+ + docs: syncIoDocs[type],
196
+ + labels: ['dynamic', 'cache', 'client', ...measure],
197
+ + context: [ROUTE, `${type}()`],
198
+ + },
199
+ + {
200
+ + name: `${type} client component`,
201
+ + error: () => createSyncIOClientError(ROUTE, `${type}()`, type),
202
+ + docs: `${syncIoDocs[type]}-client`,
203
+ + labels: ['stream', 'defer', ...measure],
204
+ + context: [ROUTE, `${type}()`],
205
+ + },
206
+ + ]
207
+ +})
208
+ +
209
+ +const instantCases: MessageCase[] = [
210
+ + {
211
+ + name: 'client hook',
212
+ + error: () => new ClientHookDynamicError(ROUTE, 'useSearchParams()'),
213
+ + docs: 'https://nextjs.org/docs/messages/blocking-prerender-client-hook',
214
+ + labels: ['stream', 'block'],
215
+ + context: [ROUTE, 'useSearchParams()'],
216
+ + },
217
+ + {
218
+ + name: 'unrendered segment',
219
+ + error: () =>
220
+ + createUnrenderedSegmentError(ROUTE, [
221
+ + 'app/@modal/default.tsx',
222
+ + 'app/@sidebar/default.tsx',
223
+ + ]),
224
+ + docs: 'https://nextjs.org/docs/messages/instant-unrendered-segment',
225
+ + labels: ['render', 'ignore'],
226
+ + context: [
227
+ + ROUTE,
228
+ + 'app/@modal/default.tsx',
229
+ + 'app/@sidebar/default.tsx',
230
+ + ],
231
+ + },
232
+ + {
233
+ + name: 'partial link prefetch',
234
+ + error: () => createLinkPrefetchPartialError(ROUTE),
235
+ + docs: 'https://nextjs.org/docs/messages/instant-link-prefetch-partial',
236
+ + labels: ['upgrade', 'disable', 'ignore'],
237
+ + },
238
+ +]
239
+ +
240
+ +describe('insight console guidance', () => {
241
+ + it.each([...blockingRouteCases, ...syncIoCases, ...instantCases])(
242
+ + '$name has one anchor-less Learn more link after its labeled fixes',
243
+ + expectSingleLearnMoreLink
244
+ + )
245
+ +
246
+ + it.each(blockingRouteCases)(
247
+ + '$name remains recognizable by the development overlay',
248
+ + ({ error }) => {
249
+ + expect(getBlockingRouteErrorDetails(error())).not.toBeNull()
250
+ + }
251
+ + )
252
+ +
253
+ + it('preserves the unrendered-segment input list', () => {
254
+ + const message = createUnrenderedSegmentError(ROUTE, [
255
+ + 'app/@modal/default.tsx',
256
+ + 'app/@sidebar/default.tsx',
257
+ + ]).message
258
+ + expect(message).toContain('app/@modal/default.tsx')
259
+ + expect(message).toContain('app/@sidebar/default.tsx')
260
+ + })
261
+ +
262
+ + it('keeps per-fix links on development-overlay cards', () => {
263
+ + for (const [kind, variant] of [
264
+ + ['blocking-route', 'dynamic'],
265
+ + ['metadata', 'runtime'],
266
+ + ['viewport', 'dynamic'],
267
+ + ['link-prefetch-partial', 'runtime'],
268
+ + ] as const) {
269
+ + const cards = getCards(kind, variant)
270
+ + expect(cards.length).toBeGreaterThan(1)
271
+ + for (const card of cards) {
272
+ + expect(card.link).toMatch(/^https:\/\/nextjs\.org\/docs\/messages\/[^#]+#.+/)
273
+ + }
274
+ + }
275
+ + })
276
+ +})
nextjs-95967-single-learn-more-links/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ 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
59
+ git -C /app clean -fd -- 'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ 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
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm test-webpack '"'"'packages/next/src/next-devtools/dev-overlay/container/insight-console-messages.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ 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
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-96022-dev-use-cache-invalidation/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && 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' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-96022-dev-use-cache-invalidation/solution/gold.patch ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/errors.json b/packages/next/errors.json
2
+ index 94dd1aaade..7a88dde307 100644
3
+ --- a/packages/next/errors.json
4
+ +++ b/packages/next/errors.json
5
+ @@ -1445,5 +1445,6 @@
6
+ "1444": "Invalid target hostname \"%s\" for proxy request, expected \"%s\"",
7
+ "1445": "Invariant: Missing `__NEXT_PRIVATE_ORIGIN` environment variable.",
8
+ "1446": "Missing initURL",
9
+ - "1447": "Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server."
10
+ + "1447": "Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server.",
11
+ + "1448": "Error in the \"%s\" app-route HMR subscription"
12
+ }
13
+ diff --git a/packages/next/src/build/templates/app-route.ts b/packages/next/src/build/templates/app-route.ts
14
+ index e6e9d9b8a9..100ed82897 100644
15
+ --- a/packages/next/src/build/templates/app-route.ts
16
+ +++ b/packages/next/src/build/templates/app-route.ts
17
+ @@ -253,6 +253,7 @@ export async function handler(
18
+ validationLevel: nextConfig.experimental.instantInsights.validationLevel,
19
+ supportsDynamicResponse,
20
+ incrementalCache,
21
+ + hmrRefreshHash: getRequestMeta(req, 'hmrRefreshHash'),
22
+ cacheLifeProfiles: nextConfig.cacheLife,
23
+ staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,
24
+ waitUntil: ctx.waitUntil,
25
+ diff --git a/packages/next/src/client/components/app-router-headers.ts b/packages/next/src/client/components/app-router-headers.ts
26
+ index 30a8373be0..2d63005ae7 100644
27
+ --- a/packages/next/src/client/components/app-router-headers.ts
28
+ +++ b/packages/next/src/client/components/app-router-headers.ts
29
+ @@ -12,7 +12,6 @@ export const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const
30
+ export const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER =
31
+ 'next-router-segment-prefetch' as const
32
+ export const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh' as const
33
+ -export const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const
34
+ export const NEXT_URL = 'next-url' as const
35
+ export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
36
+
37
+ diff --git a/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx b/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx
38
+ index 35af5e073f..b3fbc56c4e 100644
39
+ --- a/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx
40
+ +++ b/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx
41
+ @@ -31,7 +31,6 @@ import type { McpPageMetadataResponse } from '../../../../shared/lib/mcp-page-me
42
+ import { useUntrackedPathname } from '../../../components/navigation-untracked'
43
+ import reportHmrLatency from '../../report-hmr-latency'
44
+ import { TurbopackHmr } from '../turbopack-hot-reloader-common'
45
+ -import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../../components/app-router-headers'
46
+ import {
47
+ publicAppRouterInstance,
48
+ type GlobalErrorState,
49
+ @@ -412,14 +411,9 @@ export function processMessage(
50
+ JSON.stringify({
51
+ event: 'server-component-reload-page',
52
+ clientId: __nextDevClientId,
53
+ - hash: message.hash,
54
+ })
55
+ )
56
+
57
+ - // Store the latest hash in a session cookie so that it's sent back to the
58
+ - // server with any subsequent requests.
59
+ - document.cookie = `${NEXT_HMR_REFRESH_HASH_COOKIE}=${message.hash};path=/`
60
+ -
61
+ if (
62
+ RuntimeErrorHandler.hadRuntimeError ||
63
+ document.documentElement.id === '__next_error__'
64
+ diff --git a/packages/next/src/server/app-render/app-render.tsx b/packages/next/src/server/app-render/app-render.tsx
65
+ index 40c63d577a..40794f3be6 100644
66
+ --- a/packages/next/src/server/app-render/app-render.tsx
67
+ +++ b/packages/next/src/server/app-render/app-render.tsx
68
+ @@ -2856,6 +2856,7 @@ async function renderToHTMLOrFlightImpl(
69
+
70
+ const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment)
71
+ const fallbackParams = getRequestMeta(req, 'fallbackParams') || null
72
+ + const hmrRefreshHash = getRequestMeta(req, 'hmrRefreshHash')
73
+
74
+ const createRequestStore = createRequestStoreForRender.bind(
75
+ null,
76
+ @@ -2869,7 +2870,8 @@ async function renderToHTMLOrFlightImpl(
77
+ isHmrRefresh,
78
+ serverComponentsHmrCache,
79
+ renderResumeDataCache,
80
+ - fallbackParams
81
+ + fallbackParams,
82
+ + hmrRefreshHash
83
+ )
84
+ const requestStore = createRequestStore()
85
+
86
+ diff --git a/packages/next/src/server/app-render/work-unit-async-storage.external.ts b/packages/next/src/server/app-render/work-unit-async-storage.external.ts
87
+ index 639426d5cb..f1cd69f1f6 100644
88
+ --- a/packages/next/src/server/app-render/work-unit-async-storage.external.ts
89
+ +++ b/packages/next/src/server/app-render/work-unit-async-storage.external.ts
90
+ @@ -18,7 +18,6 @@ import type {
91
+ import type { Params } from '../request/params'
92
+ import type { ImplicitTags } from '../lib/implicit-tags'
93
+ import type { WorkStore } from './work-async-storage.external'
94
+ -import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../client/components/app-router-headers'
95
+ import { InvariantError } from '../../shared/lib/invariant-error'
96
+ import type { StagedRenderingController } from './staged-rendering'
97
+ import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
98
+ @@ -61,6 +60,7 @@ export interface RequestStore extends CommonWorkUnitStore {
99
+ readonly draftMode: DraftModeProvider
100
+ readonly isHmrRefresh?: boolean
101
+ readonly serverComponentsHmrCache?: ServerComponentsHmrCache
102
+ + readonly hmrRefreshHash?: string
103
+
104
+ readonly rootParams: Params
105
+
106
+ @@ -438,9 +438,8 @@ export function getHmrRefreshHash(
107
+ case 'private-cache':
108
+ case 'prerender':
109
+ case 'prerender-runtime':
110
+ - return workUnitStore.hmrRefreshHash
111
+ case 'request':
112
+ - return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
113
+ + return workUnitStore.hmrRefreshHash
114
+ case 'prerender-client':
115
+ case 'validation-client':
116
+ case 'prerender-ppr':
117
+ diff --git a/packages/next/src/server/async-storage/request-store.ts b/packages/next/src/server/async-storage/request-store.ts
118
+ index 9a9d2dde4d..c8ab6d82ae 100644
119
+ --- a/packages/next/src/server/async-storage/request-store.ts
120
+ +++ b/packages/next/src/server/async-storage/request-store.ts
121
+ @@ -126,6 +126,12 @@ export type RequestStoreInputs = {
122
+ previewProps: WrapperRenderOpts['previewProps']
123
+ isHmrRefresh: boolean | undefined
124
+ serverComponentsHmrCache: ServerComponentsHmrCache | undefined
125
+ + /**
126
+ + * The hash of the most recent server component change (dev only). Included in
127
+ + * `"use cache"` cache keys so that cached entries are revalidated after an
128
+ + * edit, for every client, regardless of whether it runs the HMR client.
129
+ + */
130
+ + hmrRefreshHash: string | undefined
131
+ fallbackParams: OpaqueFallbackRouteParams | null | undefined
132
+ }
133
+
134
+ @@ -173,7 +179,8 @@ export function createRequestStoreForRender(
135
+ isHmrRefresh: RequestContext['isHmrRefresh'],
136
+ serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
137
+ resumeDataCache: ResumeDataCache | null,
138
+ - fallbackParams: OpaqueFallbackRouteParams | null
139
+ + fallbackParams: OpaqueFallbackRouteParams | null,
140
+ + hmrRefreshHash: string | undefined
141
+ ): RequestStore {
142
+ return createRequestStore({
143
+ // Pages start in render phase by default
144
+ @@ -193,6 +200,7 @@ export function createRequestStoreForRender(
145
+ previewProps,
146
+ isHmrRefresh,
147
+ serverComponentsHmrCache,
148
+ + hmrRefreshHash,
149
+ fallbackParams,
150
+ })
151
+ }
152
+ @@ -202,7 +210,8 @@ export function createRequestStoreForAPI(
153
+ url: RequestContext['url'],
154
+ implicitTags: RequestContext['implicitTags'],
155
+ onUpdateCookies: RenderOpts['onUpdateCookies'],
156
+ - previewProps: WrapperRenderOpts['previewProps']
157
+ + previewProps: WrapperRenderOpts['previewProps'],
158
+ + hmrRefreshHash: string | undefined
159
+ ): RequestStore {
160
+ return createRequestStore({
161
+ // API routes start in action phase by default
162
+ @@ -216,6 +225,7 @@ export function createRequestStoreForAPI(
163
+ previewProps,
164
+ isHmrRefresh: false,
165
+ serverComponentsHmrCache: undefined,
166
+ + hmrRefreshHash,
167
+ fallbackParams: null,
168
+ })
169
+ }
170
+ @@ -239,6 +249,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
171
+ previewProps,
172
+ isHmrRefresh,
173
+ serverComponentsHmrCache,
174
+ + hmrRefreshHash,
175
+ fallbackParams,
176
+ } = inputs
177
+
178
+ @@ -321,6 +332,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
179
+ serverComponentsHmrCache:
180
+ serverComponentsHmrCache ||
181
+ (globalThis as any).__serverComponentsHmrCache,
182
+ + hmrRefreshHash,
183
+ fallbackParams,
184
+ }
185
+ }
186
+ diff --git a/packages/next/src/server/async-storage/work-store.ts b/packages/next/src/server/async-storage/work-store.ts
187
+ index 6b8f4042b5..c765f13a23 100644
188
+ --- a/packages/next/src/server/async-storage/work-store.ts
189
+ +++ b/packages/next/src/server/async-storage/work-store.ts
190
+ @@ -28,6 +28,12 @@ export type WorkStoreContext = {
191
+ cacheLifeProfiles: ResolvedCacheLifeProfiles
192
+ staticPageGenerationTimeout: number
193
+ incrementalCache?: IncrementalCache
194
+ + /**
195
+ + * The hash of the most recent server component change (dev only). Included
196
+ + * in `"use cache"` cache keys so that cached entries are revalidated after
197
+ + * an edit, for every client, regardless of whether it runs the HMR client.
198
+ + */
199
+ + hmrRefreshHash?: string
200
+ isOnDemandRevalidate?: boolean
201
+ cacheComponents: boolean
202
+ validationLevel: ValidationLevel
203
+ diff --git a/packages/next/src/server/base-server.ts b/packages/next/src/server/base-server.ts
204
+ index d201b7151a..9ac5cbceb8 100644
205
+ --- a/packages/next/src/server/base-server.ts
206
+ +++ b/packages/next/src/server/base-server.ts
207
+ @@ -422,6 +422,15 @@ export default abstract class Server<
208
+ : undefined
209
+ }
210
+
211
+ + /**
212
+ + * The hash of the most recent server component change (dev only), used to
213
+ + * revalidate `"use cache"` entries after an edit. Overridden by the dev
214
+ + * server; returns `undefined` otherwise.
215
+ + */
216
+ + protected getServerComponentsHmrRefreshHash(): string | undefined {
217
+ + return undefined
218
+ + }
219
+ +
220
+ protected abstract loadEnvConfig(params: {
221
+ dev: boolean
222
+ forceReload: boolean
223
+ @@ -1547,6 +1556,20 @@ export default abstract class Server<
224
+ )
225
+ }
226
+
227
+ + // Attach the server components HMR refresh hash here, alongside the HMR
228
+ + // cache, so it reaches every render that passes through this request
229
+ + // handling, including internal renders (e.g. dev validation/warmup) that
230
+ + // don't re-enter the top-level request handler. It's included in `"use
231
+ + // cache"` keys so cached entries revalidate after an edit, for every
232
+ + // client.
233
+ + if (!getRequestMeta(req, 'hmrRefreshHash')) {
234
+ + addRequestMeta(
235
+ + req,
236
+ + 'hmrRefreshHash',
237
+ + this.getServerComponentsHmrRefreshHash()
238
+ + )
239
+ + }
240
+ +
241
+ // when invokePath is specified we can short short circuit resolving
242
+ // we only honor this header if we are inside of a render worker to
243
+ // prevent external users coercing the routing path
244
+ diff --git a/packages/next/src/server/dev/hot-reloader-turbopack.ts b/packages/next/src/server/dev/hot-reloader-turbopack.ts
245
+ index 672abba0b6..3372f40d92 100644
246
+ --- a/packages/next/src/server/dev/hot-reloader-turbopack.ts
247
+ +++ b/packages/next/src/server/dev/hot-reloader-turbopack.ts
248
+ @@ -696,6 +696,14 @@ export async function createHotReloaderTurbopack(
249
+ let serverHmrSubscriptions: ServerHmrSubscriptions | undefined
250
+
251
+ let hmrEventHappened = false
252
+ + // A counter identifying the current version of the compiled output, included
253
+ + // by `"use cache"` in dev cache keys so that cached entries revalidate after
254
+ + // an edit. It advances once per HMR change event (for App Router pages that
255
+ + // is an RSC change, which is what a cached render depends on), independent of
256
+ + // how many clients are connected. It deliberately does not advance on `BUILT`
257
+ + // messages: those are sent per connected client on every compilation, so
258
+ + // advancing there would both churn the hash without an edit and fail to
259
+ + // advance it at all when no client is connected.
260
+ let hmrHash = 0
261
+
262
+ const clientsWithoutHtmlRequestId = new Set<ws>()
263
+ @@ -1495,6 +1503,16 @@ export async function createHotReloaderTurbopack(
264
+ }
265
+ },
266
+
267
+ + getServerComponentsHmrRefreshHash() {
268
+ + // The current server-components generation. Only the change subscription
269
+ + // (an actual recompile) advances `hmrHash`; reloads and config
270
+ + // invalidations don't, so the value stays stable across requests until a
271
+ + // real edit. Returned unconditionally (`"0"` before the first edit) so
272
+ + // `"use cache"` keys are present and consistent for every request,
273
+ + // mirroring webpack's always-present `stats.hash`.
274
+ + return String(hmrHash)
275
+ + },
276
+ +
277
+ sendToLegacyClients(action) {
278
+ const payload = JSON.stringify(action)
279
+
280
+ @@ -1641,7 +1659,6 @@ export async function createHotReloaderTurbopack(
281
+ await clearAllModuleContexts()
282
+ this.send({
283
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
284
+ - hash: String(++hmrHash),
285
+ })
286
+ }
287
+ },
288
+ @@ -1922,7 +1939,10 @@ export async function createHotReloaderTurbopack(
289
+
290
+ sendToClient(client, {
291
+ type: HMR_MESSAGE_SENT_TO_BROWSER.BUILT,
292
+ - hash: String(++hmrHash),
293
+ + // Report the current version without advancing it: a completed
294
+ + // compilation is not itself an edit, and this hash is not
295
+ + // consumed by the Turbopack client.
296
+ + hash: String(hmrHash),
297
+ errors: [...clientErrors.values()],
298
+ warnings: [],
299
+ })
300
+ @@ -1981,7 +2001,6 @@ export async function createHotReloaderTurbopack(
301
+ // Tell browsers to refetch RSC (soft refresh, not full page reload)
302
+ hotReloader.send({
303
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
304
+ - hash: String(++hmrHash),
305
+ })
306
+ },
307
+ })
308
+ diff --git a/packages/next/src/server/dev/hot-reloader-types.ts b/packages/next/src/server/dev/hot-reloader-types.ts
309
+ index 04334c6f49..2e2855605d 100644
310
+ --- a/packages/next/src/server/dev/hot-reloader-types.ts
311
+ +++ b/packages/next/src/server/dev/hot-reloader-types.ts
312
+ @@ -117,7 +117,6 @@ export interface ReloadPageMessage {
313
+
314
+ export interface ServerComponentChangesMessage {
315
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES
316
+ - hash: string
317
+ }
318
+
319
+ /**
320
+ @@ -259,6 +258,13 @@ export interface NextJsHotReloaderInterface {
321
+ * and App Router clients that don't have Cache Components enabled.
322
+ */
323
+ sendToLegacyClients(action: HmrMessageSentToBrowser): void
324
+ + /**
325
+ + * The hash of the most recent server component change, or `undefined` if no
326
+ + * server component change has occurred yet. In dev, this is included in `"use
327
+ + * cache"` cache keys so that cached entries are revalidated after an edit,
328
+ + * for every client, regardless of whether it runs the HMR client.
329
+ + */
330
+ + getServerComponentsHmrRefreshHash(): string | undefined
331
+ setCacheStatus(status: ServerCacheStatus, htmlRequestId: string): void
332
+ setReactDebugChannel(
333
+ debugChannel: ReactDebugChannelForBrowser,
334
+ diff --git a/packages/next/src/server/dev/hot-reloader-webpack.ts b/packages/next/src/server/dev/hot-reloader-webpack.ts
335
+ index 063ebe195a..3f687776c7 100644
336
+ --- a/packages/next/src/server/dev/hot-reloader-webpack.ts
337
+ +++ b/packages/next/src/server/dev/hot-reloader-webpack.ts
338
+ @@ -241,6 +241,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
339
+ private serverError: Error | null = null
340
+ private hmrServerError: Error | null = null
341
+ private serverPrevDocumentHash: string | null
342
+ + private serverComponentsHmrRefreshHash: string | undefined
343
+ private serverChunkNames?: Set<string>
344
+ private prevChunkNames?: Set<any>
345
+ private onDemandEntries?: ReturnType<typeof onDemandEntryHandler>
346
+ @@ -431,14 +432,18 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
347
+ }
348
+
349
+ protected async refreshServerComponents(hash: string): Promise<void> {
350
+ + this.serverComponentsHmrRefreshHash = hash
351
+ this.send({
352
+ type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
353
+ - hash,
354
+ // TODO: granular reloading of changes
355
+ // entrypoints: serverComponentChanges,
356
+ })
357
+ }
358
+
359
+ + public getServerComponentsHmrRefreshHash(): string | undefined {
360
+ + return this.serverComponentsHmrRefreshHash
361
+ + }
362
+ +
363
+ public onHMR(
364
+ req: IncomingMessage,
365
+ _socket: Duplex,
366
+ diff --git a/packages/next/src/server/dev/next-dev-server.ts b/packages/next/src/server/dev/next-dev-server.ts
367
+ index 5f40da7ef9..54fa3aaf96 100644
368
+ --- a/packages/next/src/server/dev/next-dev-server.ts
369
+ +++ b/packages/next/src/server/dev/next-dev-server.ts
370
+ @@ -231,6 +231,10 @@ export default class DevServer extends Server {
371
+ return this.serverComponentsHmrCache
372
+ }
373
+
374
+ + protected override getServerComponentsHmrRefreshHash(): string | undefined {
375
+ + return this.bundlerService.getServerComponentsHmrRefreshHash()
376
+ + }
377
+ +
378
+ protected getRouteMatchers(): RouteMatcherManager {
379
+ const { pagesDir, appDir } = findPagesDir(this.dir)
380
+
381
+ diff --git a/packages/next/src/server/dev/turbopack-utils.ts b/packages/next/src/server/dev/turbopack-utils.ts
382
+ index 25155df83f..7aa2900da5 100644
383
+ --- a/packages/next/src/server/dev/turbopack-utils.ts
384
+ +++ b/packages/next/src/server/dev/turbopack-utils.ts
385
+ @@ -408,6 +408,34 @@ export async function handleRouteType({
386
+ const writtenEndpoint = await route.endpoint.writeToDisk()
387
+ hooks?.handleWrittenEndpoint(key, writtenEndpoint, false)
388
+
389
+ + if (dev) {
390
+ + // Advance the hot-reloader's HMR refresh hash whenever this route
391
+ + // handler is recompiled, so its `"use cache"` entries are invalidated
392
+ + // after an edit. Subscribing runs `subscribeToClientChanges`, which
393
+ + // bumps the `hmrHash` counter on each change; that counter is returned
394
+ + // by `getServerComponentsHmrRefreshHash` and folded into cache keys by
395
+ + // `getHmrRefreshHash`. Unlike app pages there is no RSC for a connected
396
+ + // browser to refetch, so `createMessage` returns nothing; the
397
+ + // subscription exists only to advance the hash.
398
+ + hooks?.subscribeToChanges(
399
+ + key,
400
+ + /** includeIssues= */ true,
401
+ + route.endpoint,
402
+ + () => undefined,
403
+ + (error) => {
404
+ + // This subscription only advances the refresh hash, so there is
405
+ + // nothing to send the browser when it fails. `subscribeToChanges`
406
+ + // drops the subscription on error and re-creates it the next time
407
+ + // this route is ensured, so just log it.
408
+ + console.error(
409
+ + new Error(`Error in the "${page}" app-route HMR subscription`, {
410
+ + cause: error,
411
+ + })
412
+ + )
413
+ + }
414
+ + )
415
+ + }
416
+ +
417
+ const type = writtenEndpoint.type
418
+
419
+ manifestLoader.loadAppPathsManifest(page)
420
+ diff --git a/packages/next/src/server/dev/use-cache-probe-worker.ts b/packages/next/src/server/dev/use-cache-probe-worker.ts
421
+ index c77c7c8901..a29a26bcb4 100644
422
+ --- a/packages/next/src/server/dev/use-cache-probe-worker.ts
423
+ +++ b/packages/next/src/server/dev/use-cache-probe-worker.ts
424
+ @@ -167,6 +167,7 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> {
425
+ previewProps: undefined,
426
+ isHmrRefresh: msg.request.isHmrRefresh,
427
+ serverComponentsHmrCache: undefined,
428
+ + hmrRefreshHash: msg.request.hmrRefreshHash,
429
+ fallbackParams: null,
430
+ })
431
+
432
+ diff --git a/packages/next/src/server/lib/dev-bundler-service.ts b/packages/next/src/server/lib/dev-bundler-service.ts
433
+ index c1e963d0f6..f284e79b12 100644
434
+ --- a/packages/next/src/server/lib/dev-bundler-service.ts
435
+ +++ b/packages/next/src/server/lib/dev-bundler-service.ts
436
+ @@ -64,6 +64,10 @@ export class DevBundlerService {
437
+ return await this.bundler.hotReloader.ensurePage(definition)
438
+ }
439
+
440
+ + public getServerComponentsHmrRefreshHash(): string | undefined {
441
+ + return this.bundler.hotReloader.getServerComponentsHmrRefreshHash()
442
+ + }
443
+ +
444
+ public logErrorWithOriginalStack =
445
+ this.bundler.logErrorWithOriginalStack.bind(this.bundler)
446
+
447
+ diff --git a/packages/next/src/server/request-meta.ts b/packages/next/src/server/request-meta.ts
448
+ index db02b9abdd..0521765ea2 100644
449
+ --- a/packages/next/src/server/request-meta.ts
450
+ +++ b/packages/next/src/server/request-meta.ts
451
+ @@ -114,6 +114,14 @@ export interface RequestMeta {
452
+ */
453
+ serverComponentsHmrCache?: ServerComponentsHmrCache
454
+
455
+ + /**
456
+ + * The hash of the most recent server component change (dev only), set by the
457
+ + * router-server from the hot-reloader. Included in `"use cache"` cache keys
458
+ + * so that cached entries are revalidated after an edit, for every client,
459
+ + * regardless of whether it runs the HMR client.
460
+ + */
461
+ + hmrRefreshHash?: string
462
+ +
463
+ /**
464
+ * Equals the segment path that was used for the prefetch RSC request.
465
+ */
466
+ diff --git a/packages/next/src/server/route-modules/app-route/module.ts b/packages/next/src/server/route-modules/app-route/module.ts
467
+ index d87306003e..5bcc998eac 100644
468
+ --- a/packages/next/src/server/route-modules/app-route/module.ts
469
+ +++ b/packages/next/src/server/route-modules/app-route/module.ts
470
+ @@ -805,7 +805,8 @@ export class AppRouteRouteModule extends RouteModule<
471
+ req.nextUrl,
472
+ implicitTags,
473
+ undefined,
474
+ - context.previewProps
475
+ + context.previewProps,
476
+ + context.renderOpts.hmrRefreshHash
477
+ )
478
+
479
+ const workStore = createWorkStore(staticGenerationContext)
480
+ 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
481
+ index 272e71d1a7..1f3b3a5f30 100644
482
+ --- a/packages/next/src/server/use-cache/use-cache-probe-globals.ts
483
+ +++ b/packages/next/src/server/use-cache/use-cache-probe-globals.ts
484
+ @@ -24,6 +24,7 @@ export type UseCacheProbeRequestSnapshot = {
485
+ rootParams: Params
486
+ isDraftMode: boolean
487
+ isHmrRefresh: boolean
488
+ + hmrRefreshHash: string | undefined
489
+ }
490
+
491
+ /**
492
+ 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
493
+ index f8733b7e8f..dbed303bda 100644
494
+ --- a/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts
495
+ +++ b/packages/next/src/server/use-cache/use-cache-probe-scheduler.ts
496
+ @@ -115,6 +115,7 @@ export function setupProbeScheduler(
497
+ rootParams: outerRequestStore.rootParams ?? {},
498
+ isDraftMode: workStore.isDraftMode ?? false,
499
+ isHmrRefresh: outerRequestStore.isHmrRefresh ?? false,
500
+ + hmrRefreshHash: outerRequestStore.hmrRefreshHash,
501
+ },
502
+ timeoutMs: probeInternalTimeoutMs,
503
+ }).then(
504
+ diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts
505
+ index 2bebc96297..f549de8b8d 100644
506
+ --- a/packages/next/src/server/use-cache/use-cache-wrapper.ts
507
+ +++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts
508
+ @@ -74,10 +74,7 @@ import {
509
+ } from './handlers'
510
+ import type { CacheReadWriteHandler } from './tiered-cache-handler'
511
+ import { cloneCacheEntry } from './clone-cache-entry'
512
+ -import {
513
+ - NEXT_HMR_REFRESH_HASH_COOKIE,
514
+ - NEXT_INSTANT_TEST_COOKIE,
515
+ -} from '../../client/components/app-router-headers'
516
+ +import { NEXT_INSTANT_TEST_COOKIE } from '../../client/components/app-router-headers'
517
+ import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'
518
+ import type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'
519
+ import {
520
+ @@ -366,10 +363,8 @@ function computeRootParamsCacheKeySuffix(
521
+ // Next-internal cookies that must not vary the private cache key, since they're
522
+ // not part of the application's own cookie state. The instant-navigation cookie
523
+ // toggles while a navigation lock is held, so including it would force spurious
524
+ -// misses. The HMR refresh hash is already part of the cache key (see
525
+ -// `cacheKeyParts`), so including its cookie too would just be redundant.
526
+ +// misses.
527
+ const COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY = new Set<string>([
528
+ - NEXT_HMR_REFRESH_HASH_COOKIE,
529
+ NEXT_INSTANT_TEST_COOKIE,
530
+ ])
531
+
532
+ diff --git a/packages/next/src/server/web/adapter.ts b/packages/next/src/server/web/adapter.ts
533
+ index 38c960b804..c9c2a43ac3 100644
534
+ --- a/packages/next/src/server/web/adapter.ts
535
+ +++ b/packages/next/src/server/web/adapter.ts
536
+ @@ -313,7 +313,10 @@ export async function adapter(
537
+ request.nextUrl,
538
+ implicitTags,
539
+ onUpdateCookies,
540
+ - previewProps
541
+ + previewProps,
542
+ + // Edge route handlers can't use `"use cache"`, so there's no HMR
543
+ + // refresh hash to thread through here.
544
+ + undefined
545
+ )
546
+
547
+ const workStore = createWorkStore({
nextjs-96022-dev-use-cache-invalidation/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-96022-dev-use-cache-invalidation/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && 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' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-96022-dev-use-cache-invalidation/tests/test.patch ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ index da4e0a22..ca835118 100644
3
+ --- a/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts
4
+ +++ b/test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts
5
+ @@ -108,15 +108,11 @@ describe('use-cache-dev', () => {
6
+ )
7
+ })
8
+
9
+ - // These two currently fail in both Turbopack and Webpack. Dev "use cache"
10
+ - // invalidation relies on the __next_hmr_refresh_hash__ cookie that the
11
+ - // browser HMR client sets after an edit; a client that fetches directly
12
+ - // (curl, a plain fetch, a second device) never sends that cookie, so the
13
+ - // "use cache" key does not change across the edit and the stale entry is
14
+ - // reused. Change these to `it` once editing a file invalidates cached data
15
+ - // for requests that do not carry the cookie, covering both route handlers
16
+ - // and pages.
17
+ - it.failing(
18
+ + // Regression coverage for requesters that don't run the browser HMR client.
19
+ + // A direct requester never receives browser-authored refresh state, but it
20
+ + // must still observe a new cache generation after the server recompiles an
21
+ + // edited page or route handler.
22
+ + it(
23
+ 'should update cached data used by a route handler after editing a file',
24
+ async () => {
25
+ const initialData = await next
26
+ @@ -160,10 +156,20 @@ describe('use-cache-dev', () => {
27
+ // random value due to a cache miss.
28
+ expect(newData.text).toBe('bar')
29
+ expect(newData.mathRandom).not.toBe(initialData.mathRandom)
30
+ +
31
+ + // Once the edited module has compiled, ordinary warm requests should
32
+ + // keep reusing its new cache entry rather than advancing the cache key
33
+ + // for development bookkeeping.
34
+ + const warmData = await next
35
+ + .fetch('/api/cached')
36
+ + .then((res) => res.json())
37
+ +
38
+ + expect(warmData.text).toBe('bar')
39
+ + expect(warmData.mathRandom).toBe(newData.mathRandom)
40
+ }
41
+ )
42
+
43
+ - it.failing(
44
+ + it(
45
+ 'should update cached data used by a page fetched without a cookie after editing a file',
46
+ async () => {
47
+ // `next.render$` fetches directly, without the browser HMR client, so
48
+ @@ -202,6 +208,13 @@ describe('use-cache-dev', () => {
49
+ // random value due to a cache miss.
50
+ expect($('#text').text()).toBe('bar')
51
+ expect($('#mathRandom').text()).not.toBe(initialMathRandom)
52
+ +
53
+ + // The post-edit value should remain cached on another direct request.
54
+ + const editedMathRandom = $('#mathRandom').text()
55
+ + $ = await next.render$('/cached-page')
56
+ +
57
+ + expect($('#text').text()).toBe('bar')
58
+ + expect($('#mathRandom').text()).toBe(editedMathRandom)
59
+ }
60
+ )
61
+
nextjs-96022-dev-use-cache-invalidation/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ 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
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ 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
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ 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
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ 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
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-byte-budgeted-lru-keys/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && 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' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-byte-budgeted-lru-keys/solution/gold.patch ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/server/dev/next-dev-server.ts b/packages/next/src/server/dev/next-dev-server.ts
2
+ index 388dd82b9e..14dbe16304 100644
3
+ --- a/packages/next/src/server/dev/next-dev-server.ts
4
+ +++ b/packages/next/src/server/dev/next-dev-server.ts
5
+ @@ -195,9 +195,11 @@ export default class DevServer extends Server {
6
+ this.staticPathsCache = new LRUCache(
7
+ // 5MB
8
+ 5 * 1024 * 1024,
9
+ - function length(value) {
10
+ + function length(value, cacheKey) {
11
+ // Ensure minimum size of 1 for LRU eviction to work correctly
12
+ - return JSON.stringify(value.staticPaths)?.length || 1
13
+ + return (
14
+ + cacheKey.length + (JSON.stringify(value.staticPaths)?.length || 1)
15
+ + )
16
+ }
17
+ )
18
+
19
+ @@ -214,8 +216,8 @@ export default class DevServer extends Server {
20
+ )
21
+ this.serverComponentsHmrCache = new LRUCache(
22
+ hmrCacheSize,
23
+ - function length(value) {
24
+ - return JSON.stringify(value).length
25
+ + function length(value, cacheKey) {
26
+ + return cacheKey.length + JSON.stringify(value).length
27
+ }
28
+ )
29
+ }
30
+ diff --git a/packages/next/src/server/lib/cache-handlers/default.ts b/packages/next/src/server/lib/cache-handlers/default.ts
31
+ index 112c41a203..b188176d98 100644
32
+ --- a/packages/next/src/server/lib/cache-handlers/default.ts
33
+ +++ b/packages/next/src/server/lib/cache-handlers/default.ts
34
+ @@ -58,7 +58,7 @@ export function createDefaultCacheHandler(maxSize: number): CacheHandler {
35
+
36
+ const memoryCache = new LRUCache<PrivateCacheEntry>(
37
+ maxSize,
38
+ - (entry) => entry.size
39
+ + (entry, cacheKey) => entry.size + cacheKey.length
40
+ )
41
+ const pendingSets = new Map<string, Promise<void>>()
42
+
43
+ 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
44
+ index e446656409..d9f66ba850 100644
45
+ --- a/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts
46
+ +++ b/packages/next/src/server/lib/incremental-cache/memory-cache.external.ts
47
+ @@ -24,30 +24,37 @@ function getSegmentDataSize(segmentData: Map<string, Buffer> | undefined) {
48
+
49
+ export function getMemoryCache(maxMemoryCacheSize: number) {
50
+ if (!memoryCache) {
51
+ - memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }) {
52
+ + memoryCache = new LRUCache(maxMemoryCacheSize, function length(
53
+ + { value },
54
+ + cacheKey
55
+ + ) {
56
+ + let valueSize: number
57
+ +
58
+ if (!value) {
59
+ - return 25
60
+ + valueSize = 25
61
+ } else if (value.kind === CachedRouteKind.REDIRECT) {
62
+ - return JSON.stringify(value.props).length
63
+ + valueSize = JSON.stringify(value.props).length
64
+ } else if (value.kind === CachedRouteKind.IMAGE) {
65
+ throw new Error('invariant image should not be incremental-cache')
66
+ } else if (value.kind === CachedRouteKind.FETCH) {
67
+ - return JSON.stringify(value.data || '').length
68
+ + valueSize = JSON.stringify(value.data || '').length
69
+ } else if (value.kind === CachedRouteKind.APP_ROUTE) {
70
+ - return value.body.length
71
+ - }
72
+ - // rough estimate of size of cache value
73
+ - if (value.kind === CachedRouteKind.APP_PAGE) {
74
+ - return Math.max(
75
+ + valueSize = value.body.length
76
+ + } else if (value.kind === CachedRouteKind.APP_PAGE) {
77
+ + // rough estimate of size of cache value
78
+ + valueSize = Math.max(
79
+ 1,
80
+ value.html.length +
81
+ getBufferSize(value.rscData) +
82
+ (value.postponed?.length || 0) +
83
+ getSegmentDataSize(value.segmentData)
84
+ )
85
+ + } else {
86
+ + valueSize =
87
+ + value.html.length + (JSON.stringify(value.pageData)?.length || 0)
88
+ }
89
+
90
+ - return value.html.length + (JSON.stringify(value.pageData)?.length || 0)
91
+ + return cacheKey.length + valueSize
92
+ })
93
+ }
94
+
95
+ diff --git a/packages/next/src/server/lib/source-maps.ts b/packages/next/src/server/lib/source-maps.ts
96
+ index af2969c03e..654de4126e 100644
97
+ --- a/packages/next/src/server/lib/source-maps.ts
98
+ +++ b/packages/next/src/server/lib/source-maps.ts
99
+ @@ -215,13 +215,13 @@ function bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {
100
+ const invalidSourceMap = Symbol('invalid-source-map')
101
+ const sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(
102
+ 512 * 1024 * 1024,
103
+ - (url) =>
104
+ - url === invalidSourceMap
105
+ - ? // Ideally we'd account for key length. So we just guestimate a small source map
106
+ - // so that we don't create a huge cache with empty source maps.
107
+ + (url, sourceURL) =>
108
+ + sourceURL.length +
109
+ + (url === invalidSourceMap
110
+ + ? // Guestimate a small source map so invalid entries don't fill the cache.
111
+ 8 * 1024
112
+ : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength
113
+ - url.length
114
+ + url.length)
115
+ )
116
+ export function findSourceMapURLDEV(
117
+ scriptNameOrSourceURL: string
nextjs-byte-budgeted-lru-keys/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-byte-budgeted-lru-keys/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && 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' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-byte-budgeted-lru-keys/tests/test.patch ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ new file mode 100644
3
+ index 0000000000..4cb91c9136
4
+ --- /dev/null
5
+ +++ b/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts
6
+ @@ -0,0 +1,237 @@
7
+ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
8
+ +import type { SourceMap } from 'module'
9
+ +import { tmpdir } from 'os'
10
+ +import { join } from 'path'
11
+ +import DevServer from 'next/dist/server/dev/next-dev-server'
12
+ +import { defaultConfig } from 'next/dist/server/config-shared'
13
+ +import type { CacheEntry } from './cache-handlers/types'
14
+ +import { createDefaultCacheHandler } from './cache-handlers/default'
15
+ +import { getMemoryCache } from './incremental-cache/memory-cache.external'
16
+ +
17
+ +function cacheEntry(body: string): CacheEntry {
18
+ + return {
19
+ + value: new ReadableStream({
20
+ + start(controller) {
21
+ + controller.enqueue(new TextEncoder().encode(body))
22
+ + controller.close()
23
+ + },
24
+ + }),
25
+ + tags: [],
26
+ + stale: 60,
27
+ + timestamp: Date.now(),
28
+ + expire: 60,
29
+ + revalidate: 60,
30
+ + }
31
+ +}
32
+ +
33
+ +class TestDevServer extends DevServer {
34
+ + readStaticPaths(pathname: string) {
35
+ + return this.getStaticPaths({
36
+ + pathname,
37
+ + urlPathname: pathname,
38
+ + requestHeaders: {},
39
+ + page: '/[slug]',
40
+ + isAppPath: false,
41
+ + })
42
+ + }
43
+ +
44
+ + hmrCache() {
45
+ + return this.getServerComponentsHmrCache()
46
+ + }
47
+ +}
48
+ +
49
+ +describe('byte-budgeted server caches', () => {
50
+ + it('charges incremental-cache keys against the memory budget', () => {
51
+ + const cache = getMemoryCache(64)
52
+ + const key = `/api/data?${'p'.repeat(80)}`
53
+ + const warning = jest.spyOn(console, 'warn').mockImplementation()
54
+ +
55
+ + cache?.set(key, {
56
+ + value: { kind: 'FETCH', data: { body: 'ok' } },
57
+ + lastModified: 1,
58
+ + } as any)
59
+ +
60
+ + warning.mockRestore()
61
+ + expect(cache?.get(key)).toBeUndefined()
62
+ + })
63
+ +
64
+ + it('charges use-cache keys against the default handler budget', async () => {
65
+ + const handler = createDefaultCacheHandler(16)
66
+ + const key = `cache-${'k'.repeat(32)}`
67
+ + const warning = jest.spyOn(console, 'warn').mockImplementation()
68
+ +
69
+ + await handler.set(key, Promise.resolve(cacheEntry('x')))
70
+ +
71
+ + warning.mockRestore()
72
+ + expect(await handler.get(key, [])).toBeUndefined()
73
+ + })
74
+ +
75
+ + it('charges route keys against the development static paths budget', async () => {
76
+ + const dir = mkdtempSync(join(tmpdir(), 'next-static-paths-cache-'))
77
+ + mkdirSync(join(dir, 'pages'))
78
+ + mkdirSync(join(dir, '.next', 'server', 'pages'), { recursive: true })
79
+ + writeFileSync(
80
+ + join(dir, '.next', 'prerender-manifest.json'),
81
+ + JSON.stringify({
82
+ + version: 4,
83
+ + routes: {},
84
+ + dynamicRoutes: {},
85
+ + notFoundRoutes: [],
86
+ + preview: {
87
+ + previewModeId: 'a'.repeat(32),
88
+ + previewModeSigningKey: 'b'.repeat(64),
89
+ + previewModeEncryptionKey: 'c'.repeat(32),
90
+ + },
91
+ + })
92
+ + )
93
+ + writeFileSync(join(dir, '.next', 'build-manifest.json'), '{}')
94
+ + writeFileSync(join(dir, '.next', 'react-loadable-manifest.json'), '{}')
95
+ + writeFileSync(
96
+ + join(dir, '.next', 'server', 'pages-manifest.json'),
97
+ + JSON.stringify({
98
+ + '/_document': 'pages/_document.js',
99
+ + '/_app': 'pages/_app.js',
100
+ + '/[slug]': 'pages/[slug].js',
101
+ + })
102
+ + )
103
+ + writeFileSync(
104
+ + join(dir, '.next', 'server', 'pages', '_document.js'),
105
+ + 'module.exports={default:()=>null}'
106
+ + )
107
+ + writeFileSync(
108
+ + join(dir, '.next', 'server', 'pages', '_app.js'),
109
+ + 'module.exports={default:()=>null}'
110
+ + )
111
+ + const counter = join(dir, 'counter')
112
+ + writeFileSync(counter, '0')
113
+ + writeFileSync(
114
+ + join(dir, '.next', 'server', 'pages', '[slug].js'),
115
+ + `const fs=require('fs');const p=${JSON.stringify(
116
+ + counter
117
+ + )};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}}}`
118
+ + )
119
+ +
120
+ + try {
121
+ + const server = new TestDevServer({
122
+ + dir,
123
+ + conf: {
124
+ + ...defaultConfig,
125
+ + experimental: {
126
+ + ...defaultConfig.experimental,
127
+ + instantInsights: { validationLevel: 'warning' },
128
+ + useCacheTimeout: 50,
129
+ + turbopackMemoryEvictionMode: 'auto',
130
+ + },
131
+ + },
132
+ + bundlerService: {
133
+ + getServerComponentsHmrRefreshHash: () => '',
134
+ + sendHmrMessage: jest.fn(),
135
+ + } as any,
136
+ + startServerSpan: undefined as any,
137
+ + })
138
+ + const parameterName = 'p'.repeat(3 * 1024 * 1024)
139
+ + const first = `/[${parameterName}a]`
140
+ + const second = `/[${parameterName}b]`
141
+ +
142
+ + await server.readStaticPaths(first)
143
+ + await server.readStaticPaths(second)
144
+ + const refreshed = await server.readStaticPaths(first)
145
+ +
146
+ + for (let i = 0; i < 100 && Number(readFileSync(counter)) < 3; i++) {
147
+ + await new Promise((resolve) => setTimeout(resolve, 10))
148
+ + }
149
+ + await new Promise((resolve) => setTimeout(resolve, 100))
150
+ + expect(refreshed.staticPaths).toEqual(['/generated-3'])
151
+ + } finally {
152
+ + rmSync(dir, { recursive: true, force: true })
153
+ + }
154
+ + })
155
+ +
156
+ + it('charges module keys against the development HMR cache budget', () => {
157
+ + const dir = mkdtempSync(join(tmpdir(), 'next-dev-cache-'))
158
+ + mkdirSync(join(dir, 'pages'))
159
+ + mkdirSync(join(dir, '.next'))
160
+ + writeFileSync(
161
+ + join(dir, '.next', 'prerender-manifest.json'),
162
+ + JSON.stringify({
163
+ + version: 4,
164
+ + routes: {},
165
+ + dynamicRoutes: {},
166
+ + notFoundRoutes: [],
167
+ + preview: {
168
+ + previewModeId: 'a'.repeat(32),
169
+ + previewModeSigningKey: 'b'.repeat(64),
170
+ + previewModeEncryptionKey: 'c'.repeat(32),
171
+ + },
172
+ + })
173
+ + )
174
+ +
175
+ + try {
176
+ + const server = new TestDevServer({
177
+ + dir,
178
+ + conf: {
179
+ + ...defaultConfig,
180
+ + experimental: {
181
+ + ...defaultConfig.experimental,
182
+ + serverComponentsHmrCache: true,
183
+ + instantInsights: { validationLevel: 'warning' },
184
+ + useCacheTimeout: 50,
185
+ + turbopackMemoryEvictionMode: 'auto',
186
+ + },
187
+ + },
188
+ + bundlerService: {
189
+ + getServerComponentsHmrRefreshHash: () => '',
190
+ + sendHmrMessage: jest.fn(),
191
+ + } as any,
192
+ + startServerSpan: undefined as any,
193
+ + })
194
+ + const cache = server.hmrCache()
195
+ + const prefix = 'm'.repeat(30 * 1024 * 1024)
196
+ + const first = `${prefix}-first`
197
+ + const second = `${prefix}-second`
198
+ +
199
+ + cache!.set(first, ['first'] as any)
200
+ + cache!.set(second, ['second'] as any)
201
+ +
202
+ + expect(cache!.get(first)).toBeUndefined()
203
+ + expect(cache!.get(second)).toEqual(['second'])
204
+ + } finally {
205
+ + rmSync(dir, { recursive: true, force: true })
206
+ + }
207
+ + })
208
+ +
209
+ + it('eventually revisits old source-map misses when URL keys fill the budget', () => {
210
+ + jest.resetModules()
211
+ + const nodeModule = jest.requireActual<typeof import('module')>('module')
212
+ + const available = new Map<string, SourceMap>()
213
+ + const findSourceMap = jest
214
+ + .spyOn(nodeModule, 'findSourceMap')
215
+ + .mockImplementation((sourceURL) => available.get(sourceURL))
216
+ +
217
+ + let sourceMaps!: typeof import('./source-maps')
218
+ + jest.isolateModules(() => {
219
+ + sourceMaps = require('./source-maps')
220
+ + })
221
+ +
222
+ + const original = 'server-entry.js'
223
+ + expect(sourceMaps.findSourceMapURLDEV(original)).toBeNull()
224
+ +
225
+ + for (let i = 0; i < 65_535; i++) {
226
+ + sourceMaps.findSourceMapURLDEV(`chunk-${i}-${'x'.repeat(96)}`)
227
+ + }
228
+ +
229
+ + available.set(original, {
230
+ + payload: {
231
+ + version: 3,
232
+ + file: original,
233
+ + sources: ['server-entry.ts'],
234
+ + names: [],
235
+ + mappings: '',
236
+ + },
237
+ + } as SourceMap)
238
+ +
239
+ + const refreshed = sourceMaps.findSourceMapURLDEV(original)
240
+ + findSourceMap.mockRestore()
241
+ + expect(refreshed).toMatch(/^data:application\/json;base64,/)
242
+ + })
243
+ +})
nextjs-byte-budgeted-lru-keys/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/packages/next/src/server/lib/byte-budgeted-cache-keys.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ 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
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ 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
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'true'; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-byte-exact-binary-fetch-cache-keys/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-byte-exact-binary-fetch-cache-keys/tests/test.patch ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/unit/incremental-cache/generate-cache-key.test.ts b/test/unit/incremental-cache/generate-cache-key.test.ts
2
+ new file mode 100644
3
+ index 00000000..f320376b
4
+ --- /dev/null
5
+ +++ b/test/unit/incremental-cache/generate-cache-key.test.ts
6
+ @@ -0,0 +1,252 @@
7
+ +import { IncrementalCache } from '../../../packages/next/src/server/lib/incremental-cache'
8
+ +
9
+ +function createCache() {
10
+ + return new IncrementalCache({
11
+ + dev: false,
12
+ + requestHeaders: {},
13
+ + getPrerenderManifest: () =>
14
+ + ({
15
+ + version: 4,
16
+ + routes: {},
17
+ + dynamicRoutes: {},
18
+ + notFoundRoutes: [],
19
+ + preview: {
20
+ + previewModeId: 'id',
21
+ + previewModeSigningKey: 'key',
22
+ + previewModeEncryptionKey: 'key',
23
+ + },
24
+ + }) as any,
25
+ + })
26
+ +}
27
+ +
28
+ +describe('IncrementalCache.generateCacheKey', () => {
29
+ + const cache = createCache()
30
+ + const url = 'https://example.com/api'
31
+ +
32
+ + it('distinguishes binary bodies that UTF-8 decoding would collapse', async () => {
33
+ + // 0xff and 0xfe both decode to U+FFFD as UTF-8; the key must tell them
34
+ + // apart by their raw bytes.
35
+ + const a = await cache.generateCacheKey(url, {
36
+ + body: new Uint8Array([0xff]),
37
+ + })
38
+ + const b = await cache.generateCacheKey(url, {
39
+ + body: new Uint8Array([0xfe]),
40
+ + })
41
+ + expect(a).not.toBe(b)
42
+ + })
43
+ +
44
+ + it('distinguishes a string body from its UTF-8 encoded bytes', async () => {
45
+ + // A string and the bytes it encodes to are different request shapes.
46
+ + const a = await cache.generateCacheKey(url, { body: 'hello' })
47
+ + const b = await cache.generateCacheKey(url, {
48
+ + body: new TextEncoder().encode('hello'),
49
+ + })
50
+ + expect(a).not.toBe(b)
51
+ + })
52
+ +
53
+ + it('uses the selected bytes of arbitrary ArrayBuffer views', async () => {
54
+ + const backing = new Uint8Array([9, 1, 2, 3, 9])
55
+ + const dataView = new DataView(backing.buffer, 1, 3)
56
+ + const typedView = new Uint8Array([1, 2, 3])
57
+ +
58
+ + const a = await cache.generateCacheKey(url, { body: dataView })
59
+ + const b = await cache.generateCacheKey(url, { body: typedView })
60
+ + expect(a).toBe(b)
61
+ + })
62
+ +
63
+ + it('distinguishes URLSearchParams, FormData, and string bodies', async () => {
64
+ + const form = new FormData()
65
+ + form.append('x', 'a')
66
+ +
67
+ + const formKey = await cache.generateCacheKey(url, { body: form })
68
+ + const paramsKey = await cache.generateCacheKey(url, {
69
+ + body: new URLSearchParams([['x', 'a']]),
70
+ + })
71
+ + const stringKey = await cache.generateCacheKey(url, { body: 'x=a' })
72
+ +
73
+ + expect(new Set([formKey, paramsKey, stringKey]).size).toBe(3)
74
+ + })
75
+ +
76
+ + it('distinguishes a Blob from its raw content bytes', async () => {
77
+ + const bytes = new Uint8Array([1, 2, 3])
78
+ + const blobKey = await cache.generateCacheKey(url, {
79
+ + body: new Blob([bytes]),
80
+ + })
81
+ + const bytesKey = await cache.generateCacheKey(url, { body: bytes })
82
+ +
83
+ + expect(blobKey).not.toBe(bytesKey)
84
+ + })
85
+ +
86
+ + it('is deterministic for identical bodies', async () => {
87
+ + const a = await cache.generateCacheKey(url, {
88
+ + body: new Uint8Array([1, 2, 3]),
89
+ + })
90
+ + const b = await cache.generateCacheKey(url, {
91
+ + body: new Uint8Array([1, 2, 3]),
92
+ + })
93
+ + expect(a).toBe(b)
94
+ + })
95
+ +
96
+ + it('does not collide FormData multi-values with a comma-joined string', async () => {
97
+ + // The two values ['a', 'b'] must not hash the same as the single 'a,b'.
98
+ + const multi = new FormData()
99
+ + multi.append('x', 'a')
100
+ + multi.append('x', 'b')
101
+ +
102
+ + const joined = new FormData()
103
+ + joined.append('x', 'a,b')
104
+ +
105
+ + const a = await cache.generateCacheKey(url, { body: multi })
106
+ + const b = await cache.generateCacheKey(url, { body: joined })
107
+ + expect(a).not.toBe(b)
108
+ + })
109
+ +
110
+ + it('distinguishes blobs that differ only by content type', async () => {
111
+ + const bytes = new Uint8Array([1, 2, 3])
112
+ + const a = await cache.generateCacheKey(url, {
113
+ + body: new Blob([bytes], { type: 'text/plain' }),
114
+ + })
115
+ + const b = await cache.generateCacheKey(url, {
116
+ + body: new Blob([bytes], { type: 'application/json' }),
117
+ + })
118
+ + expect(a).not.toBe(b)
119
+ + })
120
+ +
121
+ + it('distinguishes ArrayBuffers', async () => {
122
+ + const a = await cache.generateCacheKey(url, {
123
+ + body: new Uint8Array([1, 2, 3, 4]).buffer,
124
+ + })
125
+ + const b = await cache.generateCacheKey(url, {
126
+ + body: new Uint8Array([1, 2, 3]).buffer,
127
+ + })
128
+ + expect(a).not.toBe(b)
129
+ + })
130
+ +
131
+ + it('produces the same key for identical bytes in different typed arrays', async () => {
132
+ + const uint8View = new Uint8Array([1, 2, 3, 4])
133
+ + const uint16View = new Uint16Array(
134
+ + uint8View.buffer,
135
+ + uint8View.byteOffset,
136
+ + uint8View.byteLength / 2
137
+ + )
138
+ + const a = await cache.generateCacheKey(url, {
139
+ + body: uint8View,
140
+ + })
141
+ + const b = await cache.generateCacheKey(url, {
142
+ + body: uint16View,
143
+ + })
144
+ + expect(a).toBe(b)
145
+ + })
146
+ +
147
+ + it('does not collide FormData with differently interleaved values', async () => {
148
+ + const a = new FormData()
149
+ + a.append('x', 'a')
150
+ + a.append('x', 'b')
151
+ + a.append('y', 'a')
152
+ +
153
+ + const b = new FormData()
154
+ + b.append('x', 'a')
155
+ + b.append('y', 'a')
156
+ + b.append('x', 'b')
157
+ +
158
+ + const keyA = await cache.generateCacheKey(url, { body: a })
159
+ + const keyB = await cache.generateCacheKey(url, { body: b })
160
+ + expect(keyA).not.toBe(keyB)
161
+ + })
162
+ +
163
+ + it('does not collide FormData whose value forges quoted entry delimiters', async () => {
164
+ + // User values may resemble framing text and must remain data.
165
+ + const a = new FormData()
166
+ + a.append('x', 'a"key:"y"str:"b')
167
+ +
168
+ + const b = new FormData()
169
+ + b.append('x', 'a')
170
+ + b.append('y', 'b')
171
+ +
172
+ + const keyA = await cache.generateCacheKey(url, { body: a })
173
+ + const keyB = await cache.generateCacheKey(url, { body: b })
174
+ + expect(keyA).not.toBe(keyB)
175
+ + })
176
+ +
177
+ + it('does not collide FormData whose value spans an entry boundary', async () => {
178
+ + // One value may contain text resembling a complete following entry.
179
+ + const a = new FormData()
180
+ + a.append('x', 'akey:ystr:b')
181
+ +
182
+ + const b = new FormData()
183
+ + b.append('x', 'a')
184
+ + b.append('y', 'b')
185
+ +
186
+ + const keyA = await cache.generateCacheKey(url, { body: a })
187
+ + const keyB = await cache.generateCacheKey(url, { body: b })
188
+ + expect(keyA).not.toBe(keyB)
189
+ + })
190
+ +
191
+ + it('does not collide FormData files that differ only by name/type split', async () => {
192
+ + // File name and content type are separate fetch-relevant metadata.
193
+ + const bytes = new Uint8Array([1, 2, 3])
194
+ +
195
+ + const a = new FormData()
196
+ + a.append('f', new Blob([bytes], { type: 'c' }), 'ab')
197
+ +
198
+ + const b = new FormData()
199
+ + b.append('f', new Blob([bytes], { type: 'bc' }), 'a')
200
+ +
201
+ + const keyA = await cache.generateCacheKey(url, { body: a })
202
+ + const keyB = await cache.generateCacheKey(url, { body: b })
203
+ + expect(keyA).not.toBe(keyB)
204
+ + })
205
+ +
206
+ + it('does not collide a file whose content forges a following entry', async () => {
207
+ + // File bytes may resemble framing for a following field.
208
+ + const enc = new TextEncoder()
209
+ +
210
+ + const a = new FormData()
211
+ + a.append('f', new Blob([enc.encode('AAAkey:1kstr:1v')], { type: '' }), 'n')
212
+ +
213
+ + const b = new FormData()
214
+ + b.append('f', new Blob([enc.encode('AAA')], { type: '' }), 'n')
215
+ + b.append('k', 'v')
216
+ +
217
+ + const keyA = await cache.generateCacheKey(url, { body: a })
218
+ + const keyB = await cache.generateCacheKey(url, { body: b })
219
+ + expect(keyA).not.toBe(keyB)
220
+ + })
221
+ +
222
+ + it('does not collide blobs that differ only by type/content split', async () => {
223
+ + // Blob content types and bytes must be framed as separate values.
224
+ + const enc = new TextEncoder()
225
+ +
226
+ + const a = new Blob([enc.encode('y')], { type: 'bytes:x' })
227
+ + const b = new Blob([enc.encode('xbytes:y')], { type: '' })
228
+ +
229
+ + const keyA = await cache.generateCacheKey(url, { body: a })
230
+ + const keyB = await cache.generateCacheKey(url, { body: b })
231
+ + expect(keyA).not.toBe(keyB)
232
+ + })
233
+ +
234
+ + it('does not collide a FormData value whose length digits absorb a forged entry', async () => {
235
+ + // Length digits adjacent to user data must not make framing ambiguous.
236
+ + const a = new FormData()
237
+ + a.append('x', 'key:1astr:0')
238
+ +
239
+ + const b = new FormData()
240
+ + b.append('x', '1')
241
+ + b.append('a', '')
242
+ +
243
+ + const keyA = await cache.generateCacheKey(url, { body: a })
244
+ + const keyB = await cache.generateCacheKey(url, { body: b })
245
+ + expect(keyA).not.toBe(keyB)
246
+ + })
247
+ +
248
+ + it('does not collide blobs whose type-length digits absorb the content', async () => {
249
+ + // Type lengths and content beginning with digits remain distinct.
250
+ + const enc = new TextEncoder()
251
+ + const a = new Blob([new Uint8Array(0)], { type: 'bytes:aaaaa' })
252
+ + const b = new Blob([enc.encode('aaaaabytes:')], { type: '1' })
253
+ +
254
+ + const keyA = await cache.generateCacheKey(url, { body: a })
255
+ + const keyB = await cache.generateCacheKey(url, { body: b })
256
+ + expect(keyA).not.toBe(keyB)
257
+ + })
258
+ +})
nextjs-byte-exact-binary-fetch-cache-keys/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/unit/incremental-cache/generate-cache-key.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/unit/incremental-cache/generate-cache-key.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/unit/incremental-cache/generate-cache-key.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/generate-cache-key.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm test-webpack '"'"'test/unit/incremental-cache/generate-cache-key.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ 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
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-cache-short-expire-dev/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-cache-short-expire-dev/solution/gold.patch ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/server/lib/cache-handlers/default.ts b/packages/next/src/server/lib/cache-handlers/default.ts
2
+ index 5a215994fe..0270c24b62 100644
3
+ --- a/packages/next/src/server/lib/cache-handlers/default.ts
4
+ +++ b/packages/next/src/server/lib/cache-handlers/default.ts
5
+ @@ -20,6 +20,7 @@ import {
6
+ tagsManifest,
7
+ type TagManifestEntry,
8
+ } from '../incremental-cache/tags-manifest.external'
9
+ +import { MIN_PRERENDERABLE_EXPIRE } from '../../use-cache/constants'
10
+
11
+ type PrivateCacheEntry = {
12
+ entry: CacheEntry
13
+ @@ -83,10 +84,30 @@ export function createDefaultCacheHandler(maxSize: number): CacheHandler {
14
+
15
+ const entry = privateEntry.entry
16
+
17
+ + // A negative `expire` is an eviction sentinel: the tiered cache handler
18
+ + // (dev-only) marks a front entry for deletion by overwriting it with a
19
+ + // negative `expire`, since the cache-handler interface has no per-key
20
+ + // delete. Treat it as missing here, independently of the minimum
21
+ + // retention below (which would otherwise keep it alive). This is distinct
22
+ + // from `revalidate = -1` below, which keeps serving the entry but forces
23
+ + // a revalidation.
24
+ + if (entry.expire < 0) {
25
+ + debug?.('get', cacheKey, 'evicted')
26
+ + return undefined
27
+ + }
28
+ +
29
+ // The dev server serves stale entries until they expire (see the file
30
+ - // overview); production drops them once past the revalidate time.
31
+ + // overview); production drops them once past the revalidate time. In dev,
32
+ + // an entry is retained for at least `MIN_PRERENDERABLE_EXPIRE` so that
33
+ + // entries with a short `expire` (for example a `cacheLife({ expire: 0 })`
34
+ + // client-only cache) still linger long enough that a reload hits the
35
+ + // cache. That minimum is the same threshold below which the "use cache"
36
+ + // wrapper treats an entry as dynamic, so it only extends the retention of
37
+ + // entries that are dynamic anyway. It affects retention only; the
38
+ + // returned entry keeps its real `expire`, so staging decisions are
39
+ + // unchanged.
40
+ const maxAgeSeconds = process.env.__NEXT_DEV_SERVER
41
+ - ? entry.expire
42
+ + ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)
43
+ : entry.revalidate
44
+
45
+ if (
46
+ diff --git a/packages/next/src/server/use-cache/handlers.ts b/packages/next/src/server/use-cache/handlers.ts
47
+ index 8217c381ee..d9edb00284 100644
48
+ --- a/packages/next/src/server/use-cache/handlers.ts
49
+ +++ b/packages/next/src/server/use-cache/handlers.ts
50
+ @@ -107,26 +107,25 @@ export function initializeCacheHandlers(cacheMaxMemorySize: number): boolean {
51
+ // Create a set of the cache handlers.
52
+ reference[handlersSetSymbol] = new Set(handlersMap.values())
53
+
54
+ - // In development we add dedicated built-in in-memory handlers so that warm
55
+ - // reloads are fast. These are always built-in handlers, never a
56
+ - // user-configured one, and are gated on the dev server so production behaves
57
+ - // exactly as configured.
58
+ + // In development we add dedicated built-in in-memory handlers so that reloads
59
+ + // are fast. These are always built-in handlers, never a user-configured one,
60
+ + // and are gated on the dev server so production behaves exactly as
61
+ + // configured.
62
+ if (process.env.__NEXT_DEV_SERVER) {
63
+ reference[memoryCacheDisabledSymbol] = cacheMaxMemorySize === 0
64
+
65
+ - // Private caches are persisted here so warm reloads are fast. Private
66
+ - // entries can hold data specific to the incoming request (for example,
67
+ - // derived from its cookies or headers), so this is never the
68
+ - // user-configured `default` alias. Sized so it still caches under
69
+ - // `cacheMaxMemorySize: 0` (otherwise it would become the no-op stub and
70
+ - // private reloads would miss).
71
+ + // Private caches are persisted here so reloads are fast. Private entries
72
+ + // can hold data specific to the incoming request (for example, derived from
73
+ + // its cookies or headers), so this is never the user-configured `default`
74
+ + // alias. Sized so it still caches under `cacheMaxMemorySize: 0` (otherwise
75
+ + // it would become the no-op stub and private reloads would miss).
76
+ reference[privateHandlerSymbol] = createDefaultCacheHandler(
77
+ DEV_MEMORY_CACHE_SIZE
78
+ )
79
+
80
+ // Built-in front handlers, one per custom kind, and the tiered handlers
81
+ // that place a front in front of a (possibly slow or remote) backing
82
+ - // handler so warm reads resolve in a microtask, are both created per kind
83
+ + // handler so cache hits resolve in a microtask, are both created per kind
84
+ // in `setCacheHandler`.
85
+ reference[devFrontHandlersSymbol] = new Map()
86
+ reference[devTieredHandlersSymbol] = new Map()
87
+ @@ -178,7 +177,7 @@ export function isMemoryCacheDisabled(): boolean {
88
+ * Whether `kind` is backed by a real user-configured handler rather than the
89
+ * built-in in-memory default. Such a handler may be slow or remote, so in
90
+ * development a built-in front handler is placed in front of it (see
91
+ - * `getDevTieredCacheHandler`) to keep warm reads microtask-fast. The presence
92
+ + * `getDevTieredCacheHandler`) to keep cache hits microtask-fast. The presence
93
+ * of a dev front handler is the signal, since front handlers are created
94
+ * exactly for user-registered kinds. Always `false` in production.
95
+ */
96
+ @@ -193,7 +192,7 @@ export function isCustomCacheHandler(kind: string): boolean {
97
+ /**
98
+ * Get the dev-only tiered cache handler for a custom `kind`: a fast built-in
99
+ * in-memory front handler in front of the user-configured backing handler, so
100
+ - * warm reads resolve in a microtask. Returns `undefined` if there is none (a
101
+ + * cache hits resolve in a microtask. Returns `undefined` if there is none (a
102
+ * built-in kind, or production).
103
+ */
104
+ export function getDevTieredCacheHandler(
105
+ @@ -307,11 +306,14 @@ export function setCacheHandler(
106
+ reference[handlersSetSymbol].add(cacheHandler)
107
+
108
+ // A user-configured handler may be slow or remote. In development, give it a
109
+ - // dedicated built-in in-memory front handler so warm reads resolve in a
110
+ + // dedicated built-in in-memory front handler so cache hits resolve in a
111
+ // microtask, and pair the two into a tiered handler the wrapper reads
112
+ // through. Both are created alongside registration so their lifecycle matches
113
+ // the backing handler's, and the front handler's presence is the signal that
114
+ - // this kind is backed by a real handler (see `isCustomCacheHandler`).
115
+ + // this kind is backed by a real handler (see `isCustomCacheHandler`). Being a
116
+ + // built-in default handler, the front inherits the dev minimum retention, so
117
+ + // a short-`expire` value still hits the front instead of falling through to
118
+ + // the slow backing on every read.
119
+ if (process.env.__NEXT_DEV_SERVER) {
120
+ const frontHandler = createDefaultCacheHandler(DEV_MEMORY_CACHE_SIZE)
121
+ reference[devFrontHandlersSymbol]?.set(kind, frontHandler)
122
+ diff --git a/packages/next/src/server/use-cache/tiered-cache-handler.ts b/packages/next/src/server/use-cache/tiered-cache-handler.ts
123
+ index a73ba7e920..a5e8b3eeac 100644
124
+ --- a/packages/next/src/server/use-cache/tiered-cache-handler.ts
125
+ +++ b/packages/next/src/server/use-cache/tiered-cache-handler.ts
126
+ @@ -14,7 +14,7 @@ export type CacheReadWriteHandler = Pick<CacheHandler, 'get' | 'set'>
127
+ /**
128
+ * Development-only. Puts a fast built-in in-memory `front` handler in front of
129
+ * a slower or persistent user-configured `backing` handler. Its only job is to
130
+ - * guarantee that warm reads resolve in a microtask (so they aren't counted as
131
+ + * guarantee that cache hits resolve in a microtask (so they aren't counted as
132
+ * cache misses at a staged-render boundary, which would otherwise surface a
133
+ * cold cache indicator), while keeping the front in sync with the backing.
134
+ *
135
+ @@ -76,9 +76,9 @@ export function createTieredCacheHandler(
136
+ const frontEntry = await front.get(cacheKey, softTags)
137
+
138
+ if (frontEntry) {
139
+ - // Warm hit: serve immediately (in a microtask). A background reconcile
140
+ + // Cache hit: serve immediately (in a microtask). A background reconcile
141
+ // keeps the front in sync with the backing for the next read;
142
+ - // reconciles for the same key are serialized, so concurrent warm reads
143
+ + // reconciles for the same key are serialized, so concurrent cache hits
144
+ // don't hit the backing in parallel.
145
+ scheduleBackgroundSync(cacheKey, () =>
146
+ reconcileFrontFromBacking(
147
+ @@ -104,7 +104,7 @@ export function createTieredCacheHandler(
148
+ }
149
+
150
+ // Mirror this freshly read backing entry into the front so the next read
151
+ - // is warm. The mirror is serialized per key: if a sync is already
152
+ + // hits it. The mirror is serialized per key: if a sync is already
153
+ // running, this chains after it, so the front converges to this read even
154
+ // if the backing changed since that sync started.
155
+ const [servedEntry, mirroredEntry] = cloneCacheEntry(backingEntry)
156
+ @@ -130,9 +130,9 @@ export function createTieredCacheHandler(
157
+ }
158
+
159
+ /**
160
+ - * After serving a warm front hit, consult the backing and mirror a newer entry
161
+ - * into the front for the next read. Runs in the background; failures are
162
+ - * non-fatal.
163
+ + * After serving a cache hit from the front, consult the backing and mirror a
164
+ + * newer entry into the front for the next read. Runs in the background;
165
+ + * failures are non-fatal.
166
+ */
167
+ async function reconcileFrontFromBacking(
168
+ front: CacheHandler,
169
+ @@ -186,17 +186,18 @@ async function mirrorIntoFront(
170
+
171
+ /**
172
+ * Build an already-expired copy of an entry, used to evict it from the front
173
+ - * handler (which has no per-key delete) once the backing no longer has it. In
174
+ - * dev the default handler treats an entry as missing once `now > timestamp +
175
+ - * expire * 1000`, so `expire: 0` against the original (past) timestamp makes
176
+ - * the next read a miss. The value is never read once the entry is expired, but
177
+ - * it must carry at least one byte because the built-in LRU cache refuses to
178
+ - * store size-0 entries.
179
+ + * handler (which has no per-key delete) once the backing no longer has it. The
180
+ + * default handler treats a negative `expire` as an eviction sentinel and
181
+ + * reports the entry as missing on the next read. A negative `expire` is used
182
+ + * rather than `0` because the dev front handler enforces a minimum retention,
183
+ + * so a `0` `expire` would be kept alive by that minimum instead of evicted. The
184
+ + * value is never read once the entry is evicted, but it must carry at least one
185
+ + * byte because the built-in LRU cache refuses to store size-0 entries.
186
+ */
187
+ function toExpiredEntry(entry: CacheEntry): CacheEntry {
188
+ return {
189
+ ...entry,
190
+ - expire: 0,
191
+ + expire: -1,
192
+ value: new ReadableStream({
193
+ start(controller) {
194
+ controller.enqueue(new Uint8Array(1))
195
+ diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts
196
+ index 9dfddda9d4..3ca4a061e8 100644
197
+ --- a/packages/next/src/server/use-cache/use-cache-wrapper.ts
198
+ +++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts
199
+ @@ -1092,12 +1092,17 @@ async function collectResult(
200
+ // `MIN_PRERENDERABLE_EXPIRE` (5 minutes) caps how long an entry lingers in
201
+ // the dedicated in-memory private handler. It is the shortest `expire` that
202
+ // isn't treated as dynamic; a smaller `expire` would exclude the entry from
203
+ - // prerenders. The size-0 case (`cacheMaxMemorySize: 0`) deliberately does NOT
204
+ - // force this: it keeps its resolved cache life so that the cache entry can be
205
+ - // considered prerenderable instead of being misread as a dynamic hole, and a
206
+ - // separate dev revalidation (see the cache-hit path below) keeps its reloads
207
+ - // showing a fresh value. Custom kinds keep their real cache life too, since
208
+ - // their backing handler owns it.
209
+ + // prerenders. Two other cases deliberately do NOT force this and keep their
210
+ + // resolved cache life, relying instead on the dev handler's minimum retention
211
+ + // and a dev revalidation (see the cache-hit path below) to keep reloads fast
212
+ + // and fresh. The size-0 case (`cacheMaxMemorySize: 0`) keeps its life so the
213
+ + // entry can be considered prerenderable instead of being misread as a dynamic
214
+ + // hole. An explicit short-`expire` public cache (e.g. `cacheLife({ expire: 0
215
+ + // })`) keeps its life so it stays correctly excluded from static prerenders
216
+ + // via its real `expire` while a reload still hits the cache; forcing
217
+ + // `revalidate: 0` here would instead corrupt the cache life propagated to an
218
+ + // enclosing cache and trigger the nested-dynamic error. A cache backed by a
219
+ + // custom handler keeps its real cache life too, since that handler owns it.
220
+ const forceDynamicCacheLifeInDev = isPrivateCacheInDev
221
+
222
+ // If cacheLife() was used to set an explicit revalidate/expire/stale time we
223
+ @@ -1640,7 +1645,7 @@ export async function cache(
224
+ if (isPrivate) {
225
+ // Private caches normally go to the Resume Data Cache (RDC), not a cache
226
+ // handler. In development we additionally persist them in a dedicated
227
+ - // built-in in-memory handler so that warm reloads are fast.
228
+ + // built-in in-memory handler so that reloads are fast.
229
+ if (process.env.__NEXT_DEV_SERVER) {
230
+ cacheHandler = getPrivateCacheHandler()
231
+ }
232
+ @@ -1652,7 +1657,7 @@ export async function cache(
233
+
234
+ // In development, a user-configured (custom) handler may be slow or
235
+ // remote, so we read through a tiered handler that puts a built-in
236
+ - // in-memory front in front of it to keep warm reads microtask-fast.
237
+ + // in-memory front in front of it to keep cache hits microtask-fast.
238
+ // Built-in handlers (the default handler, and its size-0 replacement) are
239
+ // already in-memory and used directly.
240
+ if (process.env.__NEXT_DEV_SERVER && isCustomCacheHandler(kind)) {
241
+ @@ -2188,7 +2193,7 @@ export async function cache(
242
+
243
+ let stream: undefined | ReadableStream = undefined
244
+
245
+ - // Set when a short-lived warm hit ends its cache read up front (dev only) so
246
+ + // Set when a short-lived cache hit ends its cache read up front (dev only) so
247
+ // the static-shell boundary doesn't count it as a phantom miss. Once set, the
248
+ // cache signal read is balanced, so serving must use a plain stream and skip
249
+ // any trailing cacheSignal.endRead() call.
250
+ @@ -2945,7 +2950,19 @@ export async function cache(
251
+
252
+ if (
253
+ entry === undefined ||
254
+ - currentTime > entry.timestamp + entry.expire * 1000 ||
255
+ + // In dev, the built-in default handler retains a short-`expire` entry
256
+ + // for at least `MIN_PRERENDERABLE_EXPIRE`, both when used directly
257
+ + // and when fronting a custom cache handler. Apply that same minimum
258
+ + // here so the retained entry is served and re-warmed in the
259
+ + // background (below), rather than blocking to regenerate it on every
260
+ + // read. The entry's real `expire` is untouched, so staging still
261
+ + // treats it as dynamic.
262
+ + currentTime >
263
+ + entry.timestamp +
264
+ + (process.env.__NEXT_DEV_SERVER
265
+ + ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)
266
+ + : entry.expire) *
267
+ + 1000 ||
268
+ (workStore.isStaticGeneration &&
269
+ currentTime > entry.timestamp + entry.revalidate * 1000)
270
+ ) {
271
+ @@ -3134,19 +3151,24 @@ export async function cache(
272
+
273
+ // Trigger a background revalidation when the entry is stale (past its
274
+ // `revalidate`), so the next read gets a fresh value without blocking
275
+ - // this one. In development with the in-memory cache disabled
276
+ - // (`cacheMaxMemorySize: 0`), built-in entries keep their resolved
277
+ - // (potentially non-dynamic) cache life, so an entry read back from
278
+ - // the dev in-memory cache is normally still fresh and wouldn't
279
+ - // revalidate on its own; revalidate those on every dynamic request
280
+ - // render too, so each reload still shows a fresh value.
281
+ + // this one. Development additionally re-warms on every dynamic
282
+ + // request render in two cases where the dev in-memory entry would
283
+ + // otherwise read back as fresh, so a subsequent reload still shows a
284
+ + // fresh value. The first is with the in-memory cache disabled
285
+ + // (`cacheMaxMemorySize: 0`), where built-in entries keep their
286
+ + // resolved (potentially non-dynamic) cache life. The second is a
287
+ + // short-`expire` entry (an explicit dynamic or client-only cache,
288
+ + // e.g. `cacheLife({ expire: 0 })`), which is retained for at least
289
+ + // `MIN_PRERENDERABLE_EXPIRE` so it is served from the cache; this
290
+ + // also covers custom handlers, re-executing and writing through to
291
+ + // the backing.
292
+ let shouldTriggerBackgroundRevalidation =
293
+ currentTime > entry.timestamp + entry.revalidate * 1000
294
+ if (
295
+ !shouldTriggerBackgroundRevalidation &&
296
+ process.env.__NEXT_DEV_SERVER &&
297
+ - isMemoryCacheDisabled() &&
298
+ - !isCustomCacheHandler(kind)
299
+ + (entry.expire < MIN_PRERENDERABLE_EXPIRE ||
300
+ + (isMemoryCacheDisabled() && !isCustomCacheHandler(kind)))
301
+ ) {
302
+ switch (workUnitStore.type) {
303
+ case 'request':
nextjs-cache-short-expire-dev/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-cache-short-expire-dev/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-cache-short-expire-dev/tests/test.patch ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ index a5d1524c73..4f3c15dfb9 100644
3
+ --- a/test/development/app-dir/cache-components-dev-streaming/app/page.tsx
4
+ +++ b/test/development/app-dir/cache-components-dev-streaming/app/page.tsx
5
+ @@ -14,6 +14,11 @@ export default function Page() {
6
+ /use-cache-private-runtime-prefetch
7
+ </Link>
8
+ </li>
9
+ + <li>
10
+ + <Link href="/use-cache-expire-zero/nav">
11
+ + /use-cache-expire-zero/nav
12
+ + </Link>
13
+ + </li>
14
+ <li>
15
+ <Link href="/partial-prefetching/session-data">
16
+ /partial-prefetching/session-data
17
+ 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
18
+ new file mode 100644
19
+ index 0000000000..cdf45502d4
20
+ --- /dev/null
21
+ +++ b/test/development/app-dir/cache-components-dev-streaming/app/use-cache-expire-zero/[slug]/page.tsx
22
+ @@ -0,0 +1,43 @@
23
+ +import { Suspense } from 'react'
24
+ +import { setTimeout } from 'timers/promises'
25
+ +import { cacheLife } from 'next/cache'
26
+ +
27
+ +export const prefetch = 'allow-runtime'
28
+ +
29
+ +// A distinct slug per test keys a separate cache entry (so the first request
30
+ +// for each slug is a genuine cold miss), while both tests share this one
31
+ +// runtime-prefetchable page. Declaring the slugs also keeps `params` statically
32
+ +// known, so the page shell doesn't depend on dynamic params. In development
33
+ +// this does not pre-fill the cache.
34
+ +export function generateStaticParams() {
35
+ + return [{ slug: 'nav' }, { slug: 'reload' }]
36
+ +}
37
+ +
38
+ +async function getExpireZeroValue(slug: string) {
39
+ + 'use cache'
40
+ + // An explicit short `expire` opts this public cache into a dynamic,
41
+ + // client-only life: excluded from the static shell, but included in the
42
+ + // runtime prefetch. The slug keys the entry; the value itself is just a
43
+ + // timestamp.
44
+ + cacheLife({ expire: 0 })
45
+ + await setTimeout(1500)
46
+ + return new Date().toISOString()
47
+ +}
48
+ +
49
+ +async function ExpireZeroCached({ slug }: Promise<{ slug: string }>) {
50
+ + const value = await getExpireZeroValue(slug)
51
+ +
52
+ + return <p id="expire-zero">{value}</p>
53
+ +}
54
+ +
55
+ +export default function Page({
56
+ + params,
57
+ +}: {
58
+ + params: Promise<{ slug: string }>
59
+ +}) {
60
+ + return (
61
+ + <Suspense fallback={<p id="expire-zero-fallback">Loading...</p>}>
62
+ + <ExpireZeroCached slug={params.then(({ slug }) => slug)} />
63
+ + </Suspense>
64
+ + )
65
+ +}
66
+ 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
67
+ index 2f649898b1..b8c3b0eb1a 100644
68
+ --- a/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts
69
+ +++ b/test/development/app-dir/cache-components-dev-streaming/cache-components-dev-streaming.test.ts
70
+ @@ -189,6 +189,91 @@ describe('cache-components-dev-streaming', () => {
71
+ })
72
+ })
73
+
74
+ + it('shows the short-expire-cache fallback on a cold client navigation but not on a warm one', async () => {
75
+ + // A public `'use cache'` with an explicit short `expire` (`cacheLife({
76
+ + // expire: 0 })`) is a runtime-prefetch route here, so its cached content
77
+ + // belongs to the runtime shell stage. On a warm navigation the dev minimum
78
+ + // retention keeps the entry available, and the client defers revealing the
79
+ + // response until the shell has flushed, so the content arrives with the
80
+ + // shell and the fallback isn't shown - just like a private cache.
81
+ + const browser = await next.browser('/')
82
+ +
83
+ + // Cold navigation: the cache misses and fills in the background, so the
84
+ + // fallback is shown until the content streams in.
85
+ + await browser.elementByCss('a[href="/use-cache-expire-zero/nav"]').click()
86
+ + expect(await browser.elementByCss('#expire-zero-fallback').text()).toBe(
87
+ + 'Loading...'
88
+ + )
89
+ + expect(await browser.elementByCss('#expire-zero').text()).toBeDateString()
90
+ +
91
+ + // Wait for the background write to settle so the next navigation hits the
92
+ + // warm entry instead of racing a pending write.
93
+ + await waitFor(2000)
94
+ +
95
+ + // Hard-reload home so the warm navigation below starts from a fresh page.
96
+ + await browser.loadPage(new URL('/', next.url).href)
97
+ +
98
+ + // Warm navigation: record whether the fallback ever enters the DOM. It
99
+ + // shouldn't, since the retained entry is delivered with the shell. (The
100
+ + // client-side reveal race that this delivery relies on is covered by the
101
+ + // private-cache test above, so we don't repeat its stress loop here.)
102
+ + const fallbackObserver = observeNodeAppearances(browser, [
103
+ + 'expire-zero-fallback',
104
+ + ])
105
+ +
106
+ + await fallbackObserver.observe()
107
+ +
108
+ + await browser.elementByCss('a[href="/use-cache-expire-zero/nav"]').click()
109
+ + expect(await browser.elementByCss('#expire-zero').text()).toBeDateString()
110
+ +
111
+ + const appearanceCounts = await fallbackObserver.getResult()
112
+ + expect(appearanceCounts).toEqual({
113
+ + 'expire-zero-fallback': 0,
114
+ + })
115
+ + })
116
+ +
117
+ + it('serves a short-expire cache warm on reload and converges to a fresh value', async () => {
118
+ + const browser = await next.browser('/use-cache-expire-zero/reload', {
119
+ + waitHydration: false,
120
+ + // Do not wait for "load"; inspect the page as it streams in.
121
+ + waitUntil: 'commit',
122
+ + })
123
+ +
124
+ + // Cold load: the cache misses, so the fallback streams first, and the
125
+ + // generated value streams in once generation completes. The value is a
126
+ + // dynamic hole (real `expire: 0`), so it streams in after the shell.
127
+ + expect(
128
+ + await browser
129
+ + .elementByCss('#expire-zero-fallback', { waitUntil: false })
130
+ + .text()
131
+ + ).toBe('Loading...')
132
+ + const coldValue = await browser
133
+ + .elementByCss('#expire-zero', { waitUntil: false })
134
+ + .text()
135
+ + expect(coldValue).toBeDateString()
136
+ +
137
+ + // Warm reload: the dev minimum retention keeps the short-expire entry, so
138
+ + // the reload serves the previously cached value fast instead of
139
+ + // regenerating it. A background revalidation regenerates a fresh entry for
140
+ + // the next reload (asserted below). We wait for the streamed-in element
141
+ + // without waiting for "load", so no retry is needed.
142
+ + await browser.refresh({ waitUntil: 'commit' })
143
+ + expect(
144
+ + await browser.elementByCss('#expire-zero', { waitUntil: false }).text()
145
+ + ).toBe(coldValue)
146
+ +
147
+ + // That warm reload re-warmed a fresh entry in the background, so a later
148
+ + // reload converges to the new value. Read after "load" here (a plain
149
+ + // refresh) since we want the settled value, not the streaming inspection
150
+ + // above.
151
+ + await retry(async () => {
152
+ + await browser.refresh()
153
+ + expect(await browser.elementById('expire-zero').text()).not.toBe(
154
+ + coldValue
155
+ + )
156
+ + })
157
+ + })
158
+ +
159
+ // The following are smoke tests that Cache Components validation still
160
+ // surfaces errors for both cold-cache renders (validated via a separate
161
+ // warm-cache render) and warm-cache renders (validated via the streamed
162
+ 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
163
+ new file mode 100644
164
+ index 0000000000..e7d5b06820
165
+ --- /dev/null
166
+ +++ b/test/development/app-dir/use-cache-custom-handler-dev/app/expire-zero/page.tsx
167
+ @@ -0,0 +1,36 @@
168
+ +import { Suspense } from 'react'
169
+ +import { setTimeout } from 'timers/promises'
170
+ +import { cacheLife } from 'next/cache'
171
+ +
172
+ +// A public `'use cache'` routed through the custom (slow) handler, with an
173
+ +// explicit short `expire`. In dev the built-in front handler applies a minimum
174
+ +// retention, so a cache hit still resolves from the front in a microtask
175
+ +// instead of paying the backing's latency on every read.
176
+ +async function getCachedValue() {
177
+ + 'use cache'
178
+ + // `expire: 0` gives a short, dynamic (client-only) cache life, excluded from
179
+ + // static prerenders. Reusing it across client navigations would require
180
+ + // opting the route into runtime prefetching (`prefetch = 'allow-runtime'`) so
181
+ + // Cached Navigations embeds it into the client router cache; this fixture
182
+ + // doesn't, since the test only exercises the dev front handler serving it
183
+ + // warm on reloads.
184
+ + cacheLife({ expire: 0 })
185
+ + await setTimeout(1000)
186
+ + return new Date().toISOString()
187
+ +}
188
+ +
189
+ +async function CachedValue() {
190
+ + const value = await getCachedValue()
191
+ +
192
+ + return <p id="value">{value}</p>
193
+ +}
194
+ +
195
+ +export default function Page() {
196
+ + return (
197
+ + <main>
198
+ + <Suspense fallback={<p id="loading">Loading...</p>}>
199
+ + <CachedValue />
200
+ + </Suspense>
201
+ + </main>
202
+ + )
203
+ +}
204
+ 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
205
+ index f7a8508129..197060fa4a 100644
206
+ --- a/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts
207
+ +++ b/test/development/app-dir/use-cache-custom-handler-dev/use-cache-custom-handler-dev.test.ts
208
+ @@ -40,6 +40,38 @@ describe('use-cache-custom-handler-dev', () => {
209
+ expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(false)
210
+ })
211
+
212
+ + it('serves a short-expire value warm through a custom handler and re-warms it on each reload', async () => {
213
+ + const browser = await next.browser('/expire-zero', {
214
+ + waitHydration: false,
215
+ + // Do not wait for "load"; inspect the page as it streams in.
216
+ + waitUntil: 'commit',
217
+ + })
218
+ +
219
+ + // Cold load: the custom handler misses, the value generates and is written
220
+ + // through to both the backing handler and the dev-only in-memory front. We
221
+ + // wait for the streamed-in element without waiting for "load".
222
+ + const coldValue = await browser
223
+ + .elementByCss('#value', { waitUntil: false })
224
+ + .text()
225
+ + expect(coldValue).toBeDateString()
226
+ +
227
+ + // Warm reload: served fast from the front, whose minimum retention keeps
228
+ + // the short-`expire` entry. The custom handler's slow `get` isn't on the
229
+ + // critical path, and the short `expire` no longer evicts the front entry on
230
+ + // every read, so the same cached value shows.
231
+ + await browser.refresh({ waitUntil: 'commit' })
232
+ + expect(
233
+ + await browser.elementByCss('#value', { waitUntil: false }).text()
234
+ + ).toBe(coldValue)
235
+ +
236
+ + // Each warm reload re-executes the cache function and writes through to the
237
+ + // backing, so reloads converge to a fresh value.
238
+ + await retry(async () => {
239
+ + await browser.refresh()
240
+ + expect(await browser.elementById('value').text()).not.toBe(coldValue)
241
+ + })
242
+ + })
243
+ +
244
+ it('stops serving a front-cached entry after the backing cache is purged out-of-band', async () => {
245
+ const browser = await next.browser('/purged')
246
+
nextjs-cache-short-expire-dev/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ 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
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ 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
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ 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
59
+ 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
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ 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
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ 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
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ 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
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ 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
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-cna-tailwind-turbopack/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium && pnpm turbo run build --filter=next --filter=create-next-app --filter=eslint-config-next --log-order=stream && pnpm turbo run pack-for-isolated-tests --filter=next --filter=eslint-config-next --log-order=stream' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-cna-tailwind-turbopack/solution/gold.patch ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/create-next-app/templates/index.ts b/packages/create-next-app/templates/index.ts
2
+ index cd3221494140802f61b6ea0cdd8f8958b3a1b543..7810b69c707dfbe33a170dfaec06aaeefe614a23 100644
3
+ --- a/packages/create-next-app/templates/index.ts
4
+ +++ b/packages/create-next-app/templates/index.ts
5
+ @@ -72,7 +72,9 @@ export const installTemplate = async ({
6
+ const copySource = ["**"];
7
+ if (!eslint) copySource.push("!eslint.config.mjs");
8
+ if (!biome) copySource.push("!biome.json");
9
+ - if (!tailwind) copySource.push("!postcss.config.mjs");
10
+ + if (!tailwind || bundler === Bundler.Turbopack) {
11
+ + copySource.push("!postcss.config.mjs");
12
+ + }
13
+
14
+ await copy(copySource, root, {
15
+ parents: true,
16
+ @@ -109,6 +111,30 @@ export const installTemplate = async ({
17
+ );
18
+ }
19
+
20
+ + if (tailwind && bundler === Bundler.Turbopack) {
21
+ + const nextConfigFile = path.join(
22
+ + root,
23
+ + mode === "js" ? "next.config.mjs" : "next.config.ts",
24
+ + );
25
+ + let configContent = await fs.readFile(nextConfigFile, "utf8");
26
+ +
27
+ + configContent = configContent.replace(
28
+ + "/* config options here */\n",
29
+ + `/* config options here */
30
+ + turbopack: {
31
+ + rules: {
32
+ + "*.css": {
33
+ + loaders: ["@tailwindcss/turbopack"],
34
+ + as: "*.css",
35
+ + },
36
+ + },
37
+ + },
38
+ +`,
39
+ + );
40
+ +
41
+ + await fs.writeFile(nextConfigFile, configContent);
42
+ + }
43
+ +
44
+ if (reactCompiler) {
45
+ const nextConfigFile = path.join(
46
+ root,
47
+ @@ -278,9 +304,13 @@ export const installTemplate = async ({
48
+
49
+ /* Add Tailwind CSS dependencies. */
50
+ if (tailwind) {
51
+ + const tailwindPlugin =
52
+ + bundler === Bundler.Turbopack
53
+ + ? "@tailwindcss/turbopack"
54
+ + : "@tailwindcss/postcss";
55
+ packageJson.devDependencies = {
56
+ ...packageJson.devDependencies,
57
+ - "@tailwindcss/postcss": "^4",
58
+ + [tailwindPlugin]: "^4",
59
+ tailwindcss: "^4",
60
+ };
61
+ }
nextjs-cna-tailwind-turbopack/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-cna-tailwind-turbopack/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && 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 \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium && pnpm turbo run build --filter=next --filter=create-next-app --filter=eslint-config-next --log-order=stream && pnpm turbo run pack-for-isolated-tests --filter=next --filter=eslint-config-next --log-order=stream' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-cna-tailwind-turbopack/tests/test.patch ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/production/create-next-app/lib/specification.ts b/test/production/create-next-app/lib/specification.ts
2
+ index 20d75029..ed1f17ca 100644
3
+ --- a/test/production/create-next-app/lib/specification.ts
4
+ +++ b/test/production/create-next-app/lib/specification.ts
5
+ @@ -19,6 +19,12 @@ export type ProjectSpecification = {
6
+ }
7
+ }
8
+
9
+ +const tailwindFiles = process.env.NEXT_RSPACK ? ['postcss.config.mjs'] : []
10
+ +const tailwindDevDeps = [
11
+ + process.env.NEXT_RSPACK ? '@tailwindcss/postcss' : '@tailwindcss/turbopack',
12
+ + 'tailwindcss',
13
+ +]
14
+ +
15
+ /**
16
+ * Required files for a given project template and mode.
17
+ */
18
+ @@ -95,10 +101,10 @@ export const projectSpecification: ProjectSpecification = {
19
+ 'pages/_app.js',
20
+ 'pages/api/hello.js',
21
+ 'pages/index.js',
22
+ - 'postcss.config.mjs',
23
+ + ...tailwindFiles,
24
+ ],
25
+ deps: [],
26
+ - devDeps: ['@tailwindcss/postcss', 'tailwindcss'],
27
+ + devDeps: tailwindDevDeps,
28
+ },
29
+ ts: {
30
+ files: [
31
+ @@ -106,7 +112,7 @@ export const projectSpecification: ProjectSpecification = {
32
+ 'pages/_app.tsx',
33
+ 'pages/api/hello.ts',
34
+ 'pages/index.tsx',
35
+ - 'postcss.config.mjs',
36
+ + ...tailwindFiles,
37
+ 'tsconfig.json',
38
+ ],
39
+ deps: [],
40
+ @@ -114,8 +120,7 @@ export const projectSpecification: ProjectSpecification = {
41
+ '@types/node',
42
+ '@types/react-dom',
43
+ '@types/react',
44
+ - '@tailwindcss/postcss',
45
+ - 'tailwindcss',
46
+ + ...tailwindDevDeps,
47
+ 'typescript',
48
+ ],
49
+ },
50
+ @@ -126,17 +131,17 @@ export const projectSpecification: ProjectSpecification = {
51
+ 'jsconfig.json',
52
+ 'pages/_app.js',
53
+ 'pages/index.js',
54
+ - 'postcss.config.mjs',
55
+ + ...tailwindFiles,
56
+ ],
57
+ deps: [],
58
+ - devDeps: ['@tailwindcss/postcss', 'tailwindcss'],
59
+ + devDeps: tailwindDevDeps,
60
+ },
61
+ ts: {
62
+ files: [
63
+ 'next-env.d.ts',
64
+ 'pages/_app.tsx',
65
+ 'pages/index.tsx',
66
+ - 'postcss.config.mjs',
67
+ + ...tailwindFiles,
68
+ 'tsconfig.json',
69
+ ],
70
+ deps: [],
71
+ @@ -144,8 +149,7 @@ export const projectSpecification: ProjectSpecification = {
72
+ '@types/node',
73
+ '@types/react-dom',
74
+ '@types/react',
75
+ - '@tailwindcss/postcss',
76
+ - 'tailwindcss',
77
+ + ...tailwindDevDeps,
78
+ 'typescript',
79
+ ],
80
+ },
81
+ @@ -214,12 +218,12 @@ export const projectSpecification: ProjectSpecification = {
82
+ 'app-tw': {
83
+ js: {
84
+ deps: [],
85
+ - devDeps: ['@tailwindcss/postcss', 'tailwindcss'],
86
+ + devDeps: tailwindDevDeps,
87
+ files: [
88
+ 'app/layout.js',
89
+ 'app/page.js',
90
+ 'jsconfig.json',
91
+ - 'postcss.config.mjs',
92
+ + ...tailwindFiles,
93
+ ],
94
+ },
95
+ ts: {
96
+ @@ -228,15 +232,14 @@ export const projectSpecification: ProjectSpecification = {
97
+ '@types/node',
98
+ '@types/react-dom',
99
+ '@types/react',
100
+ - '@tailwindcss/postcss',
101
+ - 'tailwindcss',
102
+ + ...tailwindDevDeps,
103
+ 'typescript',
104
+ ],
105
+ files: [
106
+ 'app/layout.tsx',
107
+ 'app/page.tsx',
108
+ 'next-env.d.ts',
109
+ - 'postcss.config.mjs',
110
+ + ...tailwindFiles,
111
+ 'tsconfig.json',
112
+ ],
113
+ },
114
+ @@ -244,12 +247,12 @@ export const projectSpecification: ProjectSpecification = {
115
+ 'app-tw-empty': {
116
+ js: {
117
+ deps: [],
118
+ - devDeps: ['@tailwindcss/postcss', 'tailwindcss'],
119
+ + devDeps: tailwindDevDeps,
120
+ files: [
121
+ 'app/layout.js',
122
+ 'app/page.js',
123
+ 'jsconfig.json',
124
+ - 'postcss.config.mjs',
125
+ + ...tailwindFiles,
126
+ ],
127
+ },
128
+ ts: {
129
+ @@ -258,15 +261,14 @@ export const projectSpecification: ProjectSpecification = {
130
+ '@types/node',
131
+ '@types/react-dom',
132
+ '@types/react',
133
+ - '@tailwindcss/postcss',
134
+ - 'tailwindcss',
135
+ + ...tailwindDevDeps,
136
+ 'typescript',
137
+ ],
138
+ files: [
139
+ 'app/layout.tsx',
140
+ 'app/page.tsx',
141
+ 'next-env.d.ts',
142
+ - 'postcss.config.mjs',
143
+ + ...tailwindFiles,
144
+ 'tsconfig.json',
145
+ ],
146
+ },
147
+ diff --git a/test/production/create-next-app/lib/utils.ts b/test/production/create-next-app/lib/utils.ts
148
+ index 4787efbc..9e0da8d2 100644
149
+ --- a/test/production/create-next-app/lib/utils.ts
150
+ +++ b/test/production/create-next-app/lib/utils.ts
151
+ @@ -143,18 +143,21 @@ export const shouldBeTemplateProject = ({
152
+ mode,
153
+ srcDir,
154
+ }: CustomTemplateOptions) => {
155
+ + const isTailwindTemplate = [
156
+ + 'app-tw',
157
+ + 'app-tw-empty',
158
+ + 'default-tw',
159
+ + 'default-tw-empty',
160
+ + ].includes(template)
161
+ +
162
+ projectFilesShouldExist({
163
+ cwd,
164
+ projectName,
165
+ files: getProjectSetting({ template, mode, setting: 'files', srcDir }),
166
+ })
167
+
168
+ - // Tailwind templates share the same files (tailwind.config.mjs, postcss.config.mjs)
169
+ - if (
170
+ - !['app-tw', 'app-tw-empty', 'default-tw', 'default-tw-empty'].includes(
171
+ - template
172
+ - )
173
+ - ) {
174
+ + // Tailwind templates share the same files across JavaScript and TypeScript.
175
+ + if (!isTailwindTemplate) {
176
+ projectFilesShouldNotExist({
177
+ cwd,
178
+ projectName,
179
+ @@ -165,6 +168,14 @@ export const shouldBeTemplateProject = ({
180
+ })
181
+ }
182
+
183
+ + if (isTailwindTemplate && !process.env.NEXT_RSPACK) {
184
+ + projectFilesShouldNotExist({
185
+ + cwd,
186
+ + projectName,
187
+ + files: ['postcss.config.mjs'],
188
+ + })
189
+ + }
190
+ +
191
+ projectDepsShouldBe({
192
+ type: 'dependencies',
193
+ cwd,
194
+ diff --git a/test/production/create-next-app/templates/app.test.ts b/test/production/create-next-app/templates/app.test.ts
195
+ index f52d05fa..9593db13 100644
196
+ --- a/test/production/create-next-app/templates/app.test.ts
197
+ +++ b/test/production/create-next-app/templates/app.test.ts
198
+ @@ -1,4 +1,7 @@
199
+ +import { readFileSync } from 'fs'
200
+ +import { join } from 'path'
201
+ import {
202
+ + projectFilesShouldExist,
203
+ projectShouldHaveNoGitChanges,
204
+ resolveNextTgzFilename,
205
+ shouldBeTemplateProject,
206
+ @@ -145,7 +148,49 @@ describe('create-next-app --app (App Router)', () => {
207
+ await tryNextDev({
208
+ cwd,
209
+ projectName,
210
+ + tailwind: true,
211
+ })
212
+ +
213
+ + // The non-Turbopack path must keep its PostCSS integration.
214
+ + if (!process.env.NEXT_RSPACK) {
215
+ + const rspackProjectName = 'app-tw-rspack'
216
+ + const rspackResult = await run(
217
+ + [
218
+ + rspackProjectName,
219
+ + '--ts',
220
+ + '--app',
221
+ + '--tailwind',
222
+ + '--rspack',
223
+ + '--skip-install',
224
+ + '--no-eslint',
225
+ + '--no-biome',
226
+ + '--no-src-dir',
227
+ + '--no-import-alias',
228
+ + '--no-react-compiler',
229
+ + '--no-agents-md',
230
+ + ],
231
+ + nextTgzFilename,
232
+ + { cwd }
233
+ + )
234
+ +
235
+ + expect(rspackResult.exitCode).toBe(0)
236
+ + projectFilesShouldExist({
237
+ + cwd,
238
+ + projectName: rspackProjectName,
239
+ + files: ['postcss.config.mjs'],
240
+ + })
241
+ + const rspackRoot = join(cwd, rspackProjectName)
242
+ + const rspackPackage = JSON.parse(
243
+ + readFileSync(join(rspackRoot, 'package.json'), 'utf8')
244
+ + )
245
+ + expect(rspackPackage.devDependencies).toHaveProperty(
246
+ + '@tailwindcss/postcss'
247
+ + )
248
+ + expect(rspackPackage.devDependencies).toHaveProperty('tailwindcss')
249
+ + expect(rspackPackage.devDependencies).not.toHaveProperty(
250
+ + '@tailwindcss/turbopack'
251
+ + )
252
+ + }
253
+ })
254
+ })
255
+
256
+ diff --git a/test/production/create-next-app/utils.ts b/test/production/create-next-app/utils.ts
257
+ index 73a46770..39411d8a 100644
258
+ --- a/test/production/create-next-app/utils.ts
259
+ +++ b/test/production/create-next-app/utils.ts
260
+ @@ -2,6 +2,7 @@ import execa from 'execa'
261
+ import { join } from 'path'
262
+ import { spawn } from 'child_process'
263
+ import { fetchViaHTTP, findPort, killApp } from 'next-test-utils'
264
+ +import webdriver from 'next-webdriver'
265
+ import {
266
+ resolveTestPkgPaths,
267
+ serializeTestPkgPathsEnv,
268
+ @@ -9,6 +10,15 @@ import {
269
+
270
+ export const CNA_PATH = require.resolve('create-next-app/dist/index.js')
271
+
272
+ +// Run create-next-app from TypeScript source so the test exercises the current
273
+ +// checkout. The verifier applies candidate changes after its build fixtures are
274
+ +// prepared, so invoking dist/index.js here would test a stale pre-patch bundle.
275
+ +const CNA_SOURCE_PATH = join(
276
+ + __dirname,
277
+ + '../../../packages/create-next-app/index.ts'
278
+ +)
279
+ +const TSX_CLI_PATH = require.resolve('tsx/cli')
280
+ +
281
+ /**
282
+ * Resolves the path to the packed `next` tarball. Uses NEXT_TEST_PKG_PATHS
283
+ * when available (set by run-tests.js), otherwise finds packed.tgz files
284
+ @@ -49,7 +59,7 @@ export const run = async (
285
+ env?: Record<string, string>
286
+ }
287
+ ) => {
288
+ - return execa('node', [CNA_PATH].concat(args), {
289
+ + return execa('node', [TSX_CLI_PATH, CNA_SOURCE_PATH].concat(args), {
290
+ // tests with options.reject false are expected to exit(1) so don't inherit
291
+ stdio: options.reject === false ? 'pipe' : 'inherit',
292
+ ...options,
293
+ @@ -84,12 +94,14 @@ export async function tryNextDev({
294
+ isApp = true,
295
+ isApi = false,
296
+ isEmpty = false,
297
+ + tailwind = false,
298
+ }: {
299
+ cwd: string
300
+ projectName: string
301
+ isApp?: boolean
302
+ isApi?: boolean
303
+ isEmpty?: boolean
304
+ + tailwind?: boolean
305
+ }) {
306
+ // The caller wraps this in `useTempDir`, so `cwd` (and the CNA project
307
+ // inside it) is already an isolated temp directory that gets removed
308
+ @@ -129,6 +141,8 @@ export async function tryNextDev({
309
+ // headroom so these tests aren't flaky on loaded CI machines.
310
+ const startServerTimeout = 60_000
311
+
312
+ + let browser: Awaited<ReturnType<typeof webdriver>> | undefined
313
+ +
314
+ try {
315
+ await new Promise<void>((resolve, reject) => {
316
+ const onTimeout = setTimeout(() => {
317
+ @@ -164,6 +178,17 @@ export async function tryNextDev({
318
+ })
319
+ })
320
+
321
+ + // The webpack test matrix forces generated apps to build with webpack,
322
+ + // but create-next-app only exposes Turbopack and Rspack as bundler choices.
323
+ + // Only assert rendered Tailwind styles when the generated bundler matches
324
+ + // the test bundler.
325
+ + if (tailwind && !process.env.IS_WEBPACK_TEST) {
326
+ + browser = await webdriver(port, '/')
327
+ + expect(await browser.elementByCss('main').getComputedCss('display')).toBe(
328
+ + 'flex'
329
+ + )
330
+ + }
331
+ +
332
+ const res = await fetchViaHTTP(port, '/')
333
+ if (isEmpty || isApi) {
334
+ expect(await res.text()).toContain('Hello world!')
335
+ @@ -190,6 +215,7 @@ export async function tryNextDev({
336
+ expect(apiRes.status).toBe(200)
337
+ }
338
+ } finally {
339
+ + await browser?.close()
340
+ await killApp(server).catch(() => {})
341
+ }
342
+ }