- 21 Oct, 2026 24 commits
-
-
next-js-bot[bot] authored
-
Jamiboy Mohammad authored
## Summary Deletes 69 `as any` casts from `packages/next/src` (466 → 397) where the existing types already make the cast unnecessary. Each change only removes ` as any`, plus any parentheses that become redundant. Nothing else is added or changed: no new declarations, fields, annotations, helpers, or replacement assertions. The emitted JavaScript is identical, so there is no runtime change. How the casts were found: 1. Delete every `as any` in `packages/next/src`, locating them through the TypeScript AST rather than text search. 2. Run `tsc`, put back each cast whose removal caused an error, and repeat until clean. 3. Retry the casts that were put back one at a time, so removals in the same file can't mask each other. Casts that need a type change, a declaration, or code changes to go away are left to #100419. ## Verification - Transpiled each changed file on `canary` and on this branch with `ts.transpileModule` (the package's compiler options, comments stripped) and compared the output, ignoring whitespace and semicolons: 44/44 identical. - `tsc --noEmit` passes for `packages/next` and for the root project. - Colocated jest suites for the touched files pass (9 suites). <!-- NEXT_JS_LLM -->
-
next-js-bot[bot] authored
This auto-generated PR updates font data with latest available Co-authored-by:next-js-bot[bot] <279046576+next-js-bot[bot]@users.noreply.github.com>
-
Luke Sandberg authored
## Summary When lazy compilation of dynamic imports is enabled (`experimental.turbopackLazyDynamicImports`), lazy `import.meta.glob` matches now get the same treatment: each matched module is compiled only once its thunk is first called. Eager matches are unaffected. ## Verification - Added a `/glob` case to `test/development/app-dir/lazy-dynamic-imports`. <!-- NEXT_JS_LLM -->
-
Luke Sandberg authored
## Summary #98836 added an on-demand `__turbopack_ensure_chunk__` hook to the Turbopack Node dev runtime by overriding `__turbopack_context__.l`. The override returned `ensured.then(() => loadChunkAsync(...))`, so every call that hit a not-yet-cached chunk produced a **new promise**, and the first caller's promise never matched the one later callers got from `chunkCache`. That broke referential identity for `__next_chunk_load__` (which wraps `.l`), which React relies on. It also created extra promises for React's dev async tracking to process. This change makes `loadChunkAsync` itself aware of `__turbopack_ensure_chunk__`: - The hook is called synchronously on a cache miss. If it returns `undefined` (nothing to compile), the chunk is required synchronously and the shared pre-resolved promise is cached, exactly as without the hook. - If it returns a promise (the chunk is being compiled on demand), a single `ensure → require/install` promise is cached in `chunkCache` immediately. Concurrent and later callers all get the same promise until `clearChunkCache()`. - If ensuring the chunk fails (a synchronous throw or an async rejection), the failure is not cached, so the next load retries. `require` failures stay cached as `ChunkLoadError`, as before. - The separate `.l` override and `chunksBeingEnsured` map in `dev-base.ts` are removed. The Node runtime snapshots are regenerated. On the Next.js side, the dev hook is now a plain function. It returns synchronously for chunks that aren't lazy-compilation chunks, or that have no matching entries, and returns a promise only when it actually activates a lazy chunk. ## Verification - `pnpm test-dev-turbo test/development/app-dir/lazy-dynamic-imports/lazy-dynamic-imports.test.ts` (12/12 pass) - A scratch Node script against the generated dev and build runtimes, with a mocked ensure hook. It checks: - async ensure: same promise for concurrent and post-settle calls, ensure called once, modules installed only after ensure, and eviction plus retry after an ensure failure - sync ensure: modules installed synchronously with the shared resolved promise, and no caching after a synchronous throw - cached `ChunkLoadError`, non-JS chunks, and `clearChunkCache` reset The identity and sync-path checks fail on the previous runtime and pass with this change. <!-- NEXT_JS_LLM --> <!-- fleet a53f5f3f-06ac-4812-a068-facaf3b95fe5 --> --------- 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>
-
Tobias Koppers authored
### What? Adds a batch invalidation API and uses it wherever many tasks are invalidated at once: - `Invalidator::invalidate_all`, `invalidate_all_with_reason` and `invalidate_all_with_reasons` invalidate a set of invalidators as one batch. - Duplicates are fine: task ids are deduplicated once. - Empty input does nothing, and records no reasons. - `TurboTasksApi::invalidate_many` / `invalidate_many_with_reasons` (implemented by `TurboTasks`) make one `Backend::invalidate_tasks` call, which previously had no in-tree callers. - Reasons are recorded once, before any work starts. - `TurboTasksBackend::invalidate_tasks` splits large batches into chunks and invalidates them in parallel, using the same sizing as `parallel::for_each_owned` (via the now-public `parallel::for_each_chunk`). Batched invalidations report the `Invalidator` dirty cause, like single ones. - Converted call sites: - File watcher: all invalidators of one event batch go in one call, with one `WatchChange` reason per path. There is now one `file change` span per batch instead of one per invalidator. Its `paths` field lists the changed paths, comma separated, capped at 20 with `, ... (N more paths)`. The call still happens under the existing invalidation lock. - `DiskFileSystem`: whole-filesystem, subtree and after-write invalidation. These replace the per-invalidator `parallel::for_each_owned` calls and per-invalidator reason clones. - `State::set`: all dependents in one call. - A new `state_fan_out` criterion bench in `turbo-tasks-backend/benches`. ### Why? Every multi-task producer called `Invalidator::invalidate` once per task. Each call went through `Backend::invalidate_task` → `invalidate(smallvec![id])`, which runs its own operation and scheduling. So none of these producers got the batched scheduling from #100446 (one scheduler queue lock per batch instead of per task), or the batched restores of paged-out tasks from #100465, which this PR builds on. ### How? - **Dirty priority across helper threads.** When an invalidation comes from inside a task (e.g. `State::set` in a task), the dirtied tasks get that task's priority as their parent priority, which the backend reads from the task-local task state. The parallel helper threads don't have it. So `invalidate_tasks` reads the priority once, before parallelizing, and gives every chunk an `ExecuteContext` with that priority (`execute_context_with_priority`; `ExecuteContext::get_current_task_priority` returns it instead of the task-local). Nothing else of the task state is needed, and other contexts are unchanged. - **Parallel work inside `with_turbo_tasks`.** `scope_bounded` wrapped every job, including jobs it runs on the calling thread, in `turbo_tasks_scope`, which panics while `with_turbo_tasks` holds a borrow of the instance. Jobs now only enter the scope when the thread doesn't already have that same instance. This lets `State::notify_mutated` keep using `with_turbo_tasks`. - **Unique ids at the backend.** `invalidate_many*` requires unique ids. The `Invalidator` helpers dedupe, because the watcher and the filesystem can yield the same task for several paths. Debug builds assert uniqueness for the whole batch before chunking and again in `invalidate` for each chunk; release builds pass the ids through without collecting them. ### Benchmark ``` cargo bench -p turbo-tasks-backend --bench mod -- state_fan_out ``` - **Setup:** one `State` read by N dependent tasks. Each iteration times `State::set` plus a strongly consistent read of the root sum, and asserts the result. - **Variants:** `resident`, and `evicted`, where everything is snapshotted and evicted before each iteration. That eviction step is not timed, and it asserts that at least N tasks were evicted. - **Comparison:** A/B against this PR's parent on `canary`, with the same bench copied in. Six paired runs on one 8-vCPU VM, alternating which side runs first. - **Revision:** measured on an earlier revision of this PR, before it was rebased onto #100465 (batched restores in `invalidate`), and while the chunking still lived in `TurboTasks`. The A/B wasn't re-run on the current revision, so the numbers don't include #100465's effect on either side. - **Statistics:** the change is the geometric mean of the per-pair ratios, with a 95% t-interval. | variant / N | median base | median this PR | change (95% CI) | |---|---|---|---| | resident / 1 | 0.284 ms | 0.288 ms | −7.6% [−32.0%, +25.5%] | | resident / 1,000 | 5.278 ms | 5.023 ms | −1.3% [−5.7%, +3.2%] | | resident / 10,000 | 61.045 ms | 58.029 ms | −4.7% [−8.3%, −1.0%] | | evicted / 1 | 0.258 ms | 0.265 ms | +3.3% [−0.2%, +7.0%] | | evicted / 1,000 | 8.295 ms | 6.760 ms | **−19.4%** [−21.6%, −17.2%] | | evicted / 10,000 | 91.967 ms | 69.775 ms | **−21.8%** [−25.1%, −18.4%] | - **Evicted:** a clear improvement when the dependents have to be restored, from invalidating the chunks in parallel and batching their scheduling (measured without #100465's batched restores). - **Resident:** a small win at 10k, and no reliable difference at 1k or for a single task. - **Limits:** the intervals reflect repeatability on one VM, not across machines. This is a `State` fan-out microbenchmark, not an end-to-end filesystem measurement. The OS page cache was warm. ### Tests - **`tests/invalidate_all.rs`:** - a 2,000-task batch, large enough to chunk, re-executes every task exactly once - duplicates in one batch - reasons show up in the update info - empty batches are no-ops - `State::set` inside a task with 2,000 dependents, and `parallel::for_each` inside `with_turbo_tasks` (both panic without the `scope_bounded` change) - a 1,999-task batch invalidated from inside a task leaves every task dirty with the same parent priority as one task invalidated on its own (fails without the explicit priority: tasks of the helper-thread chunks get `Initial`). Re-executions are held back so the dirty state can be inspected. - **Watcher:** the `paths` span formatting, including truncation. <!-- 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>
-
Tobias Koppers authored
### What? Makes the turbo-tasks test `scope_unbounded::tests::test_unbounded_busy_queue_does_not_churn_workers` deterministic, and tightens its worker-lifetime bound from 16 to 4. ### Why? The test failed intermittently with errors like `a saturated queue should not churn drainers, got 20 lifetimes for 20000 items`. The calling thread enqueued trivial items one at a time while the scope workers drained them immediately. If the producer was preempted for longer than `WORKER_IDLE_TIMEOUT` (100µs), the workers idled out and the next enqueue respawned them. Under CPU load this exceeded the loose bound in about 1 of 5 runs. The old shape also didn't prove much: with the idle timeout set to 0 it still usually passed. ### How? The test still processes 20,000 items, but the queue is now kept saturated by construction rather than by out-racing the scheduler: - **Parents.** Half the items are seeded as parents. Each parent waits until the seed iterator is exhausted, so no worker can sit on an empty queue while the producer is still seeding. - **Children.** Each parent spawns one child, so a worker that exits too early will be re-armed by a later `spawn`. - **Child gate.** Children wait until every parent's `spawn` call has returned. The queue is FIFO, so all parents are already in flight by then and the wait cannot deadlock. While any `spawn` is still pending, no drainer can find the queue empty. With this, a correct implementation has at most 4 accumulator lifetimes: 3 scope workers plus the calling thread. The test now checks that workers are not torn down while work is queued. It no longer measures the exact idle timeout, which can't be asserted without depending on scheduler timing. Verification: - On an 8-vCPU Linux machine: 100/100 runs idle and 100/100 runs with 8 busy-loop processes. More stress runs also passed (300/300 under 8 busy-loop processes, 400/400 across 4 concurrent test loops under 16). - Mutation check: making scope workers exit after each item makes the test fail with thousands of lifetimes (2,940 in the recorded run). - All `scope_unbounded` tests pass, and `cargo fmt --check` and `cargo clippy -p turbo-tasks --tests -- -D warnings` are clean. <!-- NEXT_JS_LLM --> <!-- fleet 8bf6a21a-27a8-41a9-bb36-ee50675a54d6 --> 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>
-
Luke Sandberg authored
## Summary Replaces the `import.meta.glob` code-splitting snapshot test added in #100522 with an execution test. The new test checks the behavior directly: lazy matches load only when called, and each one loads separately. The test checks the runtime module factory map, `__turbopack_modules__`: - The eager match is in the map at startup and evaluates correctly. - Neither lazy match is in the map before its thunk is called. - Loading the first lazy match adds it to the map, but not the second one. - Loading the second lazy match then adds it too. The check targets each module's `(ecmascript)` entry. The map also contains `(ecmascript, async loader)` stubs, and those ship in the importing chunk, so matching on the source path alone would show the lazy targets as already loaded. This is a separate fixture because the existing `resolving/import-meta-glob` test imports the same files both lazily and eagerly, so it can't show that a lazy target isn't loaded yet. The snapshot fixture and its generated chunks are removed. There are no production code changes. ## Verification - With `turbopack/crates/turbopack-ecmascript/src/references/import_meta_glob.rs` temporarily set back to its state before #100522, the new execution test fails because a lazy match is already in the module map before its thunk is called. - With the current implementation, all `import_meta_glob*` execution tests pass, and the remaining `snapshot/imports` tests pass. <!-- NEXT_JS_LLM --> <!-- fleet ca9e5cd1-7e86-4f88-b9f3-22f348cd6f50 --> 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>
-
Tobias Koppers authored
## Summary Stacked on #100324. Includes the commits from #100392, which were folded into this PR. Next.js emits two lifecycle spans for `instrumentation.ts` in the Node.js runtime: `load instrumentation module` and `register instrumentation`. They're backdated, because they're emitted after `register()` returns (`register()` usually installs the tracer provider). Until now they were always separate root traces. Direct entrypoints (Vercel, adapters, standalone handlers) register instrumentation lazily, in the first request. That split the first request's work across extra traces. Now the spans join the trace of the request that triggered registration: ``` route / page entrypoint: [P →] GET /page (BaseServer.handleRequest, backdated to cover registration) ├─ load instrumentation module ├─ register instrumentation └─ prepare route module → render … Node.js middleware entrypoint, no parent: GET (Next.request, backdated) ├─ middleware GET (backdated to cover registration) │ ├─ load instrumentation module │ └─ register instrumentation └─ GET /page Node.js middleware entrypoint with host span / incoming traceparent P: P ├─ middleware GET (backdated to cover registration) │ ├─ load instrumentation module │ └─ register instrumentation └─ GET /page ``` ### How - `ensureInstrumentationRegisteredWithDeferredSpans`: when this call starts registration and registration succeeds, the lifecycle spans are recorded instead of emitted. The function returns an idempotent emitter to that caller only. Concurrent callers, later callers and startup callers get nothing. - `RouteModule.ensureInstrumentation(req, { deferSpans: true })` is called by the templates before `traceRequest`. It records when the request started and returns that time, together with the emitter, as `instrumentation`. `traceRequest` takes it as an option, backdates the request span to that time, and emits the lifecycle spans as the span's first children. - The Node.js middleware template passes the emitter and the start time to the adapter. The adapter calls the emitter first thing inside the `Middleware.execute` span and backdates that span to the request start. - The shared parent (incoming `traceparent`, host span, or the backdated inserted `Next.request` root) is still captured before entering the middleware span. The middleware and the render stay siblings, and `traceparent` handling and forwarding are unchanged. - Unchanged: - `next start` / `next dev` startup registration (separate roots). - Registration errors: emitted immediately with the same statuses, including non-`Error` throws. - Edge (no lifecycle spans). - No `instrumentation.ts`, or no `register` export. - User-created spans in `instrumentation.ts` are out of scope (see #100324). ## Verification - Collector suite, cold direct entrypoints: - Route/page requests, with and without an incoming `traceparent`, and with a host span. - Node.js middleware requests: no parent, incoming `traceparent`, host span. - Each test asserts exactly one load span and one register span in the request's trace, parented as shown above and covered by the backdated parent. For middleware, the parent is the middleware span, and it starts no later than the lifecycle spans and no earlier than its own parent. - Direct-entrypoint single-trace assertions no longer exclude lifecycle spans as startup work. Under `next start`, startup spans stay roots. Fail-first verified. - Deploy-capable `test/e2e/app-dir/otel-middleware-trace`: span tree snapshots of the lifecycle spans with their ancestors, plus the first request's tree including them. - Deployed: children of the request span that triggered registration, or of `middleware GET` for Node.js middleware. - `next dev` / `next start`: startup roots. - No deploy gate. - Unit tests for the deferral helper: once-only, concurrency, startup ownership, no `register`, `register()` errors (including `throw undefined`), and module-load failure. <!-- NEXT_JS_LLM --> <!-- fleet ce0ecb23-b14c-4679-92a9-e676130f618e --> --------- 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> Co-authored-by:
Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
-
Tobias Koppers authored
## Summary Stacked on #100294. Documents in the OpenTelemetry guide that spans created while `instrumentation.ts` loads or inside `register()` don't automatically join a request trace: - Spans started before the tracer provider is installed (e.g. at module top level before `registerOTel()`) are not recorded. - Spans started inside `register()` after `registerOTel()` / the SDK has started typically become separate root traces: the SDK installs the context manager during `register()`, so no parent context set before that is carried over. It also clarifies the existing sentence so it refers to spans created while handling a request, and recommends creating request-scoped spans in request-handling code. Making these spans nest under a Next.js span would require Next.js to install its own global OpenTelemetry context manager before loading `instrumentation.ts`; that was decided against, so this documents the behavior instead. ## Verification - Reproduced with `@opentelemetry/api`, `@opentelemetry/context-async-hooks` and `@opentelemetry/sdk-trace-base`: a span started before the provider exists isn't exported; a span started after installing provider + context manager inside a function wrapped in `context.with(parent, …)` has no parent; the same `context.with` after the manager exists parents correctly. <!-- NEXT_JS_LLM --> <!-- fleet ce0ecb23-b14c-4679-92a9-e676130f618e --> 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> Co-authored-by:
Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
-
Tobias Koppers authored
## Summary Stacked on #100349 (request span before route module preparation). Relands #100136 (reverted in f1a69d7d) and changes the span shape so middleware and the route are **siblings** in one trace per request. ### Resulting shapes ``` next start / next dev: handleRequest GET (bubble, root) ├─ middleware GET └─ GET /page next start / next dev with host span / incoming traceparent P: P └─ handleRequest GET (bubble) ├─ middleware GET └─ GET /page separately-invoked middleware (Vercel, adapters, direct entrypoints), no parent: GET (Next.request, root, inserted by the middleware adapter) ├─ middleware GET └─ GET /page separately-invoked middleware with host span / incoming traceparent P: P ├─ middleware GET └─ GET /page ``` ### How - **Self-hosted:** next-server's middleware-invoke `handleRequest` pass writes its W3C context onto the request (`traceparent`, and `tracestate` only together with it: a received `tracestate` is removed when the context has none). Middleware (Node in-process, or the Edge sandbox via the header) and the render pass both continue it. The render pass forces that extraction even under an active host span (custom server / APM), so it nests under the bubble span; a different `traceparent` the middleware explicitly set still wins. - **Middleware adapter:** an active host span wins over a request `traceparent`; otherwise the request's `traceparent` is continued, and the middleware never changes it. Without any valid context (and OTEL enabled) the adapter inserts a `Next.request` SERVER span (new `NextSpan` enum) named after the method (`http.target` keeps the path). When the downstream request doesn't already carry that shared parent, its `traceparent`/`tracestate` are forwarded via the existing `x-middleware-request-*` overrides, always as a pair: a user-set `traceparent` keeps exactly the trace headers the user set. No headers are added without OTEL. - Request-header overrides replace the whole header set, so when the user set no overrides, the received headers are listed alongside the trace headers. There's no API to add a single header yet; that needs a server and platform change. - Node middleware is no longer detached via `ROOT_CONTEXT` (the 16.3 regression from #95306). The inserted `Next.request` root ends when the middleware finishes, so the render child (a separate invocation) can outlive it. ## Verification - Trace shapes are asserted as printed span trees (`test/lib/otel-span-tree.ts`, from #100349) in inline snapshots. Span IDs are normalized away, but distinct traces keep distinct labels, so a split trace shows up as `[trace A]` / `[trace B]`. - `test/e2e/app-dir/otel-middleware-trace` (added in #100349 with the previous behavior): this PR's snapshot diff shows middleware and render becoming siblings in one trace, in dev, start, Cache Components and deploy, for Node.js and Edge middleware and behind a custom server with a host span (including an incoming `tracestate` not being paired with the host span's context). - Collector suite `test/e2e/opentelemetry/instrumentation`: the middleware test asserts the full span tree in next start/dev, direct entrypoints with/without host span, and the custom server (host span, user-set `traceparent`). - Unit tests for the tracer and `forwardTraceContextToRequest` changes. - `test/e2e/middleware-request-header-overrides`, `test/production/typescript-basic`, `test/production/middleware-typescript` pass. <!-- NEXT_JS_LLM --> <!-- fleet ce0ecb23-b14c-4679-92a9-e676130f618e --> --------- 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> Co-authored-by:
Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
-
Tobias Koppers authored
## Summary Bottom of a stack: this PR → #100294 → #100324 → #100350 → #100392. In direct entrypoints (Vercel, adapters, standalone handlers, i.e. without next-server), `prepare route module` ran before the request span started. Since 16.4 every request therefore produced an extra parentless `prepare route module` trace next to the request trace. Now it is part of the request span: ``` [P →] GET /page (BaseServer.handleRequest) └─ prepare route module → render … ``` ### How - New `RouteModule.traceRequest` (`@internal`, kept out of the published declaration types) starts the request span **before** `prepare`. It uses the caller's tracer. When the handler is wrapped by next-server, which already started the request span, it runs inside that active span instead. - Callers first await the new `RouteModule.ensureInstrumentation` (`@internal`), split out of `prepareImpl`: it registers `instrumentation.ts`, which usually installs the tracer provider, so a span started earlier would not be recorded. `prepareImpl` still calls it, and patches `res.setHeader` as before. - The app-page, app-route, pages and pages-api templates/handlers call `ensureInstrumentation` and then `traceRequest`, and handle the response through one code path: `traceRequest` passes the request span and the request's root span (the span that was active when the handler was invoked — next-server's request span or a platform/host span — or the request span itself), and the route name is propagated to the root span when it isn't the request span. - Parenting of the request span itself (incoming `traceparent`, host span, root) is unchanged. ## Verification - Collector suite `test/e2e/opentelemetry/instrumentation`: direct entrypoint cold and warm requests for all four handler types, with and without an incoming `traceparent` and with a host span, assert `RouteModule.prepare` is inside the request's trace, and route names on the request and parent spans. - New deploy-capable e2e suite `test/e2e/app-dir/otel-middleware-trace` (moved down from #100294): `proxy.ts` and Edge `middleware.ts` variants, plus a custom server with a host span. The app records its spans with a SpanProcessor; the middleware and the render report the spans they can see, and the test asserts the stitched span tree (with `http.target`, `http.route`, `next.route` and `http.status_code` where set at report time) in inline snapshots for pages, route handlers, rewrites, redirects, direct responses, matcher misses, incoming `traceparent`, header overrides and a middleware-set `traceparent`, in dev, start, Cache Components and deploy. Here it records the current behavior (middleware and render in separate traces); #100294 shows the change. - Unit tests for the tracer changes (`tracer.test.ts`). <!-- NEXT_JS_LLM --> <!-- fleet ce0ecb23-b14c-4679-92a9-e676130f618e --> --------- Co-authored-by:vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com> Co-authored-by:
Niklas Mischkulnig <4586894+mischnic@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>
-
Janka Uryga authored
in dev, we update the prerender manifest based on the `generateStaticParams` result. we were using `fs.promises.{readFile,writeFile}` for this, which made it possible for parallel requests to interfere with each other -- when a file is opened for writing by `fs.promises.writeFile`, it gets truncated, and if another request tries to read the manifest in the meantime, it can observe an empty file. this [has caused intermittent crashes](https://app.datadoghq.com/ci/ci-cd/explorer/executions?query=test_level%3Atest%20%40git.repository.id%3A%22github.com%2Fvercel%2Fnext.js%22%20%40test.name%3A%22use-cache-fallback-root-params%20resolves%20cached%20and%20uncached%20roots%20on%20ordinary%20requests%22%20%40test.status%3A%22fail%22&agg_m=count&agg_m_source=base&agg_t=count&ci_cd_explorer_tab=tests¤tTab=overview&eventStack=&fromUser=true&start=1789839150900&end=1792431150900&paused=false) in `use-cache-fallback-root-params > resolves cached and uncached roots on ordinary requests` which has a couple requests hitting the same route in parallel with different params and attempting to update the manifest. switching the reads/writes to be synchronous avoids this problem. i was unable to reproduce this race in 100 runs of `use-cache-fallback-root-params`, which previously would get a failure in around 20 runs -
Luke Sandberg authored
## Summary Non-eager `import.meta.glob` matches were referenced with a parallel chunking type, so every matched module was compiled and shipped in the importing module's chunk group. Only evaluation was deferred to the thunk, so the "lazy" mode did not actually code-split. Lazy matches now use an async edge and load through their async loader, the same as a dynamic `import()`. Each match gets its own chunk, loaded when its thunk is called. Eager matches are unchanged. ## Verification - New snapshot test `turbopack-tests/tests/snapshot/imports/import-meta-glob` shows lazy matches in separate async chunks and the eager match in the entry chunk. - Existing `import-meta-glob*` and `side-effects-glob` execution tests pass. <!-- NEXT_JS_LLM -->
-
Hendrik Liebau authored
The navigation test added in #100447 could fail in CI with a `Network.getResponseBody` protocol error. It tried to read the browser response after `createRouterAct` had intercepted and fulfilled the request. The test now relies on the existing `act` response assertion, DOM check, and cached return navigation instead of reading the intercepted response body again. [Flakiness metrics](https://app.datadoghq.com/ci/ci-cd/explorer/executions?query=test_level%3Atest%20%40git.repository.id%3A%22github.com%2Fvercel%2Fnext.js%22%20%40test.name%3A%22use-cache-swr%20serves%20the%20same%20stale%20value%20in%20navigation%20data%20and%20the%20embedded%20runtime%20prefetch%20while%20revalidation%20is%20pending%22%20%40test.type%3A%22turbopack%22%20%40test.status%3A%22fail%22&agg_m=count&agg_m_source=base&agg_t=count&ci_cd_explorer_tab=tests&fromUser=false&start=1791981691285&end=1792586491285&paused=false)
-
-
Tobias Koppers authored
### What? `invalidate_cell_dependents` in turbo-tasks-backend no longer dirties a dependent task when none of the invalidated dependency keys are still current or outdated dependencies of that task. ### Why? A cell's dependents are collected while the cell task is locked, and each dependent is locked separately afterwards. In between, the dependent can finish an execution that no longer reads the cell, and `cleanup_old_edges` removes the dependency. For hashed cells, the dependent may also track only other keys of the same cell. The code was meant to skip such removed dependencies, but its `continue` only continued the inner per-key loop. So the task was always marked dirty and rescheduled after the loop, even when every key had been removed. Follow-up to https://github.com/vercel/next.js/pull/100446#discussion_r4327450882. ### How? Every key is a separate dependency. Keys are only grouped per dependent to reduce task locking, so the decision is made per task after all keys have been checked: - An **outdated** dependency hasn't been read in the current execution yet. It marks the task dirty, but not stale, so the task is no longer treated as a recomputation (unchanged behavior). - A **current** dependency has already been read. It marks the task stale, which also makes it dirty (unchanged behavior). - A **removed** dependency contributes nothing. The task is only dirtied if at least one key is outdated or current. Installing the new cell content, notifying waiters, and processing the aggregation queue happen regardless. The race can't be triggered reliably through the public turbo-tasks API, so this adds backend unit tests that set up dependency state directly and call `invalidate_cell_dependents`. They cover: - all dependencies removed (keyed and unkeyed) - removed and current dependencies mixed - a current unkeyed dependency - an outdated dependency ### Verification - The two removed-dependency tests fail without the fix and pass with it. - `cargo test -p turbo-tasks-backend` - `cargo test -p turbo-tasks-backend --lib --features task_dirty_cause invalidate_cell_dependents_tests` - `cargo clippy -p turbo-tasks-backend --tests` <!-- NEXT_JS_LLM --> <!-- fleet 894565ac-034e-451c-be25-955c8f8e8ff5 --> 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>
-
Joseph authored
The proxy unit testing section imports `unstable_doesProxyMatch` from `next/experimental/testing/server`, but the package only exports `unstable_doesMiddlewareMatch`, so the documented snippet fails with a type error and `is not a function` at runtime. This points the docs at the exported name so it can be backported for the current release line. - d2d200fc docs: use the exported unstable_doesMiddlewareMatch name in proxy unit testing --- This PR should be backported to active lts.
-
Tobias Koppers authored
Adopts #93362. Closes #93362. ### What? Adds the process memory footprint (RSS / "Memory" column on macOS) to TurboMalloc's trace samples, mirroring how OS memory pressure was wired up in #93333. ### Why? The trace viewer already plots `memory` (TurboMalloc's accounted bytes) and, since #93333, OS-level `memory_pressure`. Neither captures the actual resident size of the process. Tracking the OS-reported footprint alongside the allocator's view exposes overhead from things the allocator doesn't account for (e.g. mimalloc reserves, mmap'd files, executable pages, native dependencies) and makes leaks/regressions in real RSS visible in traces. ### How? - New `TurboMalloc::memory_footprint() -> Option<usize>` (bytes), implemented in `turbopack/crates/turbo-tasks-malloc/src/memory_footprint.rs` with one `mod platform` per OS: - **Linux**: parses the resident-pages field of `/proc/self/statm` and multiplies by `sysconf(_SC_PAGESIZE)`. - **macOS**: `task_info(mach_task_self(), TASK_VM_INFO, …).phys_footprint` — the same value Apple's Activity Monitor labels "Memory". Guards against older kernels that return a shorter struct by checking the returned `count` covers `phys_footprint`. - **Windows**: `GetProcessMemoryInfo(GetCurrentProcess(), …).WorkingSetSize`. New `windows-sys` features `Win32_System_ProcessStatus` and `Win32_System_Threading`. - Other targets (incl. wasm) return `None`. - `TraceRow::MemorySample` gains a `memory_footprint: u64` field. `RawTraceLayer::maybe_report_memory_sample` captures it via `TurboMalloc::memory_footprint().map(|v| v as u64).unwrap_or(0)` at the same sampling point as `memory` and `memory_pressure`. - Trace-server `Store::MemorySample` becomes `(Timestamp, u64, u8, u64)` carrying `(ts, memory, memory_pressure, memory_footprint)`. A new `memory_footprint_samples_for_range` mirrors `memory_samples_for_range` and `memory_pressure_samples_for_range`, sharing the existing `memory_samples_slice` helper so the three result vectors stay index-aligned and use the same `MAX_MEMORY_SAMPLES`-cap max-per-chunk downsampling. - `ServerToClientMessage::QueryResult` exposes a parallel `memory_footprint_samples: Vec<u64>` next to `memory_samples` and `memory_pressure_samples`. This is a wire-format break for the postcard-encoded raw trace (added a serde field to `TraceRow::MemorySample`); old trace files cannot be read by the new trace-server. This matches the precedent set by #93333. ### Testing - `cargo test -p turbo-tasks-malloc` — 10 pass, including a new `parses_typical_statm_content` / `returns_none_on_malformed_statm` parser pair and a runtime `memory_footprint_is_reported_on_supported_platforms` check that asserts `Some(_)` and a positive, plausibly bounded byte count on Linux/macOS/Windows. - `cargo build`, `cargo clippy --all-targets`, and `cargo fmt --check` clean for `turbo-tasks-malloc`, `turbopack-trace-utils`, and `turbopack-trace-server`. <!-- NEXT_JS_LLM_PR --> <!-- fleet fdf95ce6-ffc0-474d-8a27-daecba57a97d --> --------- 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? `invalidate()` now opens its tasks with a bulk optional read (`ExecuteContext::for_each_try_task_all`) instead of one `try_task` per id. Non-resident persisted tasks are restored with one batched disk lookup per category instead of one lookup per task. ### Why? Follow-up to #100446 (https://github.com/vercel/next.js/pull/100446#discussion_r4326845752). The existing bulk read APIs (`prepare_tasks` / `for_each_task*`) are `MustExist`: a task missing in memory and on disk panics. Invalidation needs `try_task` semantics instead, because a task being invalidated may legitimately be gone. ### How? - `prepare_tasks_with_callback` takes a `TaskAccess` mode. - `MustExist` is the existing behavior and keeps the same panics and messages. - `AllowMissing` skips any task that `try_task` would not return, and the callback isn't called for it: - a soft-deleted task, which is left in place - a task that isn't restorable (transient, or no backing storage) and isn't resident, which is discarded - a task whose requested category has no disk key, including when only one category is missing; it is discarded and its restoring claims are cleared - The existing restore phases are reused for both modes: - ready tasks are handed off first - claimed reads are done as batched I/O - claims are applied and waiters notified before callbacks run for the tasks this call restored - tasks a peer is restoring are waited for - New `for_each_try_task_all` is built on that, sharing the guard and lock-counter handling with `for_each_task`. - `invalidate()` uses `for_each_try_task_all`. - It requires unique ids: a `debug_assert!` checks this, with no deduplication cost in release builds. The no-duplicates contract is documented on `Backend::invalidate_tasks`, and every in-tree caller already passes unique ids. - Each task is still marked dirty, and its priority computed, while its guard is held. - Scheduling is still a single `schedule_tasks` call. In-tree, `invalidate()` currently gets a single id from every caller (`Invalidator` → `Backend::invalidate_task`). Batching real multi-task invalidations (file watcher, filesystem invalidation, `State` dependents) through `Backend::invalidate_tasks` is a separate, independent PR, and it carries the benchmark. This PR makes no performance claim. ### Tests - 11 unit tests for `for_each_try_task_all` in `backend/operation/mod.rs`: - resident tasks - persisted tasks that aren't resident, checked with a test-only lookup counter: 3 tasks need 2 batched lookups and 0 single lookups - missing persistent and missing transient ids - soft-deleted tasks - a task with only one category on disk - no backing storage - a mixed batch - waiting on a peer's restore, then either restoring the task or skipping it when missing - `tests/invalidate_tasks.rs`: `Backend::invalidate_tasks` with present, missing persistent and missing transient ids. Each existing task re-executes exactly once. This test also passes on the parent commit. - `cargo test -p turbo-tasks-backend`, `cargo clippy -p turbo-tasks-backend --all-targets -- -D warnings`, `cargo check -p turbo-tasks-backend --features task_dirty_cause` <!-- 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>
-
Hendrik Liebau authored
A final runtime prerender could omit cached content or use a different value from the prospective prerender. This also affected embedded cached navigation streams, which reuse the Resume Data Cache (RDC) from the document or navigation render (#98005). Background revalidation replaced the recorded stale entry with a promise for a new value. The final prerender could then encounter pending data or consume the new value. The same overwrite caused development validation to incorrectly report uncached data. Static prerenders do not start background revalidation; they revalidate usable stale entries in the foreground. Requests and prospective runtime prerenders can serve a stale handler entry immediately and revalidate it in the background. `cacheReady()` does not wait for that revalidation. Background revalidation now writes only to the cache handler. The RDC keeps the entry recorded by the prospective prerender so the final prerender can reuse it. For embedded cached navigation streams, it keeps the entry recorded by the document or navigation render. Those entries must remain available independently of background revalidation. Later reads that reach the cache handler can still observe the revalidated entry. Fixes #99884
-
Niklas Mischkulnig authored
`durableUseCache` + a use-cache function loading a Node.js worker previously crashed because of the `bail!("shouldnt be called")` in `entry_chunk_group` For this implementation-hash computation, we don't actually perform any chunking. We just codegen the individual modules and hash those together. For that, we can optimize the nodejs worker reference implementation to not actually perform any chunking during chunk item codegen. We can just directly use the chunk path instead of doing `entry_chunk_group(chunk_path).await?.last().unwrap().path()` unnecessarily. Found here: https://github.com/vercel/next.js/pull/100504#discussion_r4335368036 -
Niklas Mischkulnig authored
`__next_require__` was not installed before calling `generateStaticParams`
-
한국 authored
### What? Fixed ISR cache lifetime persistence for Pages Router pages using the default `FileSystemCache` implementation. ### Why? Pages Router ISR cache entries did not persist their revalidation interval to disk. After restarting the server, the cache lifetime defaulted to 1 second instead of the configured `revalidate` value. As a result, previously generated pages could be treated as stale immediately after a restart, and the expected `Cache-Control` header was not preserved. This complements #99289, which addressed the same issue for the App Router, and covers the missing Pages Router case. See also #99288. ### How? - Persisted the cache lifetime when writing Pages Router cache entries to disk. - Restored the persisted cache lifetime when reading cache entries from disk. - Added a Pages Router test case to `test/production/app-dir/isr-cache-control-restart/` to verify cache behavior after a server restart. Before the fix, the test failed because the first request after restarting the server returned a `STALE` cache status instead of `HIT`. Verified that all 5 tests pass with both Turbopack and webpack using: - `pnpm test-start-turbo` - `pnpm test-start-webpack`
-
- 20 Oct, 2026 16 commits
-
-
next-js-bot[bot] authored
-
Tobias Koppers authored
### What? In dev, an app-router HMR refresh that arrives before the app router has initialized is no longer dropped. It now runs once the router mounts. Several early requests are coalesced into the newest one. ### Why? `client/app-index.tsx` opens the HMR WebSocket before the initial RSC payload resolves and before `hydrateRoot`. `dispatch` is only set when `useActionQueue` renders. If an `ADDED_PAGE` / `REMOVED_PAGE` / `SERVER_COMPONENT_CHANGES` / `STATIC_PARAMS_CHANGED` message arrives in that window, `hmrRefresh()` throws `Internal Next.js error: Router action dispatched before initialization.` and the refresh is lost. The page then keeps showing stale content until a manual reload. This shows up as the second failure mode of `test/e2e/app-dir/not-found/basic` › "should render the 404 page when the file is removed, and restore the page when re-added". The page is removed, the browser full-reloads to the 404, and the "page re-added" refresh arrives during hydration. The page stays on "Root Not Found" and the restore assertion times out. ### How? The race is resolved in `use-action-queue.ts`, where `dispatch` is initialized: - `dispatchAppRouterAction`: in dev, an `ACTION_HMR_REFRESH` that arrives while `dispatch` is still `null` is stored as the pending HMR refresh instead of throwing. A later early refresh replaces it. Its `AbortSignal` belongs to the newest generation, since `hmrRefresh` already aborts superseded ones. - Once `dispatch` exists, a new HMR refresh clears any older pending one before dispatching. `dispatch` is assigned during render, before the mount effect runs, so this stops a stale (already aborted) refresh from being replayed after a newer one. - `useActionQueue` dispatches the pending refresh from a dev-only mount effect, inside `startTransition`. It never dispatches during render. - Every other action still throws `Router action dispatched before initialization`. Production is unchanged; everything is behind the existing `NODE_ENV` checks. - `hot-reloader-app.tsx` is unchanged from canary. The earlier `deferred-hmr-refresh.ts` helper, its `HotReload` effect and its callback invariant are gone. ### Verification Full test file, `pnpm test-dev-webpack`, CI env (`NEXT_TEST_REACT_VERSION=18.3.1`, `__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true`): | | Runs | `before initialization` errors | Failures | |---|---|---|---| | with only #100112 | 10 | 2 | 2 (both at the restore step) | | with #100112 + this PR | 10 | 0 | 0 | - `pnpm test-dev-turbo` passed 3/3 with both PRs, and `pnpm test-start-webpack` passed. New integration test `test/development/app-dir/hmr-refresh-before-hydration`: - It holds the page before the router initializes by stalling the chunk of a user `app/global-error.tsx`, matched by a marker string in the chunk's source so it works with both bundlers' chunk names. - The initial Flight payload references the global error component as a *value*, which blocks the payload until that chunk loads. - A client component rendered as an element wouldn't work, because element references are lazy. - The main runtime still loads and opens the real HMR socket. - The test edits the server page twice, waits until the browser has received both `serverComponentChanges` messages, then releases the chunk. It asserts that the latest content appears without a full reload, and that the router-before-initialization error doesn't show up. | | webpack dev | Turbopack dev | |---|---|---| | without the fix | fails: `before` stays, and the router error is thrown for each change | same | | with the fix (`NEXT_TEST_MAX_RETRIES=0`) | 5/5 pass | 5/5 pass | After the move into `use-action-queue.ts`: - The integration test passed 5/5 again on both bundlers. - Disabling the deferral makes it fail again on webpack. - The full not-found file passed 3/3 with #100112 applied, in the CI env. - A local harness (not committed) checked the ordering where a newer refresh arrives after render but before the mount effect: removing the clear makes exactly that case fail. This PR is independent of #100112, which fixes the other root cause of the same flake (a webpack dev manifest read while the file is half-written). <!-- NEXT_JS_LLM --> <!-- fleet e9d6c475-aeff-42d9-a058-210b6631f951 --> --------- 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>
-
Tobias Koppers authored
### What? Raise the per-test timeout to 120s for `test/production/app-dir/dynamic-params-retained-cache` when it runs with webpack. Turbopack keeps the default 60s. ### Why? The test runs two production builds and two servers inside one `it`, so the whole sequence shares jest's 60s budget. Recent webpack production CI passes took about 26–48s. On a slower runner the test timed out right after the second server became ready, after both builds had completed ([job](https://github.com/vercel/next.js/actions/runs/38431444892/job/115418819665)). This follows the existing webpack-only timeout used by `server-action-period-hash`, which also runs two builds. ### How? Add `jest.setTimeout(120_000)` behind `IS_WEBPACK_TEST`, with a short comment. ### Verification - `pnpm test-start-webpack test/production/app-dir/dynamic-params-retained-cache/dynamic-params-retained-cache.test.ts` - `pnpm test-start-turbo test/production/app-dir/dynamic-params-retained-cache/dynamic-params-retained-cache.test.ts` <!-- NEXT_JS_LLM --> <!-- fleet 34574f75-75ca-4871-9010-7480c809fbc7 --> 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
-
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>
-