- 20 Oct, 2026 26 commits
-
-
next-js-bot[bot] authored
-
Sebastian "Sebbie" Silbermann authored
Moves access to Next.js bot behind GitHub environments to ensure the bot only runs code that has been reviewed by at least two people with write access. New GitHub environments: - `bot-autonomous` - `bot-approved` ## Testing - Verified all 6 remaining key consumers on canary are covered (`git grep RELEASE_GITHUB_APP_PRIVATE_KEY` only finds the environment-backed mint steps). - After settings land: dispatch canary with `force=false` right after a release (exits early but exercises env + mint), and dispatch stable with `dryRun=true` to watch the `bot-approved` approval gate trigger with no side effects. - The nightly canary is the real soak test for `bot-autonomous`. Backports: #100123 (`releases/lts/active`), #100124 (`releases/lts/maintenance`) --------- Co-authored-by:Claude Code <noreply@anthropic.com>
-
Tobias Koppers authored
## Summary This retries `vercel deploy` when it fails with a transient network error before the CLI reports a deployment. It is the third of three stacked PRs. **Why.** On v16.5.0-canary.6 attempt 1 ([example](https://github.com/vercel/next.js/actions/runs/37957356976/job/113914293394)), `vercel deploy` printed `Error: fetch failed` and no deployment URL. The harness failed straight away; the cause it reported was a misleading `Invalid URL`. **When it retries.** All of these must hold: - `vercel deploy` exits non-zero; - stdout isn't a URL, and the output (with ANSI codes stripped) has no `Inspect`/`Preview`/`Production` URL line; - the output has a CLI `Error:` line with a network failure: `fetch failed`, `ECONNRESET`, `ETIMEDOUT`, `EAI_AGAIN`, `ECONNREFUSED`, `UND_ERR_SOCKET`, `UND_ERR_CONNECT_TIMEOUT` or `socket hang up`; - the output doesn't contain an auth or build diagnostic (`Unauthorized`, `Forbidden`, `Build failed`, `Command "…" exited`, …). **Limits.** - At most 3 attempts in total, waiting 5 s and then 10 s between them. - It only retries while at least 60 s of the setup budget would remain after the wait. - Every other failure goes through the existing `throwDeploymentError` path unchanged, with no extra deploy. **Accepted risk.** If the connection drops after Vercel accepted the upload, a retry can leave an orphaned preview deployment (the harness deploys with `--force`). That's at most 2 extra previews per suite start in the test project. The retry log line says so and includes the CLI output. This PR also fixes a typo in a comment in `test/e2e/app-dir/resume-data-cache/resume-data-cache.test.ts`. That change is there so `Test new and changed tests when deployed` runs a deploy-mode suite against the full stack. ## Verification - `pnpm jest test/unit/next-deploy-failure`: 43/43 pass. - **Retries:** retry-then-succeed, giving up after 3 calls, and skipping the retry when too little budget is left. - **No retry (exactly one deploy):** auth error, build failure, a network error after a URL or an `Inspect` line (including ANSI-colored output), a build diagnostic that mentions `fetch failed`, and `Unauthorized` next to `fetch failed`. - prettier, eslint and `pnpm typescript` are clean. - Not run: a real Vercel deployment (the sandbox has no test credentials). <!-- NEXT_JS_LLM --> <!-- fleet b78d4bc5-dee1-4d80-b647-54229882f21f --> --------- Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Tobias Koppers authored
### What? Tasks that become dirty together are handed to the turbo-tasks scheduler (`PriorityRunner`) as one batch instead of one by one, at two sites: - `invalidate()` (explicit invalidation of a set of tasks) - `invalidate_cell_dependents()` in `update_cell` (all dependents of a changed cell — the main fan-out path) Also adds a `cell_fan_out` criterion benchmark to `turbo-tasks-backend`. ### Why? `PriorityRunner` keeps all non-lowest-priority work in a `Mutex<BinaryHeap>`. Scheduling N tasks one by one locks that heap up to N times and grows it incrementally, contending with the workers that pop from it. This is a first step towards reducing that contention. Note: in-tree, `invalidate()` is currently only reached with a single task (`TurboTasks::invalidate` → `Backend::invalidate_task`); `invalidate_tasks` / `invalidate_tasks_set` have no in-tree callers. The real fan-out is a cell change invalidating its dependents, which is why `update_cell` is batched too. ### How? - **`PriorityRunner::schedule_many`**: behaves like calling `schedule` for each item. While there is free worker capacity, items are handed directly to new workers using the same slot reservation as `schedule`. The remaining items are queued in bulk: each item is still inserted into the claimable map before its key is published, lowest-priority keys still go to the lock-free queue, and all other keys are staged and then pushed into the heap under a single lock acquisition after one `reserve`. The staging buffer is only allocated when a batch actually contains heap items. Each claimable insert finishes before the heap is locked, preserving the existing heap → claimable lock order. - The liveness protocol is unchanged: after the bulk push there is one `SeqCst` fence followed by an `active_workers` re-check. If capacity opened up concurrently, workers are spawned for queued work as long as capacity remains. Items replaced by a newer item with the same claim key are still passed to `Executor::discard`. - **`TurboTasks::schedule_many`**: batch counterpart of `TurboTasks::schedule`; begins all foreground jobs and updates the scheduled-task counter up front; no-op for an empty batch. - **Backend**: the dirty-marking logic was split into `make_task_dirty_without_scheduling`, which returns the parent priority instead of scheduling. `invalidate()` and `invalidate_cell_dependents()` compute each task's scheduling priority while holding its guard, collect into a pre-reserved buffer, and schedule once after all tasks are marked dirty. In `update_cell` the existing order (remove old content → dirty dependents → set new content → notify waiters → run aggregation updates) is preserved; only the scheduling is deferred to the end of the dirtying loop. `make_task_dirty_internal` keeps scheduling immediately for its other callers (aggregation update, connect child(ren)). New `priority_runner` unit tests cover mixed priority bands, interleaving with `schedule`, empty batches, claiming batched items, duplicate claim keys, a multi-worker run where every item executes exactly once, and diagnostics counting. ### Benchmark `cargo bench -p turbo-tasks-backend --bench mod -- cell_fan_out` Graph: a `State` → one `source` task producing a cell → N `dependent` tasks reading that cell → a root summing them. The graph is built once (untimed); each timed iteration changes the state and does a strongly consistent read of the root, i.e. invalidation fan-out + scheduling + re-execution of all N dependents. The result is asserted every iteration. A/B on one 8-vCPU x86_64 Linux VM (Intel Xeon @ 2.50 GHz), release build, in-memory backend. Base is the parent commit of this PR with the same benchmark file added; six alternating base/branch process runs, values are criterion's central time estimate per run (ms): | N | base (6 runs) | branch (6 runs) | median base → branch | paired change (approx. 95% CI) | |---|---|---|---|---| | 1,000 | 6.45, 6.14, 5.96, 6.54, 5.69, 6.57 | 7.12, 7.15, 5.53, 5.77, 6.06, 5.29 | 6.29 → 5.91 | −1.7% [−15.5%, +14.4%] | | 10,000 | 73.49, 75.38, 89.11, 72.21, 69.77, 65.11 | 68.38, 76.65, 64.04, 75.06, 66.85, 68.76 | 72.85 → 68.57 | −5.4% [−18.6%, +9.9%] | | 100,000 | 864.7, 1011.5, 953.4, 883.8, 856.5, 814.3 | 848.5, 915.0, 791.9, 876.6, 928.1, 848.1 | 874.3 → 862.6 | −3.2% [−12.5%, +7.2%] | **No detected end-to-end difference**: the branch tends to be slightly faster, but every interval overlaps zero and run-to-run noise (~5–10%) is larger than the effect. Re-executing the N dependents (~8–9 µs per task here) dominates each iteration, so the scheduler's heap lock is a small share of the measured time. The intervals only reflect repeated processes on one VM (not independent machines), and runs were always base-first. The reduced number of heap lock acquisitions follows from the code structure; it is not separately instrumented. The benchmark is kept so later steps (batching more scheduling sites, reducing heap contention further) can be measured against it. ### Verification - `cargo test -p turbo-tasks --lib priority_runner` (also with `--features inline_execution_stats`) - `cargo test -p turbo-tasks-backend` - `cargo clippy -p turbo-tasks -p turbo-tasks-backend --all-targets -- -D warnings` <!-- NEXT_JS_LLM --> <!-- fleet d21ddb86-de88-41df-82c7-aa6a29a6165e --> --------- Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
next-js-bot[bot] authored
[diff facebook/react@ba39b32a...a6792708](https://github.com/facebook/react/compare/ba39b32a...a6792708) <details> <summary>React upstream changes</summary> - https://github.com/facebook/react/pull/37901 - https://github.com/facebook/react/pull/37876 </details> --------- Co-authored-by:
next-js-bot[bot] <279046576+next-js-bot[bot]@users.noreply.github.com>
-
Tobias Koppers authored
## Summary `compute_merged_modules` propagates merge-group bitmaps with a fixed-point traversal prioritized by negated BFS depth. This PR switches it to the reverse-postorder rank from #100428 (stacked on #100429): - its own BFS depth pass is removed; - a module is visited only after all of its importers (except across cycles). Merge-group bitmap indices can be assigned in a different order. Only bitmap equality is used, so the merged-module result is unchanged. ### Benchmarks **Setup:** - Same as the PRs below: Turbopack `next build --experimental-build-mode compile`. - `next-swc` release builds (LTO disabled, 16 codegen units). - Binaries interleaved per run, 3 runs each, clean `.next`. - Time is the depth or rank pass plus the fixed-point traversal, measured with local-only instrumentation. Values are medians with min–max ranges. | app | before (PR below) | after | |---|---|---| | generated app router app (300 routes, ~12k modules) | 74.7 ms (72.1–76.8), 78,211 visits | **11.8 ms** (10.1–12.0), 12,260 visits | | `bench/nested-deps-app-router-many-pages` (~31k modules) | 97.9 ms (95.6–108.7), 33,900 visits | 114.4 ms (113.7–142.2), 33,799 visits | On many-pages there are almost no re-visits to remove. The small regression has the same cause as the one explained in #100428: bitmap operations against final, full-size bitmaps are more expensive. ## Verification - `cargo test -p turbopack-core --lib` - `cargo test -p turbopack-tests --test snapshot`: passes with no snapshot changes. - `cargo test -p turbopack-tests --test execution`: all 317 tests pass. <!-- NEXT_JS_LLM --> <!-- fleet b56269ed-2145-4f30-b0fe-dc9762520521 --> Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Tobias Koppers authored
## Summary `collect_graph` computes per-module entry membership with the same fixed-point traversal and BFS-depth priority as `compute_chunk_group_info`. This PR switches it to the reverse-postorder rank added in the PR below. That removes its own BFS depth pass, and a module is now visited only after all of its importers (except across cycles). `TraversalPriority` has no remaining users, so it is removed. Stacked on #100428, which introduces `ModuleGraphSnapshot::reverse_postorder_ranks`. ### Benchmarks **Setup:** - Same as the PR below: Turbopack `next build --experimental-build-mode compile`. - `next-swc` release builds (LTO disabled, 16 codegen units). - Binaries interleaved per run, 3 runs each, clean `.next`. - Time is the depth or rank pass plus the fixed-point traversal, measured with local-only instrumentation. Values are medians with min–max ranges. - "Before" is the PR below, which already includes its entry deduplication. | app | before | after | |---|---|---| | generated app router app (300 routes, ~12k modules) | 14.5 ms (14.4–16.5), 12,030 visits | **9.5 ms** (8.3–11.0), 11,938 visits | | `bench/nested-deps-app-router-many-pages` (~31k modules) | 422 ms (417–426), 30,869 visits | **197 ms** (193–205), 30,777 visits | For reference, `collect_graph` on many-pages takes 534 ms (496–546) on canary. ## Verification - `cargo test -p turbopack-core --lib` - `cargo test -p turbopack-tests --test snapshot`: passes with no snapshot changes. - `cargo test -p turbopack-tests --test execution -- collect` (emit/collect execution tests). <!-- NEXT_JS_LLM --> <!-- fleet b56269ed-2145-4f30-b0fe-dc9762520521 --> Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Tobias Koppers authored
## Summary `compute_chunk_group_info` runs a fixed-point traversal over the module graph, ordered by BFS (minimum) depth. A module can gain new chunk groups after it was already visited, for example through a longer path from another entry or from a chunk group that is created later. When that happens, it is queued again and its whole subgraph is propagated again. On app-shaped graphs this means many visits per module. This PR adds `ModuleGraphSnapshot::reverse_postorder_ranks`. It ranks every module by the reverse postorder of a DFS from the entries, using an iterative DFS that resolves `VisitedModule` aliases to the canonical node. Using `Reverse(rank)` as the priority visits a module only after all of its importers, except across cycles. On a DAG, each module is therefore visited exactly once. `compute_chunk_group_info` now uses this rank instead of its own BFS depth pass. `traverse_edges_fixed_point_with_priority` also now tracks initial entries in `queue_set`: - an entry reachable from another entry is no longer queued twice; - duplicate entries are ignored. This is the first PR of a stack. `collect_graph` (#100429) and `compute_merged_modules` (#100430) follow in separate PRs. ### Benchmarks **Setup:** - `next build --experimental-build-mode compile` with Turbopack. - `next-swc` release builds (LTO disabled and 16 codegen units, to keep the native builds feasible). - Binaries interleaved per run, 3 runs each, `.next` removed before each run. - Time is the BFS depth pass or RPO rank pass plus the fixed-point traversal, measured with local-only instrumentation that isn't part of this PR. Values are medians with min–max ranges. | app | before (canary) | after | |---|---|---| | generated app router app: 300 routes in route groups, a shared UI library reached at different depths, `'use client'` boundaries, `next/dynamic` deep in routes (~12k modules) | 601 ms (545–609), 207,399 visits | **21 ms** (21–21), 12,240 visits | | `bench/nested-deps-app-router-many-pages` (~31k modules) | 292 ms (270–301), 50,921 visits | 407 ms (394–414), 33,779 visits | Overall `next build` wall time, as context only: - generated app: 12.4 → 11.8 s; - many-pages: 40.5 → 39.4 s. **Why many-pages gets slower despite fewer visits.** That app has few re-visits to remove, and RPO makes each bitmap operation more expensive: - Hub modules such as `react/jsx-runtime` have thousands of importers. - With RPO, a hub is visited after all of its importers. It accumulates bits one importer at a time, so its bitmap stays a Roaring *array* container (≤ 4096 ids) for most of those checks. - Each importer edge compares the hub's bitmap against the importer's final, full-size bitmap. That makes it an array/array merge, `O(|parent| + |child|)`. - Under BFS, hubs fill up early and become *bitset* containers, and many checks ran against still-small parent bitmaps. Measured `is_subset` cost in the inherit branch (many-pages): | | BFS | RPO | |---|---|---| | array/array checks | 99.6k checks, 108 ms | 114.8k checks, 268 ms | | array/bitset checks | 41.4k checks, 52 ms | ~0 | The trade-off is accepted: the gain on graphs with many re-visits is much larger than this regression. ## Verification - New unit tests in `module_graph/mod.rs`: - `reverse_postorder_ranks` on: - a diamond with paths of different lengths, which also checks that the fixed point visits each module exactly once; - a cycle; - multiple, overlapping and duplicate entries; - a layered graph with a `VisitedModule` alias. - Entry deduplication in the fixed-point traversal. This test fails without the fix. - A `compute_chunk_group_info` semantics test covering two entries with heuristics, an unequal-path diamond, an `Async` edge and a merged `Isolated` edge. It asserts: - per-module chunk-group membership; - merged-group entries; - clusters and priority routes. It passes with both the old and the new order. - `cargo test -p turbopack-core --lib` - `cargo test -p turbopack-tests --test snapshot`: passes with no snapshot changes. - `cargo test -p turbopack-tests --test execution` (run on the top of the stack). <!-- NEXT_JS_LLM --> <!-- fleet b56269ed-2145-4f30-b0fe-dc9762520521 --> --------- Co-authored-by:vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Tobias Koppers authored
### What? Namespace provenance from a late partial-namespace read now reaches the module's passthrough targets, even when that module was already processed with `All` usage or with the same names. ### Why? `compute_binding_usage_info` tracks modules read through a namespace value (`namespace_object_may_escape`). Export-name mangling uses this to keep original names. Passthrough edges such as `export * from './y'` forward that provenance to their target. Take a module that was reached first through a plain named or `All` edge, so its passthrough edge has already run. If a partial-namespace edge for it arrives later and adds no new export names, the module joins the provenance set but the visitor reports no change. It is never revisited, so its passthrough target stays out of the set. ### How? Direct partial-namespace edges now count adding the target to the provenance set as a change, the same way the passthrough branch already does. The export-usage merge still always runs. Each module can only be added to the set once, so this triggers at most one extra revisit per module and the fixed point still terminates. New `turbopack-core` graph tests build a small module graph with explicit edge usages and check the result directly. In the graph, `x` re-exports `y` through a passthrough edge, and `x` is reached by both a short path and a longer path. The tests cover: - the plain usage of `x` being `All` or an already-used name - the namespace read arriving on the longer path (the failing case) or on the shorter path (a control) Without this fix, the two late cases mark `x` but leave `y` out of the provenance set; all four pass with it. The new execution test `turbopack/exports/mangle-late-namespace-passthrough` reproduces the bug with real module analysis and codegen. A barrel (`export * from './source'`) is reached early by named imports from the entry, and later by a narrowed dynamic import (`webpackExports`) that sits a few modules deeper and uses no new names. The test disables `followReexports` so the named imports target the barrel instead of resolving straight to the source. It also disables `mangleViaMaterializedNamespaceObject` so the dynamic import reads the barrel itself, not a namespace facade. Without the fix, the source export is wrongly marked mangleable (`canMangle: true`). The values still read correctly in this fixture, so the test checks the mangling decision through `__webpack_exports_info__`. ### Verification - `cargo test -p turbopack-core --lib` - `cargo test -p turbopack-tests --test snapshot` (no snapshot changes) - `cargo test -p turbopack-tests --test execution`, including the new test, which fails without the fix - `cargo clippy -p turbopack-core --tests` <!-- NEXT_JS_LLM --> <!-- fleet c860b76b-981c-4d9b-a802-f28b0545c8a7 --> --------- Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com> Co-authored-by:
Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
-
Tobias Koppers authored
### What? Moves the unused reference edges of `BindingUsageInfo` into their own keyed Turbo Tasks value, `UnusedReferenceEdges`. `ModuleGraphSnapshot` now holds only those edges, not the full binding usage info. ### Why? `ModuleGraphSnapshot` needs binding usage info for one thing: deciding which graph edges to skip during traversal. Because the edge set was stored inline in `BindingUsageInfo`, graph snapshots depended on all of the binding usage info. Any change to the edges also changed `BindingUsageInfo` itself, which invalidated readers that only needed the other data (export usage, circuit breakers, partial-namespace modules). ### How? - `BindingUsageInfo` stores the unused edges as a `ResolvedVc` to the new `cell = "keyed"` transparent set and exposes it via `unused_references_edges()`. - `ModuleGraph` and `ModuleGraphLayer` read only that value into their snapshots. The removed `is_reference_unused_edge` helper is replaced by keyed `contains_key` checks on the edge set at the traversal sites. - Traversals are synchronous, so the snapshot holds a `ReadRef` of the edge set. Traversal behavior is unchanged: the same edges are skipped and the double-analysis guard still fires. ### Verification - `cargo check -p turbopack-core -p turbopack-cli` - `cargo check -p next-core -p next-api` - `cargo clippy -p turbopack-core -p turbopack-cli --all-targets` - `cargo test -p turbopack-core --lib` <!-- NEXT_JS_LLM --> <!-- fleet d3110e27-fbc9-4c1b-bdb7-95e62510e2d2 --> Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Tobias Koppers authored
### What? Adds two bullets to the "Writing Tests" section of `AGENTS.md`: - For Next.js features, prefer e2e tests (`test/e2e/`, `test/development/`, `test/production/`). For Turbopack features, prefer execution tests (`turbopack/crates/turbopack-tests/tests/execution/`). - Avoid unit tests that map directly to the implementation; complicated algorithms are the exception. Agents may write unit tests temporarily to check their work, but should not commit them or add them to the PR unless they are necessary. ### Why? Agents often add unit tests that mirror the implementation. These tests add maintenance cost and catch few real regressions. Integration-level tests cover behavior through the real entry points. ### How? The guidance goes into the existing "Test writing expectations" list, where agents already read test conventions. It names concrete directories so it is easy to act on. ### Verification - `prettier --check AGENTS.md` passes. <!-- NEXT_JS_LLM --> <!-- fleet 49585d67-9c38-49d9-bde0-810ba197f96e --> Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Aryan Sachin authored
### What? Documents that `router.push()` and `router.replace()` in the App Router (`next/navigation`) return `void` instead of a `Promise`, and provides migration guidance and code examples showing how to use React's `useTransition` to track pending navigation state. ### Why? In the Pages Router (`next/router`), `router.push()` and `router.replace()` returned a `Promise<boolean>` that developers could `await` to execute code after a route change. In the App Router, navigations are non-blocking transitions integrated with React's transition system and return `void`. This breaking difference was not documented in the `useRouter` API reference or the App Router migration guide, leading to confusion when migrating existing codebases. ### How? - Updated `docs/01-app/03-api-reference/04-functions/use-router.mdx`: - Added callout notes to `router.push()` and `router.replace()` explaining the `void` return type and referencing `useTransition`. - Added a migration bullet point under "Migrating from `next/router`". - Added an example demonstrating how to track pending navigation state with React's `useTransition` (`startTransition` / `isPending`). - Updated `docs/01-app/02-guides/migrating/app-router-migration.mdx`: - Added migration notes and dual-language (TSX/JSX) switcher examples under Step 5 ("Migrating Routing Hooks") explaining how to migrate from `await router.push(...)` using `useTransition`. Closes #61737 -
Devesh Asawa authored
### What? - Fixes the parameter type in the `proxy.ts` rewrite and redirect examples in `docs/01-app/02-guides/backend-for-frontend.mdx` from `Request` to `NextRequest`. - Fixes the parameter type in the "Prefetching links in Proxy" example in `docs/01-app/03-api-reference/02-components/link.mdx` from `Request` to `NextRequest`. - Fixes a logic bug in the same `link.mdx` example where cookies were read using `request.cookies.authToken` instead of `request.cookies.has('authToken')`. ### Why? - `request.nextUrl` only exists on `NextRequest`, not the standard Web `Request`. In TypeScript, using `request: Request` results in type errors such as `Property 'nextUrl' does not exist on type 'Request'` (6 errors across the three examples). - `request.cookies` is a `RequestCookies` map, so property access `request.cookies.authToken` is always `undefined`. The correct API is `request.cookies.has('authToken')`. In the previous example, even requests with the cookie were incorrectly routed to the public dashboard. ### How? - Added `import type { NextRequest } from 'next/server'` and typed `request: NextRequest` in the TypeScript code snippets. - Updated both TS and JS code snippets in `link.mdx` to use `request.cookies.has('authToken')`. - Tested in production mode with Turbopack on Windows: - TypeScript build check: the 6 type errors are resolved and the check passes. - `/dashboard` without cookie: routes to public dashboard. - `/dashboard` with `authToken` cookie: now correctly routes to authenticated dashboard (previously failed and routed to public). --------- Co-authored-by:Joseph <sephxd1234@gmail.com>
-
Luke Sandberg authored
-
Janka Uryga authored
the ISR fallback tests were written in a way that only worked if the first retry yielded a concrete prerender. this is enough in `next start`, but in deploy, the ISR fallback retry does not always succeed in one attempt. this PR adjusts the `act()` assertions to support multiple retry attempts. this is not easy to express using usual `act()` patterns, so we try the assertion, and retry it if it threw an error that indicates that an expected response didn't show up (other errors are rethrown)
-
Joseph authored
## Summary The Testing section of the Preserving UI state guide said Playwright `getByLabel` and `getByPlaceholder` filter by visibility. They do not: with Activity keeping a hidden page in the DOM, both locators match the hidden copy and `.fill()` fails with a strict mode violation. Only `getByRole` excludes hidden elements by default. - Lead with the tool-agnostic rule: query the accessibility tree, or filter matches by visibility before acting - Keep `getByRole` as the default Playwright example - Move `getByLabel` / `getByPlaceholder` into the explicit `.filter({ visible: true })` examples - Note that waiting for visibility does not narrow a query that matches multiple elements - Drop the Cypress example, which mixed a visibility assertion with a non-existent `cy.get()` option, and point readers to their testing tool's locator and helper docs, since this behavior varies between tools and versions ## Verification - Playwright 1.61 against a visible form plus a `display: none` copy: `getByLabel` matched 3, `getByPlaceholder` matched 2 (both strict mode violations on `.fill()`); `getByRole` and the `.filter({ visible: true })` variants each matched 1 <!-- NEXT_JS_LLM --> -
Jan Kassens authored
## Summary Continue decoupling App Router rendering from HTTP request objects by passing request headers explicitly from the Node and Edge adapters into request-store construction. The store retains the original headers object and its lazy header/cookie views, middleware cookie precedence, and cookie update callback behavior. Adds a scoped lint guard against reading `req.headers` in `app-render.tsx` and regression coverage for middleware cookies overriding incoming cookies on both Node and Edge. Internal render/store signatures change; supported public APIs are unchanged. ## Verification 173 test executions passed: - Middleware, live header views, draft mode, and cache-components cookies in `test-dev-turbo` and `test-start-turbo`; middleware, live header views, and draft mode in `test-start-webpack`. - Header static bailout in both production bundlers and standalone Edge bundling in `test-start-webpack`. - Five focused Server Action header/cookie cases in each of `test-dev-webpack`, `test-start-turbo`, and `test-start-webpack`, including redirect cookie writes and Edge async storage. <!-- NEXT_JS_LLM -->
-
Jan Kassens authored
## Summary Continue decoupling App Router prerendering from HTTP request objects. Shared preparation no longer carries `req`; dynamic rendering receives it directly. Give prerendering its own signature, removing the request and the ignored dev context and staged fallback params arguments, and update the Node and export callers. ## Verification - Full bootstrap/final builds, core types, focused ESLint/Prettier, and commit hooks passed. - Cache Components: `fallback-shells` passed in start-turbo and start-webpack; `instant-validation-static-shells` passed in dev-turbo. - App directory export: `start.test.ts` and `dynamicpage.test.ts` passed in start-turbo and start-webpack. - Webpack `app/standalone.test.ts` passed, including Edge bundling. - `app-static.test.ts` in both production bundlers: two POST-body caching cases timed out; all other cases passed. A standalone Node fetch probe, without Next.js, reproduced empty-string and empty-URLSearchParams POST timeouts against the fixture's external data endpoint; multipart POST succeeded. <!-- NEXT_JS_LLM -->
-
Jan Kassens authored
# Human This is part of factoring out `request` and `response` access from the rendering path as we don't have real values for them when e.g. pre-rendering at build time. # AI below ## Summary Use the existing `renderOpts.onClose` lifecycle callback to stop tracking fetch metrics when the response closes. This removes a direct response dependency and the request type check from App Router render preparation while preserving production runtime cleanup. Retain the Edge guard and exclude build-time prerenders from cleanup registration. Their lifecycle closes before `after()` callbacks run, and fetch metrics must remain enabled until export collects them. For Node runtime requests, both the old and new callbacks subscribe to the same response `close` event. Add end-to-end coverage for build-time metrics and runtime cleanup. Dev Cache Components can render again while preparing background validation after the response closes, so those metric logs can arrive in either order; this also occurs with canary's implementation. Only that dev case permits the extra render record. Production assertions remain strict for every record. ## Verification - Fetch logging tests: 53 passed with Turbopack and 53 with Webpack in dev. - Lifecycle tests with the failing CI cache-components dev environment: 4 passed. - Production lifecycle comparison: all 6 checks passed with both canary's implementation and this PR. Temporarily restoring the dev-only cleanup guard correctly failed the production runtime-prerender check. <!-- NEXT_JS_LLM -->
-
Sebastian "Sebbie" Silbermann authored
Switches the adapter test-results upload from a shared secret to GitHub Actions OIDC. Requires https://github.com/vercel/front/pull/92017 ## test plan - [x] [e2e deploy tests fail upload because not dispatched on a tag](https://github.com/vercel/next.js/actions/runs/39380276061) -> https://vercel.com/vercel/next-site/logs?panelState=opened&search=%22%2Fapi%2Fadapter-test-results%22&timeline=past12Hours
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by:Claude Code <noreply@anthropic.com>
-
Luke Sandberg authored
## Summary Compaction iterated its input SST files through an mmap with `MADV_SEQUENTIAL`. This does not fit the block layout pattern (which tends to be ValueBlock, ValueBlock, KeyBlock....) because iteration starts from key blocks, so the readahead isn't well targeted. OS level reclaim can recover this memory but it isn't eager and we _know_ after reading a block that we don't need it any more. `StaticSortedFileIter`, which only compaction uses, now always reads blocks with `pread` into owned buffers, independent of the overall database's `AccessMode`, so an open input file holds only the blocks it currently uses. This also enhances SharedBytes with a mechanism to be constructed from an `uninit` buffer (useful for decompression and `pread` targets). This unifies a few codepaths and allows us to avoid some small buffer copies. ### Measurements Full compaction on Linux (podman VM, kernel 7.2, XFS on virtio, page cache dropped before each run, single threaded), 2 rounds: | | time | max RSS | peak mapped file pages | |---|---|---|---| | 1.1 GB zstd database, values 16 B – 8 KiB, mmap (before) | 2.10 / 2.33 s | 315 MB | 301 – 318 MB | | same, `pread` (this PR) | 2.07 / 2.04 s | 10 MB | 5 MB | | 230 MB database of 16Mi tiny entries, mmap (before) | 2.73 / 2.64 s | 245 MB | 201 MB | | same, `pread` (this PR) | 2.35 / 2.37 s | 57 MB | 6 MB | The cgroup's `memory.peak` is the same in both, since it is dominated by page cache, which is charged either way and reclaimable: with a 512 MB cgroup limit both variants complete without OOM kills. What `pread` removes is the input files from the process' RSS. ### Why not mmap with `MADV_RANDOM` and explicit `WILLNEED`/`DONTNEED` That would let the iterator prefetch the blocks it is about to read and drop those behind it, but at best it reaches the memory profile `pread` already has, and adds costs: - `MADV_DONTNEED` on a file mapping only unmaps the pages, they stay in page cache like with `pread`. - With `MADV_RANDOM` there is no readahead, and `WILLNEED` only starts the I/O, it doesn't map pages, so every 4 KiB page still takes a (minor) fault. `pread` copies ~10 KB per call without page table work. - Unmapping requires a TLB shootdown on every CPU running the process, and compaction runs merges on many threads in the same address space as turbo-tasks. This cost grows with concurrency. - `WILLNEED` and `DONTNEED` take kernel level locks, which can lead to contention in addition to general syscall overhead. <!-- NEXT_JS_LLM --> --------- Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com> Co-authored-by:
Luke Sandberg <210140+lukesandberg@users.noreply.github.com>
-
next-js-bot[bot] authored
[diff facebook/react@99c106c4...ba39b32a](https://github.com/facebook/react/compare/99c106c4...ba39b32a) <details> <summary>React upstream changes</summary> - https://github.com/facebook/react/pull/37853 - https://github.com/facebook/react/pull/37856 - https://github.com/facebook/react/pull/37855 </details> --------- Co-authored-by:
next-js-bot[bot] <279046576+next-js-bot[bot]@users.noreply.github.com>
-
Tobias Koppers authored
## Summary This makes the deploy harness's failure say *why* the build-ID markers were missing. It is the second of three stacked PRs and builds on the bounded polling in the PR below it. When polling hits its deadline, the error still starts with `Failed to get buildId from logs`, so existing triage keeps matching. It now also includes: - the deployment URL, the attempt count and the elapsed time; - whether the transcript had **no build-log lines at all**, meaning `vercel inspect --logs` printed only its own header and status lines, which suggests the logs weren't available from Vercel. This is the signature of the canary.7 incident. - otherwise, **which** of `BUILD_ID`, `DEPLOYMENT_ID` and `NEXT_SUPPORTS_IMMUTABLE_ASSETS` are missing; - why the last `vercel inspect` call failed, if it timed out, exited non-zero or rejected. The kept transcript is also stored in `cliOutput` for callers that catch `start()`. The "no build-log lines" check is a heuristic that only feeds this message. Successful ID parsing doesn't depend on it. This PR also removes a duplicated word in a comment in `test/e2e/app-dir/segment-cache/search-params/segment-cache-search-params.test.ts`. That change is there so `Test new and changed tests when deployed` runs a deploy-mode suite against this layer of the harness. ## Verification - `pnpm jest test/unit/next-deploy-failure`: 33/33 pass. The new cases cover a header-only transcript, logs with no markers, only `NEXT_SUPPORTS_IMMUTABLE_ASSETS` missing, and a timed-out last call. They fail on the PR below. - prettier, eslint and `pnpm typescript` are clean. <!-- NEXT_JS_LLM --> <!-- fleet b78d4bc5-dee1-4d80-b647-54229882f21f --> --------- Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Tobias Koppers authored
## Summary This hardens the deploy-test harness when it waits for the fixture's build-ID markers. It is the first of three stacked PRs. **Why.** On v16.5.0-canary.7 attempt 1, 31 of 32 failed deploy jobs (~2,200 assertions) hit `Failed to get buildId from logs` while the deployment showed `● Ready` ([example](https://github.com/vercel/next.js/actions/runs/38006180482/job/114077823330)). canary.6 attempt 3 failed the same way. Evidence from the job logs: - **Logs empty, not malformed.** Every `vercel inspect --logs` attempt returned only the CLI header and status, with **no build-log lines**. It wasn't a truncated transcript and it wasn't an output-format change. - **One time window.** The failures cluster between 2026-10-09 23:58 and about 2026-10-10 00:45 UTC. In the failed-job logs there were 898 failures and 0 successes before 00:40, then a mix, then only successes. canary.6 attempt 3 ran inside the same window. - **Same CLI later worked.** CLI 63.1.2 found the markers on the first try in the canary.7 rerun and in canary.8. - **The 60 s window was borderline.** During recovery, 9 deployments succeeded only on attempt 20/20 of the fixed 20 × 3 s loop. - **Hung calls caused the hook timeouts.** 116 setup hooks hit the 240 s jest timeout. In the case I inspected, only 2 attempts fit after a 60 s build, which points to `inspect` calls hanging; they had no timeout. We can't tell from our side whether the root cause was the Vercel log service or the CLI. This PR makes the harness ride out lag and hangs. It cannot ride out a 45-minute outage. **What changes** (in `fetchBuildLogsUntilComplete`): - **Backoff:** 2, 4, 8, then 10 s between attempts, instead of a fixed 3 s × 20. - **Deadline:** polling stops at `min(deployStart + setup-hook timeout − 20 s, pollStart + 180 s)`, so the harness usually fails with its own error before jest's hook timeout. The setup-hook timeout is `NEXT_E2E_TEST_TIMEOUT`, or the existing 120 s (Linux) / 240 s (Windows) default. The first attempt always runs. No retry starts after the deadline, including when a wait overshoots. - **Per-call timeout:** each `vercel inspect --logs` call gets `min(30 s, time remaining)`. A call that times out, exits non-zero or rejects is retried instead of throwing immediately. - **All three markers required:** `BUILD_ID`, `DEPLOYMENT_ID` and `NEXT_SUPPORTS_IMMUTABLE_ASSETS` must all be present with non-blank values. Before, only the last marker was checked. - **Transcript kept:** the last transcript that contained build-log lines is kept if a later attempt comes back empty. - **Success log:** when the markers are found, the harness logs `Found build log markers for <url> on attempt N after Xms`, so deploy CI logs show how long the markers took to appear. This PR also fixes a typo in a comment in `test/e2e/app-dir/segment-cache/force-stale/force-stale.test.ts`. That change is there so `Test new and changed tests when deployed` runs a real deploy-mode suite against this harness. No timeouts are raised and no deploy coverage is skipped. The custom-script path and the `NEXT_TEST_DEPLOY_URL` path are unchanged. Stack: 1. **This PR:** bounded build-log polling. 2. Diagnostics when the markers never appear. 3. Retry `vercel deploy` on transient network errors before a deployment is reported. Related: draft #96706 swaps the CLI for REST calls but keeps the 20 × 3 s policy. This stack is complementary to it. ## Verification - `pnpm jest test/unit/next-deploy-failure`: 29/29 pass. The new cases mock `execa` and use a fake clock. They cover partial markers, hung, failed and rejected inspect calls, the backoff schedule, the deadline (including an overshooting wait and a deadline already passed during the deploy), the per-call timeout cap, blank marker values, keeping the transcript, and the success log. They fail on the base branch. - prettier, eslint and `pnpm typescript` are clean. - Not run: a real Vercel deployment (the sandbox has no test credentials). <!-- NEXT_JS_LLM --> <!-- fleet b78d4bc5-dee1-4d80-b647-54229882f21f --> --------- Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Jan Kassens authored
Replaces #100334 after reordering the stack. GitHub automatically marked the original PR as merged into its previous stack parent; it was not merged into canary. ## Summary Continue decoupling App Router rendering from HTTP responses: carry `couldBeIntercepted` through `RouteMatch` instead of inferring it from the response's `Vary` header while generating HTML and Flight payloads. Node supplies the existing route-matching result. The dev override and current Edge/build-time values are preserved. Adds payload assertions for interceptable and ordinary Node routes and a scoped restriction against importing `NEXT_URL` back into the renderer. ## Verification 131 test executions passed: - Interception prefetch-cache and parallel-routing suites in `test-start-turbo` and `test-start-webpack`, including Node and Edge navigation. - Interception prefetch-cache suite in `test-dev-turbo`. - `__NEXT_CACHE_COMPONENTS=true` dev validation via `instant-validation-static-shells` (snapshot passed). - Standalone Edge bundling in `test-start-webpack`. <!-- NEXT_JS_LLM -->
-
Luke Sandberg authored
### What? Removes the`collector_is_not_re_executed_for_collectibles_it_has_not_read_yet` test from `turbo-tasks-backend`'s `collectibles_outdated_dependency.rs`. The other variant (`gated_collector_is_not_re_executed_for_collectibles_it_has_not_read_yet`) stays, and its behaviour is unchanged. ### Why? The ungated test failed intermittently on canary with `take=…: executions after the input change` (left 2, right 1). The cause is the race that the module's doc comment already described, not a backend bug. `State::set` invalidates its readers one by one. When the collector is invalidated before the emitter, it re-executes right away, its strongly consistent read of the still-clean source returns at once, and it reads the **old** collectibles. When the new collectibles arrive, it re-executes again, as it should. Instrumentation confirmed this in every failure: the extra execution read `count=200` but saw 5 collectibles. It reproduced in about 2 of 120 serial release runs under CPU load. So "exactly one execution" can't be asserted without controlling that order. I was not very confident about this test when it was added, so dropping it seems reasonable. <!-- NEXT_JS_LLM --> <!-- fleet d8e69eb1-77bc-4ab5-b7cd-1b8550ef786a --> Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Luke Sandberg <210140+lukesandberg@users.noreply.github.com>
-
- 19 Oct, 2026 14 commits
-
-
next-js-bot[bot] authored
-
Aurora Scharff authored
-
Jan Kassens authored
Replaces #100329 after reordering the stack. GitHub automatically marked the original PR as merged into its previous stack parent; it was not merged into canary. ## Summary Continue decoupling App Router rendering from incoming request objects by passing `stagedFallbackParams` as an explicit input from the handler boundary. Keep the existing placeholder map and postponed-state precedence for staged rendering and dev validation. Edge and export supply `null`. This removes the last request-metadata lookup from `app-render.tsx`. A scoped lint restriction prevents value imports from `request-meta` while allowing its types. Existing adapter metadata writes are unchanged. Stacked on #100327. ## Verification - Cache Components regression suites in Turbopack dev: instant navigation, static-shell validation (including partial prefetching), and blocking/sync-IO validation. - Production suites with Turbopack and Webpack: fallback shells, partial shell upgrades, blocking root params, root-param fallback, and static-shell validation (including partial prefetching). - Verified the lint guard rejects aliased value imports and permits type imports. <!-- NEXT_JS_LLM -->
-
Jan Kassens authored
Replaces #100327 after reordering the stack. GitHub automatically marked the original PR as merged into its previous stack parent; it was not merged into canary. ## Summary Continue decoupling App Router rendering from incoming request objects by capturing the initial HMR version in `DevRenderContext` at the handler boundary. Request rendering uses that captured value for the existing inline bootstrap script. Prerendering never consumes the value, so it no longer carries the field in its shared render context. Stacked on #100323. ## Verification - CSS startup-race suites passed in Turbopack dev (14 tests), covering missed edits, the initial baseline, and CSP nonce reuse. - The App startup-race suite's baseline check passed in Webpack dev and Turbopack production, confirming the baseline remains absent there. <!-- NEXT_JS_LLM -->
-
next-js-bot[bot] authored
-
Niklas Mischkulnig authored
Revert part of #95732 This would cause a lot of worker pools to be created. Because `get_evaluate_pool()` takes as an argument the `additional_invalidation` and thus get a fresh worker pool per `additional_invalidation`
-
Andrew Clark authored
`await navigation()` prevents certain parts of a page from being rendered as part of a Link's prefetch (`<Link prefetch={true}>`). However, there are cases where you may wish to override that behavior and forcibly prefetch past that boundary. For example, if you have high confidence that the user will interact with a particular link. This PR adds three new options for a Link's prefetch prop: `"shell"`, `"prefetch"`, and `"navigation"`. `"shell"` and `"prefetch"` exist mostly for consistency — a value of `"shell"` has the same behavior as a missing prefetch prop, and `"prefetch"` has the same behavior as `true`. It's only `"navigation"` that introduces novel functionality. The naming scheme intentionally mirrors the `await prefetch()` and `await navigation()` APIs introduced in version 16.4. They correspond to the same conceptual stages. --------- Co-authored-by:Janka Uryga <lolzatu2@gmail.com>
-
Janka Uryga authored
fixes flakiness introduced in #100388. route trees expire after 5min by default, so they were occasionally causing the "no-requests" assertion (which we were doing after waiting for 5min) to fail in CI. we can avoid this by lowering the stale-time to 4min, which still validates that the cache's stale-time is being respected. (note that this means that the cache would be excluded from app shells. however, this test suite does not currently run in PPF, and has other tests that would have the same problem, so we'll have to deal with this later anyway)
-
Joseph authored
## Summary The `useSearchParams` docs say a prerendered route client-renders the tree up to the closest `<Suspense>` boundary. With Cache Components, that only holds when the rest of the route is prerendered. If any component on the route reads request data, such as `cookies()`, the postponed boundary is rendered on the server at request time with the real search params. Code inside it then runs on the server, and browser-only reads in render cause hydration mismatches. - `docs/01-app/03-api-reference/04-functions/use-search-params.mdx`: In Prerendering, state when the boundary is server-rendered under Cache Components, and point to `use(browser())` for browser-only components. - `errors/blocking-prerender-client-hook.mdx`: The Trade-off section said the fallback always swaps after hydration. Qualify it to routes where the rest is prerendered, and point to `use(browser())` for the request-time case. - `docs/01-app/02-guides/instant-navigation.mdx`: "suspends during server rendering" to "suspends during prerendering". Left unchanged: `errors/missing-suspense-with-csr-bailout.mdx`, which describes the non-Cache Components model and is accurate there. Finding: https://next-maintainer-agent.vercel.tools/agent-feedback/2121 ## Verification Production build on `next@16.4.0-canary.37` with `cacheComponents: true`, `curl "/<route>?q=hello"`: | Route | `useSearchParams` boundary in server HTML | | --- | --- | | Rest of the route prerendered | No, fallback only | | `cookies()` in a sibling `<Suspense>` | Yes, with `hello` | | `cookies()` awaited above the component | Yes, with `hello` | | Sibling `cookies()`, component calls `use(browser())` | No, sibling still streams | Matches `app-render.tsx`: a complete server result resumes and aborts postponed HTML boundaries into client render mode, a partial one saves postponed state for the request-time resume. Only `useSearchParams` was tested; the error page Trade-off covers the other URL hooks on the same code path. <!-- NEXT_JS_LLM -->
-
Janka Uryga authored
Since the introduction of `NavigationStatic`, the `Static` stage hasn't really been very useful, but we kept it as a "marker" stage that delineates where a static prerender ends (after `NavigationStatic`, containing all the finished accumulators). However, things get weird in the presence of caches with hanging inputs, because `createHangingInputAbortSignal` waits until `finalStage` (currently `Static`), which means that the keys for caches with hanging inputs would only finish in the `Static` stage. We were still running the `Static` stage in a separate task, before resolving the accumulators, so in practice this didn't cause any problems, but semantically we expect all userspace code to be done after the `NavigationStatic` task, and this behavior of caches breaks that expectation. I don't want to risk any weird staging bugs because of this, so removing `Static` seems like the easy choice.
-
Tobias Lins authored
**Cause** importing anything from next/server also loads connection(), which loads dynamic-rendering.ts. That file imported React at the top just to read an owner stack in development, and in a proxy build this pulled in the 688 KB app-page-turbo.runtime.prod.js. **Fix** React is now imported lazily. No public API change. Effect on a minimal proxy, on canary: the cold path goes from 53.8 ms to **39.1 ms (−27%)** and JS loaded from **1,466 KB to 748 KB**. The page runtime and React also drop out of middleware.js.nft.json, so the deployed proxy function is smaller. **Test** the new `test/production/app-dir/proxy-no-page-runtime` asserts the proxy's trace has no page runtime or React in it. It fails without the fix and passes with it on Turbopack and webpack. Existing tests that still pass: app-middleware-proxy and proxy-missing-export in production with Turbopack, and the cache-components-errors suites in dev with Turbopack. --------- Co-authored-by:Janka Uryga <lolzatu2@gmail.com>
-
Joseph authored
## Summary Adjusts the "rewritten" wording used in the `usePathname` rewrites section and the `blocking-prerender-client-hook` error page. The old text called the prerendered path the "source" and the browser URL the "rewritten" path, which reads backwards against the `source`/`destination` keys in the rewrites config. It now says the server renders the rewrite destination (for example `/blog/hello` for `app/blog/[slug]/page.tsx`) while the browser keeps the URL it requested, which is what `usePathname()` returns on the client. <!-- NEXT_JS_LLM -->
-
Tobias Koppers authored
### What? `useTempDir` (`test/lib/use-temp-dir.ts`) now deletes its temp directory with Node's native recursive `rm` (with `force` and `maxRetries: 10`) instead of fs-extra's `remove()`. If cleanup still fails after the retries, the error propagates and fails the test, as before. ### Why? `test/production/create-next-app/package-manager/pnpm.test.ts` flakes in the canary **test integration windows** job, usually on "should use pnpm for --use-pnpm flag with example" and sometimes on "should use pnpm when user-agent is pnpm". It normally passes on the in-job retry. create-next-app itself succeeds (`Success! Created use-pnpm-with-example …`). The test then hangs during cleanup until the 180 s timeout: ``` ● create-next-app with package manager pnpm › should use pnpm for --use-pnpm flag with example assert(received) Expected value to be equal to: true Received: false at fixWinEPERM (../node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/remove/rimraf.js:117:5) at ../node_modules/.pnpm/fs-extra@9.0.0/node_modules/fs-extra/lib/remove/rimraf.js:100:15 (x3) then: thrown: "Exceeded timeout of 180000 ms for a test." ``` Example logs: [job 114835938572](https://github.com/vercel/next.js/actions/runs/38255895288/job/114835938572) (lines with `fixWinEPERM`, followed by `finished on retry 1/2`) and [job 114820650313](https://github.com/vercel/next.js/actions/runs/38251637834/job/114820650313) (the user-agent case). Root cause: 1. Right after install or `git init` on Windows, a file in the project can be briefly locked (antivirus, indexer, or a lingering process), so `unlink` fails with `EPERM`. 2. On Windows, fs-extra@9's rimraf handles that in `fixWinEPERM`, which starts with `assert(er instanceof Error)` (rimraf.js:117). 3. Under Jest, Node-core fs errors are created in a different realm from the test's global `Error`, so `instanceof Error` is `false`. This is the known Jest cross-realm `instanceof` issue. 4. The assert throws inside the fs callback. The completion callback never runs, `remove()` never settles, and the test hangs until it times out. Node's built-in `rm` doesn't make that assertion. Its `maxRetries` option retries `EBUSY`/`EMFILE`/`ENFILE`/`ENOTEMPTY`/`EPERM` with a linear backoff (100 ms × attempt), which is intended for short-lived Windows locks like the ones in these logs. ### How? - Delete the directory with Node's native recursive, forced `rm`. This takes fs-extra out of the cleanup path and lets Node's own retry and backoff handle transient Windows locks. - Cleanup errors are not swallowed. A failure that outlasts the retries still rejects from the existing `finally`, so a real problem (e.g. a leaked handle) stays visible instead of turning into a silent leftover directory. - The signature, random path, `mode`, and `NEXT_TEST_SKIP_CLEANUP` behaviour are unchanged, so no caller needs changes. Known limitation: Node's rimraf runs its retry loop at every directory level, and parents retry on `EPERM`/`ENOTEMPTY` too. A transient lock clears quickly, but a lock that **persists** deep in `node_modules` can take much longer than 10 × backoff. This PR fixes the hang that never settles. It doesn't put an upper bound on cleanup time for locks that are never released. ### Verification On Linux, using scratch Jest 29 tests (not committed) against the real `test/lib/use-temp-dir.ts`: - **Reproduced the CI failure before the fix:** forced `process.platform = 'win32'` and injected one `EPERM` from the main realm into fs-extra's `unlink`. Cleanup failed with the same `assert` at `fixWinEPERM rimraf.js:117` and then hit the Jest timeout. - **After the fix:** 10/10 pass on **Node 20.9.0 (the CI version) and Node 24.14.1**: - the Windows-EPERM repro settles - two transient `EPERM`s injected into native `unlink` are retried, and the tree is removed (~310 ms, no warning) - a final `rm` rejection propagates out of `useTempDir` (no warning, no swallowing), including when the test body also threw - populated nested tree and symlink removal, the `rm` options, `NEXT_TEST_SKIP_CLEANUP`, and `mode` all behave as before - `prettier --check` and `eslint` on the changed file pass. Root `tsc --noEmit` reports no diagnostics in this file (other errors in the workspace come from unbuilt `next`). - Not run locally: real Windows. The **test integration windows** job on this PR is the confirmation. A single green run supports the fix but doesn't by itself prove the flake is gone. <!-- NEXT_JS_LLM --> <!-- fleet 5c4ff8b8-95e8-45ed-a98a-89c77031794d --> --------- Co-authored-by:vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-
Tobias Koppers authored
### What? Custom `installCommand`s in isolated test installs now run asynchronously with a hard deadline: 5 minutes by default, overridable with `NEXT_TEST_INSTALL_TIMEOUT_MS`. When the deadline fires, the command's whole process tree is killed before the install rejects with an error that includes the command and the deadline. ### Why? Some canary `build-and-test` jobs were cancelled at the 30-minute job limit while `test/e2e/yarn-pnp/test/with-sass` or `with-eslint` was still running. Normally these suites finish in 2–41s. Evidence: - [with-sass hang](https://github.com/vercel/next.js/actions/runs/38222505551/job/114722860774) - [with-eslint hang](https://github.com/vercel/next.js/actions/runs/38005869176/job/114075560853) These suites use a custom yarn install. `createNextInstall` ran that command with `execSync`, which blocks Jest's event loop, so the suite's 2-minute timeout could not fire while yarn was running. The buffered suite output was lost when the job was cancelled, so we can't prove which install step stalled. What this PR fixes is the verified mechanism that let a stalled custom install defeat Jest's deadline. #99827 has since added `timeout: 5 * 60 * 1000` to that `execSync` call, which caps the hang at 5 minutes. This PR replaces that call and goes further: - **Jest timeouts still fire.** The install no longer blocks the event loop, so hook and test timeouts can fire while yarn is running. - **The whole process tree is killed.** `execSync`'s timeout only sends SIGTERM to the `sh` child, so a `yarn`/`node` grandchild can keep running. This helper SIGKILLs the whole tree and waits for the kill to finish before rejecting. - **Clearer errors.** The error names the command and the deadline, and notes if killing the tree failed. - **Configurable.** The deadline can be changed with `NEXT_TEST_INSTALL_TIMEOUT_MS`; the default stays 5 minutes. ### How? - Replaced `execSync` (and its 5-minute `timeout` option) with a shell `spawn`. It keeps the same cwd, ignored stdin, inherited stdout/stderr, and the custom-install trace span. - Resolves on exit code 0. Rejects on a non-zero exit, a signal, a spawn error, or the deadline. - Accepts the env override only if it is a positive integer within Node's timer range. Otherwise the default is used. ### Verification - A local harness ran a shell command that starts a long-running grandchild. It showed that: - timers keep firing during the install - the 700ms deadline rejects - the grandchild is terminated - success, non-zero exit, and env override/fallback behave as expected - Prettier and ESLint on `test/lib/create-next-install.js`. - `tsc --noEmit -p tsconfig.json`: no errors in this file. The one remaining error, in `test/production/create-next-app/index.test.ts`, comes from my local worktree's outdated `packages/next/dist` build, not from this PR. - After rebasing onto canary 58f4af6a: the harness fails on canary as expected (`runCustomInstall` doesn't exist there) and passes on this branch. The module loads with canary's pnpm v12 settings and its `proper-lockfile` pack lock unchanged. - Not run locally: the real yarn PnP e2e suite. The sandbox has no Yarn registry egress; CI covers it. <!-- NEXT_JS_LLM --> <!-- fleet 167a7005-37a7-407d-950f-35e24969a548 --> Co-authored-by:
vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Tobias Koppers <1365881+sokra@users.noreply.github.com>
-