1. 19 Mar, 2026 26 commits
    • nextjs-bot's avatar
      v16.2.1-canary.2 · af97e756
      nextjs-bot authored
      af97e756
    • JJ Kasper's avatar
      Fix missing route in otel spans without base-server (#91665) · c894f5df
      JJ Kasper authored
      When invoking `handler` exports directly without `base-server` we need
      to ensure span names are still updated with the route correctly so not
      just method name is in span name.
      c894f5df
    • Luke Sandberg's avatar
      [turbopack] Respect `{eval:true}` in worker_threads constructors (#91666) · 3003e17b
      Luke Sandberg authored
      ### What?
      
      Fixed Turbopack incorrectly trying to resolve inline JavaScript code as module references when `new Worker()` is called with `{ eval: true }` option.
      
      Now we skip creating a reference when `eval:true`, and report warnings if we cannot tell what the value is
      
      ### Why?
      
      Libraries like jsPDF create Worker threads by passing inline JavaScript code as the first argument along with `{ eval: true }` as the second argument. Turbopack was incorrectly treating this inline code as a file path and attempting to resolve it as a module reference, causing build failures.
      
      ### How?
      
      Added logic to detect when the `eval: true` option is passed to the Worker constructor. When this option is present, Turbopack now skips creating a worker reference since the first argument contains executable code rather than a file path. Added comprehensive test coverage using jsPDF to verify the fix works correctly.
      
      Fixes #91642
      3003e17b
    • Josh Story's avatar
      Add instant validation tests for parallel slot config attribution (#91656) · e9df6ed9
      Josh Story authored
      Tests that unstable_instant configs placed at different positions across
      a parallel route fork correctly attribute errors to the blocking
      segment, with the cause pointing to the config that requires instant
      behavior. Includes both invalid cases that produce errors and valid
      cases that pass cleanly. Does not yet detect incompatible configurations
      like false on one slot alongside an instant config on a sibling — that
      will be handled in a followup.
      e9df6ed9
    • Hendrik Liebau's avatar
    • JJ Kasper's avatar
      Handle encoded params further (#91627) · 78f73b27
      JJ Kasper authored
      Continues https://github.com/vercel/next.js/pull/91603 applying the
      encoding normalization further and narrows in a better regression test
      separate of root params and specific to vary params flag.
      78f73b27
    • Tim Neutkens's avatar
      Revert "ci: add node-stream test coverage workflow (#89861)" · afbce6a6
      Tim Neutkens authored
      This reverts commit 058d950b.
      afbce6a6
    • Josh Story's avatar
      Add per-slot error attribution for instant validation using slot markers and… · 15cd0274
      Josh Story authored
      Add per-slot error attribution for instant validation using slot markers and config depth preference (#91610)
      
      When a validation boundary spans multiple parallel slots, errors were
      previously attributed to whichever unstable_instant config was found
      first during tree iteration — which varied between turbopack and
      webpack. This made the "Caused by: Instant Validation" source
      non-deterministic and sometimes pointed to the wrong slot's config.
      
      This adds a SlotMarker client component that wraps each slot's content
      at fork points (where parallel routes > 1). The marker's
      dynamically-named inner function appears in the SSR component stack,
      allowing resolveInstantStack to identify which slot an error belongs to
      and look up that slot's config. When a slot has no config, it falls back
      to slotStacks[0] (the root config).
      
      The root config is now selected by config depth preference rather than
      first-found. configDepth tracks how many URL-consuming segments deep a
      config was found, with deeper configs preferred as more specific. At
      equal depth, the children slot is preferred over named slots. This
      ensures deterministic attribution regardless of bundler iteration order.
      
      Key changes:
      - SlotMarker component in boundary-impl.tsx takes a name prop and lazily
      creates named inner functions cached by name
      - slotStacks array replaces the singleton createInstantStack on
      InstantValidationState (index 0 = root config, 1+ = per-slot)
      - configDepth on TreeResult only counts URL-consuming segments —
      synthetic segments like (__SLOT__), __PAGE__, and route groups don't
      contribute
      - resolveInstantStack parses component stacks for slot markers and maps
      to the correct config
      - wrapSlotsWithMarkers called at every fork in both
      buildSharedTreeSeedData and buildNewTreeSeedData
      15cd0274
    • Hendrik Liebau's avatar
    • Vercel Release Bot's avatar
      Update Rspack production test manifest (#91635) · 46377eac
      Vercel Release Bot authored
      This auto-generated PR updates the production integration test manifest used when testing Rspack.
      46377eac
    • Jimmy Lai's avatar
      ci: add node-stream test coverage workflow (#89861) · 058d950b
      Jimmy Lai authored
      ## Summary
      
      Run existing app-dir tests with `__NEXT_USE_NODE_STREAMS=true` in CI to
      validate the node stream rendering path alongside the default web stream
      path.
      
      - New CI job in `build_and_test.yml` that runs a curated set of app-dir
      tests with the flag enabled
      - `test/use-node-streams-tests-manifest.json`: manifest of tests to run
      in node-stream mode
      
      ## Test plan
      
      - [x] CI job triggers and runs tests successfully
      - [x] Does not affect existing CI jobs
      
      ---------
      Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
      058d950b
    • Tim Neutkens's avatar
      Rename /_next/webpack-hmr to /_next/hmr (#91415) · 89871864
      Tim Neutkens authored
      ## What
      
      Rename the HMR WebSocket path from `/_next/webpack-hmr` to `/_next/hmr`.
      
      ## Why
      
      The `webpack-hmr` name is a leftover from when webpack was the only
      bundler. Now that Turbopack is the default bundler for both `next dev`
      and `next build`, the path name is misleading. The generic `/_next/hmr`
      better reflects that this endpoint is bundler-agnostic.
      
      ## Changes
      
      - **Client source** (`page-bootstrap.ts`, `web-socket.ts`): updated the
      WebSocket connection path
      - **Server** (`router-server.ts`): updated the HMR request detection
      path
      - **Turbopack** (`turbopack-dev-server/src/lib.rs`): updated the
      fallback WebSocket path check
      - **Tests**: updated all test files referencing the old path
      - **Docs** (`version-12.mdx`): added a note that the path was renamed to
      `/_next/hmr` in Next.js 16, while keeping the original v12 examples
      intact
      89871864
    • Tim Neutkens's avatar
      feat(node-streams): add config flag, define-env, and env precedence test (#90427) · c5972721
      Tim Neutkens authored
      ## What?
      
      Split out these changes from #89859. Only adds more plumbing for future
      Node.js streams feature.
      c5972721
    • Tim Neutkens's avatar
      refactor: extract build infra and alias changes (#90422) · 58fb9635
      Tim Neutkens authored
      ## What?
      
      Extracts the bundling infra to have the Node.js streams experimental
      flag out of #89859
      
      This only adds the bundle and the v8-jit skill. It does not use the
      bundle yet, and it's not switching code base on the env var.
      
      There will be follow-up PRs for those.
      58fb9635
    • Jiwon Choi's avatar
      Skip CI for agent/editor config directory changes (#91622) · f922882f
      Jiwon Choi authored
      ## Summary
      - Add `.agents`, `.claude`, and `.cursor` to the `docs` group in
      `CHANGE_ITEM_GROUPS` in `scripts/run-for-change.mjs`
      - Changes to these directories (agent skill definitions, editor configs)
      don't affect Next.js build/runtime/tests, so CI should skip for them —
      same as docs-only changes
      - Both `build_and_deploy.yml` and `build_and_test.yml` already use
      `run-for-change.mjs --not --type docs` to detect non-docs changes; this
      extends that behavior to agent/editor config files
      f922882f
    • Hendrik Liebau's avatar
    • Hendrik Liebau's avatar
    • Tobias Koppers's avatar
      turbopack-css: demote recoverable CSS parse warnings to Warning severity (#91524) · 046e0c4a
      Tobias Koppers authored
      ### What?
      
      Extends the CSS parse warning severity improvements in
      `turbopack/crates/turbopack-css/src/process.rs`.
      
      Canary (#90025, #91513) already:
      - Added a `severity` field to `ParsingIssue` and a `fn severity()`
      override
      - Demoted `UnsupportedPseudoClass` / `UnsupportedPseudoElement` selector
      errors from `Error` to `Warning`
      - Still **silently dropped** all other unrecognized parser warning kinds
      (`_ => { // Ignore }`)
      
      This PR completes the work:
      
      1. **Surfaces all previously-ignored parser warnings as
      `IssueSeverity::Warning`** — the `_ => { // Ignore }` arm now emits a
      `ParsingIssue` at `Warning` severity instead of discarding it.
      
      2. **Refactors the warning loop** — the nested severity match inside the
      existing `match err.kind` arm is replaced with a single top-level `let
      severity = match err.kind { … }` followed by an unconditional emit. This
      is cleaner and makes the severity logic easier to follow.
      
      Hard parse/transform errors (`Err(e)` from `parse_css_stylesheet`,
      minify errors, CSS module pure-selector errors) are unchanged — they
      remain `IssueSeverity::Error`.
      
      ### Why?
      
      Silently dropping parser warnings hides useful diagnostic information
      from developers. Surfacing them as `Warning` gives visibility without
      marking the build as broken.
      
      The restructure also avoids a redundant
      `UnsupportedPseudoClass`/`UnsupportedPseudoElement` check inside a
      nested match — the top-level arm order (specific pseudo variants before
      the catch-all `SelectorError(..)`) handles precedence correctly.
      
      ### How?
      
      - Removed the now-unused `error::SelectorError` short import
      (fully-qualified paths are used in the match).
      - Replaced the `match err.kind { <arms that emit> … _ => { // Ignore }
      }` pattern with:
      1. `let severity = match err.kind { UnsupportedPseudo* => Warning, hard
      errors => Error, _ => Warning };`
      2. Unconditional `IssueSource` construction and `ParsingIssue {
      severity, … }.emit()`.
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      046e0c4a
    • Tobias Koppers's avatar
      turbo-persistence: fix mmap page alignment and improve error context in… · 0f089d5f
      Tobias Koppers authored
      turbo-persistence: fix mmap page alignment and improve error context in MetaFile::open_internal (#91640)
      
      ### What?
      
      Two changes to `turbopack/crates/turbo-persistence/src/meta_file.rs` and
      `mmap_helper.rs`:
      
      1. **Bug fix: mmap page alignment** — `MmapOptions::offset()` requires
      the offset to be page-aligned (typically 4096 bytes), but the code was
      passing `file.stream_position()` (the byte position after reading the
      variable-length header), which is not guaranteed to be page-aligned.
      This would cause `mmap` to fail or behave incorrectly on some inputs.
      
      2. **Improved error context** — Add `.context("...")` to all `?`
      operators in `open_internal` (except read calls) and inside
      `advise_mmap_for_persistence`, so errors carry actionable context. The
      filename is already attached by the `MetaFile::open` wrapper, so no
      filename is repeated in these messages.
      
      ### Why?
      
      The mmap offset bug could cause silent failures or panics when the meta
      file header length is not a multiple of the OS page size. The missing
      error context made it hard to diagnose failures in production.
      
      ### How?
      
      **mmap fix (`meta_file.rs`):**
      - Remove `options.offset(offset)` — map the entire file from byte 0
      instead.
      - Add a new `amqf_data_start: usize` field to `MetaFile` storing the
      header-end byte offset.
      - `amqf_data()` now returns `&self.mmap[self.amqf_data_start..]`,
      exposing only the AMQF data region. All existing callers that index into
      `amqf_data()` continue to work unchanged since their offsets are already
      relative to the start of AMQF data.
      
      **Error context (`meta_file.rs`):**
      - `File::open(path)?` → `.context("Failed to open meta file")`
      - `file.stream_position()?` → `.context("Failed to get stream
      position")`
      - `unsafe { options.map(&file) }.with_context(|| format!(...))` →
      `.context("Failed to mmap")` (drop the closure and filename, already
      provided by the outer wrapper)
      - `mmap.advise(Advice::Random)?` → `.context("Failed to advise mmap")`
      
      **Error context (`mmap_helper.rs`):**
      - `Advice::DontFork` → `.context("Failed to advise mmap DontFork")`
      - `Advice::Unmergeable` → `.context("Failed to advise mmap
      Unmergeable")`
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      0f089d5f
    • Tobias Koppers's avatar
      Turbopack: Add importModule() support to webpack loaders (#89630) · bdb2f2ce
      Tobias Koppers authored
      ## What?
      
      Adds support for `this.importModule()` in Turbopack's webpack loader
      compatibility layer. This API allows webpack loaders to dynamically
      import and execute modules (CJS, ESM, TypeScript, JSON, WebAssembly,
      etc.) during the build process, matching webpack's native
      `this.importModule()` behavior.
      
      ## Why?
      
      Webpack loaders like `@vanilla-extract/webpack-plugin`, `val-loader`,
      and custom loaders use `this.importModule()` to:
      - Load configuration files that are themselves modules with dependencies
      - Execute code at build time to generate derived source
      - Process dependency chains (e.g., a TS config that imports a CJS module
      that requires JSON)
      
      Without this, loaders relying on `importModule()` cannot work with
      Turbopack.
      
      ## How?
      
      ### Architecture
      
      The implementation follows a request/response pattern between the
      Node.js loader runner and the Rust-side Turbopack compiler:
      
      1. **Loader calls `this.importModule(request)`** in the Node.js loader
      runner
      2. **IPC message sent to Rust** with the module request and lookup path
      3. **Rust resolves the module** using Turbopack's full resolver (with
      aliases, loader rules, etc.)
      4. **Rust builds a Node.js bundle** containing the module and all its
      dependencies using Turbopack's code generation pipeline
      5. **Bundle chunks sent back to Node.js** via IPC
      6. **Node.js evaluates the bundle in-memory** using `vm.compileFunction`
      with a minimal CJS module system
      
      This approach leverages Turbopack's full module graph, so imported
      modules benefit from the same resolution (aliases, custom loaders,
      TypeScript support, etc.) as regular imports.
      
      ### Key Changes
      
      **Rust side (`turbopack-node/src/transforms/webpack.rs`):**
      - New `ImportModule` IPC response message type
      - Resolves modules through Turbopack's `esm_resolve` with full
      `AssetContext`
      - Generates a complete Node.js bundle (runtime + chunks + entry) for the
      imported module
      - Tracks file dependencies for proper cache invalidation
      
      **`SourceTransform` trait (`turbopack-core/src/source_transform.rs`):**
      - Added `asset_context` parameter to `SourceTransform::transform()` so
      transforms can access the full asset context for module resolution and
      bundling
      - Updated all implementors: `JsonSourceTransform`,
      `TextSourceTransform`, `BytesSourceTransform`, `MdxTransform`,
      `PostCssTransform`, `WebpackLoaderItems`
      
      **Node.js runtime (`turbopack-node/js/src/transforms/`):**
      - `webpack-loaders.ts`: Implements `this.importModule()` on the loader
      context, sends IPC request and evaluates the returned bundle
      - `webpack-loaders-runtime.ts`: In-memory CJS module evaluator that
      loads bundle chunks using `vm.compileFunction`, with support for:
        - Relative and absolute path resolution within the bundle
        - External package delegation to real Node.js `require()`
      - Patched `fs.createReadStream` for in-memory WebAssembly binary assets
      
      **New `ImportModule` reference subtype
      (`turbopack-core/src/reference_type.rs`):**
      - Added `EcmaScriptModulesReferenceSubType::ImportModule` to mark
      references created by importModule for proper handling in the module
      graph
      
      ### Test Coverage
      
      Comprehensive e2e test
      (`test/e2e/app-dir/webpack-loader-import-module/`) covering:
      - **TypeScript modules** with CJS and ESM dependencies
      - **CJS dependency chains** (TS → CJS → JSON)
      - **ESM `.mjs` modules** with shared dependencies
      - **Resolve aliases** (`alias-data` → `alias-data.mjs` via
      `resolveAlias` config)
      - **Custom loader rules** (`.custom-data` files processed by
      `text-to-export-loader`)
      - **Transitive dependencies** through aliases and custom loaders
      - **Turbopack-only features**: `new URL()` asset references, WebAssembly
      imports (`add.wasm`), and dynamic `import()` within importModule targets
      
      All tests pass for both webpack and Turbopack modes.
      
      ---------
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      bdb2f2ce
    • Tobias Koppers's avatar
      turbo-tasks-backend: batch schedule dirty tasks in aggregation_update (#91461) · f8f77da9
      Tobias Koppers authored
      ### What?
      
      Batch the scheduling of dirty tasks during aggregation update processing
      instead of scheduling them one at a time.
      
      In `aggregation_update.rs`, `find_and_schedule_dirty_internal`
      previously called `ctx.schedule()` immediately for each task it decided
      to schedule. This involved a separate `ctx.task(id,
      TaskDataCategory::All)` call per task to read `leaf_distance` and
      `has_output` before calling `turbo_tasks.schedule(id, priority)`.
      
      ### Why?
      
      Each individual `ctx.task(...)` call may require restoring task data
      from persistent storage (disk I/O). When many tasks need scheduling —
      e.g. during a large invalidation wave, or initially when all
      session-dependent tasks are scheduled — doing this one-at-a-time is
      inefficient.
      
      `for_each_task_all` (via `prepare_tasks_with_callback`) can batch the
      restoration of persistent task data, amortizing I/O overhead across all
      tasks in the batch.
      
      ### How?
      
      - Added a `scheduled_tasks: FxHashMap<TaskId, TaskPriority>` field to
      `AggregationUpdateQueue` (skipped in bincode serialization — transient
      state that doesn't survive suspend/resume).
      - `find_and_schedule_dirty_internal` now inserts `(task_id,
      parent_priority)` into `scheduled_tasks` instead of calling
      `ctx.schedule()` directly.
      - At the end of `process()` (in the final `else` branch, when all
      sub-queues are exhausted), if `scheduled_tasks` is non-empty,
      `ctx.for_each_task_all` is called to batch-fetch the tasks and schedule
      them, then `scheduled_tasks` is cleared. This maximizes batch size by
      deferring all scheduling to the end of the operation.
      - `scheduled_tasks` is included in `is_empty()` (with exhaustive struct
      destructuring) so the compiler enforces the check stays up to date.
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      f8f77da9
    • Tobias Koppers's avatar
      Skip loadBindings() Lightning CSS check during next start (#91538) · 6f669f1a
      Tobias Koppers authored
      ### What?
      
      Skip the `loadBindings()` call that checks Lightning CSS support when
      `loadConfig()` is called during `PHASE_PRODUCTION_SERVER` (`next
      start`).
      
      ### Why?
      
      `loadConfig()` currently calls `loadBindings()` (which loads the native
      SWC `.node` binary) whenever `experimental.useLightningcss: true` is
      set, in order to check whether the binary supports Lightning CSS. This
      check gates a warning and a flag reset.
      
      During `next start`, the app is already fully built — no CSS compilation
      happens at serve time. Loading the native binary purely to run a
      capability check that has no effect is wasted work, and it delays server
      startup unnecessarily.
      
      ### How?
      
      - Promote `PHASE_PRODUCTION_SERVER` from a type-only import to a value
      import in `config.ts` so it can be used in a runtime comparison.
      - Add `phase !== PHASE_PRODUCTION_SERVER &&` as the first condition of
      the `if` block that calls `loadBindings()` for the Lightning CSS check.
      When the phase is `PHASE_PRODUCTION_SERVER`, the block is skipped
      entirely and `useLightningcss` is left as-is (unchanged).
      
      All other phases (`PHASE_DEVELOPMENT_SERVER`, `PHASE_PRODUCTION_BUILD`,
      `PHASE_EXPORT`, etc.) are unaffected — `loadBindings()` is still called
      and the capability check runs as before.
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      6f669f1a
    • Tobias Koppers's avatar
      [turbopack] Use bail! instead of panic! for duplicate module ident error (#91636) · 99d64f3a
      Tobias Koppers authored
      ### What?
      
      In `turbopack/crates/turbopack-core/src/module_graph/mod.rs`, the
      `#[cfg(debug_assertions)]` duplicate module ident detection block inside
      `SingleModuleGraph::new_inner` called `panic!` when duplicates were
      found.
      
      ### Why?
      
      `panic!` terminates the process hard, bypassing the normal
      error-handling chain. The enclosing function `new_inner` already returns
      `anyhow::Result<Vc<Self>>`, and `bail!` is already imported and used
      elsewhere in the same file. Using `bail!` converts this into a
      propagatable error, consistent with the rest of the error-handling
      idioms in the module.
      
      ### How?
      
      Single-line change: replace `panic!(...)` with `bail!(...)` at the
      duplicate module detection site. No new imports needed — `bail!` was
      already in scope via `use anyhow::{Context, Result, bail};`.
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      99d64f3a
    • Tobias Koppers's avatar
      Restructure pr-status-triage skill: merge command into skill files (#91514) · 6836c26b
      Tobias Koppers authored
      ### What?
      
      Migrates the `.claude/commands/pr-status.md` slash command into the
      `.agents/skills/pr-status-triage/` skill, restructuring the files so
      that `SKILL.md` has a single unified workflow and supporting details
      live in the appropriate reference files. Deletes the original command
      file.
      
      ### Why?
      
      The pr-status automated workflow existed in two places: a basic 6-step
      outline in `SKILL.md` and a detailed 10-step procedure in
      `.claude/commands/pr-status.md`. This duplication meant the skill was
      incomplete without the command file, and the command file couldn't
      benefit from the skill's supporting reference files (`workflow.md`,
      `local-repro.md`).
      
      ### How?
      
      **`SKILL.md`** — Replaced the old 6-step overview with a unified 7-step
      workflow covering: background `--wait` script launch, failure/review
      analysis, blocker-first prioritization, flaky test checking, local
      reproduction, resolving review threads, and retriggering CI when only
      flaky tests remain. Step 7 now includes a retry loop: after
      retriggering, wait 5 minutes and re-triage from step 1, up to 5 times.
      
      **`workflow.md`** — Extended with content from the command file:
      subagent prompt templates (CI failures + review comments), summary table
      format examples, failure category taxonomy (8 categories), and review
      comment category taxonomy (7 types). Existing sections (prioritization
      order, failure handling rules, common patterns, resolving review
      threads) preserved.
      
      **`local-repro.md`** — Expanded the "Match CI Environment Variables"
      section with feature flag details (`__NEXT_USE_NODE_STREAMS`,
      `__NEXT_CACHE_COMPONENTS`), the `NEXT_SKIP_ISOLATE` warning for module
      resolution fixes, and a concrete example command.
      
      **`AGENTS.md`** — Updated the stale `/pr-status` command reference to
      point to the `$pr-status-triage` skill.
      
      **`.claude/commands/pr-status.md`** — Deleted (all content migrated).
      
      ### Files changed
      
      | File | Action |
      |------|--------|
      | `.agents/skills/pr-status-triage/SKILL.md` | Rewritten with unified
      workflow (includes retry loop for flaky CI) |
      | `.agents/skills/pr-status-triage/workflow.md` | Extended with
      templates, tables, categories |
      | `.agents/skills/pr-status-triage/local-repro.md` | Expanded env var
      section |
      | `AGENTS.md` | Updated skill reference (1 line) |
      | `.claude/commands/pr-status.md` | Deleted |
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      6836c26b
    • Tobias Koppers's avatar
      turbo-tasks-backend: batch find_and_schedule_dirty using for_each_task_meta (#91497) · c13536d0
      Tobias Koppers authored
      ### What?
      
      Batch-process `find_and_schedule_dirty` in `aggregation_update.rs` by
      collecting all queued jobs (up to `FIND_AND_SCHEDULE_BATCH_SIZE` = 10
      000) into a `SmallVec` and pre-fetching their task metadata with a
      batched `ctx.for_each_task_meta(...)` call.
      
      ### Why?
      
      `find_and_schedule` can accumulate thousands of tasks during
      invalidation cascades. The previous implementation issued one
      `ctx.task(...)` call per task inside `process()`, serializing
      backing-storage fetches one at a time.
      
      `ctx.for_each_task_meta` triggers a batched fetch of all task metadata
      from the backing store: keys are sorted by hash for cache-friendly
      sequential access to the storage layer. The callback is invoked per-task
      once data is ready, with the task guard handed directly to the callback
      — no second lock acquisition needed.
      
      The batch limit is set to 10 000, because find-and-schedule jobs are
      cheap (metadata read + optional schedule) compared to aggregation-update
      jobs, so yielding less often is safe and beneficial.
      
      ### How?
      
      **`fn process` — `find_and_schedule` branch:**
      - Replace the one-at-a-time loop with a single
      `drain(..FIND_AND_SCHEDULE_BATCH_SIZE)` that collects up to 10 000
      `FindAndScheduleJob` structs into a `SmallVec`, then calls
      `find_and_schedule_dirty` once with the whole batch.
      
      **`fn find_and_schedule_dirty`:**
      - Change parameter from `task_id: TaskId` to `jobs:
      SmallVec<[FindAndScheduleJob; 4]>`.
      - Call `ctx.for_each_task_meta(...)` to batch-prefetch all task metadata
      (sorted by hash for cache-friendly access) and process each task in the
      callback.
      
      **`prepare_tasks_with_callback` fix:**
      - Release `TaskLockCounter` *before* calling `prepared_task_callback`
      instead of after. This ensures the counter is 0 when the callback runs,
      so callbacks that drop their task guard and then call `ctx.task()` (like
      `find_and_schedule_dirty_internal` → `ctx.schedule()`) no longer trigger
      the "Concurrent task lock acquisition detected" panic in debug builds.
      - `for_each_task` now uses `acquire()` instead of `reacquire()` since
      counter is guaranteed 0 at callback entry. `reacquire()` is removed.
      
      **Cleanup:**
      - Use `FxHashMap` (already imported) instead of
      `std::collections::HashMap`.
      - Combine consecutive `#[cfg(trace_find_and_schedule)]` let bindings for
      clarity.
      - Add `FIND_AND_SCHEDULE_BATCH_SIZE = 10_000` as a self-contained
      constant (not derived from `MAX_COUNT_BEFORE_YIELD`).
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      c13536d0
    • Will Binns-Smith's avatar
      Turbopack: enable server HMR for app route handlers (#91466) · 62393b04
      Will Binns-Smith authored
      App router handlers are already built with the Turbopack runtime, so
      they can use server HMR. **We also already get subscription events for
      their chunks.** However, unlike app pages which use
      `__next_app__.require()` for dynamic devModuleCache lookup, route
      handlers capture userland exports statically in AppRouteRouteModule at
      construction time. This change makes routes behave a lot like pages,
      dynamically loading the user's code when requests are made. This way, we
      can freely invalidate and reload it when changes are made without
      evicting the entire require cache.
      
      Only `next dev` uses this lazy evaluation, as `next start` continues to
      eagerly import route handlers.
      
      This change removes the `isAppPage` restriction from `usesServerHmr`,
      extending server HMR coverage to all App Router entries (pages and route
      handlers) built with the Node.js runtime.
      
      For route handlers, we also clear the entry chunk from Node.js
      `require.cache` on each rebuild so the next `requirePage()` call
      re-executes the entry and obtains fresh module exports from
      `devModuleCache` (which HMR updates in-place).
      
      Test Plan: Added an additional e2e test, `with-dep`
      62393b04
  2. 18 Mar, 2026 14 commits