1. 20 Mar, 2026 11 commits
    • nextjs-bot's avatar
      v16.2.1-canary.3 · 546250ec
      nextjs-bot authored
      546250ec
    • Niklas Mischkulnig's avatar
      Turbopack: lazy require metadata and handle TLA (#91705) · 118bdaf6
      Niklas Mischkulnig authored
      A regression from #88487
      
      1. Make metadata import lazy with `() => require()`, just like for the layout segments
      2. Properly await the return value to better handle TLA modules
      
      This align with Webpack which does this:
      
      <img width="1535" height="509" alt="Bildschirmfoto 2026-03-20 um 11 58 00" src="https://github.com/user-attachments/assets/f2864c86-ccce-4884-8417-c8ae06c05f78" />
      
      
      Closes PACK-6927
      Closes #91700
      Closes https://github.com/vercel/next.js/issues/91676
      118bdaf6
    • Joseph's avatar
      docs: post release amends (#91715) · 04cc2f2e
      Joseph authored
      Fixes based on feedback post release
      
      Fixes: https://github.com/vercel/next.js/pull/91715
      04cc2f2e
    • Tobias Koppers's avatar
      turbopack: move "compact database" tracing span to backend layer (#91693) · 47230b12
      Tobias Koppers authored
      ### What?
      
      Move the `"compact database"` tracing span from `turbo-persistence`
      (`db.rs`) to the backend layer
      (`turbo-tasks-backend/src/backend/mod.rs`), make it a root span, group
      it with the sibling `"persist"` span under a shared `"background
      snapshot"` root, and emit one span per compaction session rather than
      one per iteration.
      
      ### Why?
      
      The `compact()` function is called from the background persistence job,
      which runs inside a `"persisting background job"` span (inherited via
      `.in_current_span()` at task spawn time). Previously the `"compact
      database"` span was a child of that ambient span, making it appear
      nested under `"persisting background job"` in traces — inconsistent with
      its sibling spans `"snapshot"` and `"persist"`, which are already
      top-level root spans.
      
      Moving the span to the backend call site and giving it an explicit
      parent allows us to:
      
      1. Detach it from the `"persisting background job"` ambient span.
      2. Group it with the `"persist"` span under a shared `"background
      snapshot"` root span so all snapshot + compaction work appears together
      in trace viewers.
      3. Keep `turbo-persistence` free of span-policy decisions (root vs.
      child), which belong at the call site where the ambient span context is
      known.
      
      ### How?
      
      - Introduced a non-entered `background_span`
      (`tracing::info_span!(parent: None, "background snapshot")`) as a shared
      root for both the snapshot/persist work and the compaction loop.
      - Passed `background_span.id()` as the `parent_span` argument to
      `snapshot_and_persist`, so the `"snapshot"` and `"persist"` spans become
      children of it.
      - Inside the idle compaction loop, a child `"compact database"` span is
      entered and dropped synchronously around each `compact()` call (not
      across the `tokio::select!` await point).
      - Moved the span creation outside the `MAX_IDLE_COMPACTION_PASSES` loop
      so there is one `"compact database"` span per compaction session rather
      than one per iteration.
      - Removed the `tracing::info_span!("compact database")` span from
      `turbo-persistence/src/db.rs` entirely.
      - Downgraded the `"sync new files"` span from `info` to `trace` level
      (noise reduction).
      
      The non-entered `tracing::Span` is `Send`, so it can be safely held
      across the `select!` await without triggering the `future cannot be sent
      between threads safely` compile error that an `EnteredSpan` would cause.
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      47230b12
    • Tobias Koppers's avatar
      turbo-persistence: remove Unmergeable mmap advice (#91713) · df886d4a
      Tobias Koppers authored
      ### What?
      
      Remove the `MADV_UNMERGEABLE` (Unmergeable) mmap advice from
      `turbo-persistence`'s `advise_mmap_for_persistence` helper in
      `mmap_helper.rs`.
      
      ### Why?
      
      The WSL (Windows Subsystem for Linux) kernel does not support
      `MADV_UNMERGEABLE` and returns an error when it is applied, causing
      turbo-persistence to fail on WSL. See:
      https://x.com/von_cronen/status/2034944304712392891
      
      Additionally, `MADV_UNMERGEABLE` is already the **default** state for
      memory pages — KSM (Kernel Same-page Merging) is opt-in via
      `MADV_MERGEABLE`. Explicitly setting `MADV_UNMERGEABLE` on pages that
      were never marked mergeable is a no-op on standard kernels, so the call
      provides no benefit while breaking WSL users.
      
      The `MADV_DONTFORK` advice is retained, as it has a clear correctness
      benefit (prevents mmap regions from being inherited by child processes
      on `fork()`).
      
      ### How?
      
      Removed the `mmap.advise(memmap2::Advice::Unmergeable)` call and its
      associated doc comment from
      `turbopack/crates/turbo-persistence/src/mmap_helper.rs`.
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      df886d4a
    • Hendrik Liebau's avatar
      Fix server actions in standalone mode with `cacheComponents` (#91711) · 8cbc0377
      Hendrik Liebau authored
      The `staticPathKey` condition added in #91231 inadvertently applies to
      server action requests on dynamic SSG routes when `cacheComponents` is
      enabled.
      
      Server action fetch requests from the client do not send the `RSC`
      header (`rsc: 1`). They only send `Accept: text/x-component` and the
      `Next-Action` header. This means `isRSCRequest` and
      `isDynamicRSCRequest` are both `false` for action requests. The new
      `staticPathKey` condition (`isSSG && pageIsDynamic &&
      prerenderInfo?.fallbackRouteParams`) evaluates to `true` for dynamic PPR
      routes, setting `staticPathKey` even though `ssgCacheKey` is `null` for
      actions.
      
      With `staticPathKey` set, the request enters the fallback rendering
      block, which serves the cached fallback HTML shell with the action
      result appended to it, instead of responding with just the RSC action
      result.
      
      The fix excludes server action requests from the `staticPathKey`
      computation by adding `!isPossibleServerAction` to the condition,
      restoring the pre-#91231 behavior where `staticPathKey` was always
      `null` for server actions in production.
      
      fixes #91662
      closes #91677
      closes #91669
      8cbc0377
    • Tobias Koppers's avatar
      Fix layout segment optimization: move app-page imports to server-utility transition (#91701) · 6a8a31a7
      Tobias Koppers authored
      ## Summary
      
      - Add `'turbopack-transition': 'next-server-utility'` to all server-side imports in the `app-page.ts` template so they are properly placed in the server utility layer, rather than relying on `SharedMerged` chunk groups to handle them
      - Remove the now-unnecessary `next-server-utility` transition from `fillMetadataSegment` import in `app_page_loader_tree.rs`
      - Add `SharedMultiple` chunk group variant to support multiple shared entries without a merge tag
        - This avoid passing the `parent` into `SharedMerged`, which did break the layout segment optimization.
      - Refactor `app_module_graphs` to combine `client_shared_entries` + `has_layout_segments` into a single `Option` parameter, simplifying the API and removing the dead code path for non-page endpoints
      
      ## Test plan
      
      - [ ] Verify dev and production builds work with app pages that have layout segments
      - [ ] Verify route handlers still build correctly (no client runtime entries passed)
      - [ ] Run existing app-dir e2e tests
      6a8a31a7
    • Abhishek Mardiya's avatar
      docs: fix broken Activity Patterns demo link in preserving UI state guide (#91698) · 883d93c8
      Abhishek Mardiya authored
      ## What?
      
      Fixes a broken link in the Preserving UI State guide:
      https://nextjs.org/docs/app/guides/preserving-ui-state#examples
      
      The "Activity Patterns demo" link currently points to a non-working URL.
      
      ## Why?
      
      The demo link returns a 404 / invalid page, which makes the example
      section confusing for readers.
      
      ## Changes
      
      - Updated the Activity Patterns demo link to the correct URL.
      
      ## Notes
      
      No functional changes, docs only.
      
      @icyJoseph @delbaoliveira
      883d93c8
    • Hendrik Liebau's avatar
      [test] Fix `edge-async-local-storage` deploy test timeout & race condition (#91643) · 542b2b02
      Hendrik Liebau authored
      The test was calling `createNext` inside each `it.each` test body, which
      meant deployment setup time counted against the 60-second per-test
      timeout introduced in #89929. In deploy mode, `createNext` deploys to
      Vercel which can exceed 60 seconds. When the test timed out, the `next`
      local variable was never assigned (the `await createNext(...)` hadn't
      resolved), so the `afterEach` hook would throw a `TypeError` on
      `next.destroy()`. This left the module-level `nextInstance` variable
      pointing at the stale, half-initialized deploy instance. When the next
      test case started, `createNext` saw the leftover `nextInstance` and
      threw `"createNext called without destroying previous instance"`.
      
      The test now uses `nextTestSetup`, which runs `createNext` in
      `beforeAll` where it has the longer 120-second `setupTimeout`. Both API
      route variants (`/api/single` and `/api/multiple`) are real fixture
      files served from a single instance, so deployment only happens once.
      542b2b02
    • Hendrik Liebau's avatar
      [test] Unflake rendering indicator test & skip building indicator tests (#91650) · 9f181bd1
      Hendrik Liebau authored
      [Flakiness
      metric](https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest%20%40git.repository.id%3A%22github.com%2Fvercel%2Fnext.js%22%20%40test.name%3A%28%22Build%20Activity%20Indicator%20Enabled%20-%20%28app%29%20Shows%20build%20indicator%20when%20page%20is%20built%20from%20modifying%22%20OR%20%22Build%20Activity%20Indicator%20Enabled%20-%20%28pages%29%20Shows%20build%20indicator%20when%20page%20is%20built%20from%20modifying%22%20OR%20%22Dev%20Rendering%20Indicator%20Shows%20build%20indicator%20when%20page%20is%20built%20from%20modifying%22%29%20%40test.status%3Afail&agg_m=count&agg_m_source=base&agg_t=count&fromUser=false&index=citest&start=1773322068865&end=1773926868865&paused=false)
      
      In #85083 we introduced a delay of 400 ms before showing the
      building/rendering indicator, to avoid flashing it for fast operations.
      For now, we skip the building indicator tests because our simple test
      apps usually compile much faster than that, and we haven't found a good
      way to reliably test the indicator without flakiness. We do keep the
      rendering indicator test, but increase the timeout in the pages to
      ensure the indicator is shown for long enough to be detected by the
      test.
      9f181bd1
    • Luke Sandberg's avatar
      [turbopack] Optimize compaction cpu usage (#91468) · 8e9f9514
      Luke Sandberg authored
      ## Summary
      
      Optimizes the turbo-persistence compaction and iteration paths with several targeted improvements:
      
      ### Iterator optimizations
      
      - **Flatten index block iteration** — The iterator previously used a `Vec<CurrentIndexBlock>` stack, but SST files have exactly one index level. Inline the index block fields (`index_entries`, `index_block_count`, `index_pos`) directly into `StaticSortedFileIter`, eliminating the stack allocation and `Option` overhead.
      
      - **Non-optional `CurrentKeyBlock`** — Parse the first key block during `try_into_iter()` construction so `current_key_block` is always populated, removing the `Option<CurrentKeyBlock>` wrapper and its `take()`/`Some()` ceremony in the hot loop.
      
      - **Replace `ReadBytesExt` with direct byte indexing** — In `handle_key_match`, `parse_key_block`, and `next_internal`, replace `val.read_u16::<BE>()` etc. with `u16::from_be_bytes(val[0..2].try_into().unwrap())`. This eliminates th mutable slice pointer advancement.
      
      - **Extract `read_offset_entry` helper** — Read type + offset from the key block offset table in a single `u32` load + shift, replacing two separate `ReadBytesExt` calls.
      
      
      ### Refcounting optimization
      
      - **Introduce `RcBytes`** — Thread-local byte slice type using `Rc` instead of `Arc`, eliminating atomic refcount overhead during single-threaded SST iteration. The iteration path (`StaticSortedFileIter`) now produces `RcBytes` slices backed by an `Rc<Mmap>`, so per-entry clone/drop operations are plain integer increments rather than atomic operations.
      
      
      ### Merge iterator simplification
      
      - **Optimize `MergeIter::next`** — Replaced the straightforwards `pop/push` pattern with `PeekMut`-based replace-top pattern, which means we only need to adjust the heap once per iteration instead of twice.
      
      ## Benchmark results
      
      ### Compaction (`key_8/value_4/entries_16.00Mi/commits_128`)
      
      | Benchmark | Canary | Optimized | Change |
      |-----------|--------|-----------|--------|
      | partial compaction | 1.949 s | 1.515 s | **-22%** |
      | full compaction | 2.051 s | 1.542 s | **-25%** |
      
      ### Read path (`static_sorted_file_lookup/entries_1000.00Ki`)
      
      No read regression — the branch is neutral to slightly faster:
      
      | Benchmark | Canary | Optimized | Change |
      |-----------|--------|-----------|--------|
      | hit/uncached | 6.73 µs | 6.59 µs | **-2%** |
      | hit/cached | 140.8 ns | 130.7 ns | **-7%** |
      | miss/uncached | 5.10 µs | 5.02 µs | **-2%** |
      | miss/cached | 230.1 ns | 233.1 ns | ~+1% (noise) |
      
      ## Test plan
      
      - [x] `cargo test -p turbo-persistence` — 60/60 tests passing
      - [x] Compaction benchmarks run and compared against canary baseline
      - [x] Read path (lookup) benchmarks verified no regression
      8e9f9514
  2. 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
  3. 18 Mar, 2026 3 commits
    • Luke Sandberg's avatar
      [turbopack] Simplify snapshotting logic (#91178) · 98e1133f
      Luke Sandberg authored
      ## Summary
      
      - **Use `modified` flags instead of `restored` flags** to decide which task data categories to encode during snapshots. Previously, `process` used `restored` flags (encoding any category that had been loaded into memory), while `process_snapshot` used `modified` flags. The `restored` check was overly conservative — it would re-serialize categories that were loaded from disk but never actually changed. Using `modified` for both paths only encodes categories that were actually dirtied, avoiding redundant re-persistence of clean data.
      
      - **Unify `process` and `process_snapshot` into a single callback** on `take_snapshot`. Since both closures now use the same logic (`modified` flags), the two-callback API was unnecessary. `take_snapshot` now takes a single `Fn(TaskId, &TaskStorage, &mut TurboBincodeBuffer) -> SnapshotItem` — for snapshot copies the `Box<TaskStorage>` is simply dereferenced before calling.
      
      - **Change transient task handling from silent empty return to `unreachable!`**, since transient tasks should never appear in the persistence path.
      
      ## Test plan
      
      - Existing snapshot/persistence tests should continue to pass
      - The `modified` flags are always set for any task that ends up in the modified map (via `track_modification_internal`), so no categories are missed
      98e1133f
    • nextjs-bot's avatar
      v16.2.1-canary.1 · 33b5b795
      nextjs-bot authored
      33b5b795
    • Luke Sandberg's avatar
      Update tokio from 1.43.0 to 1.47.3 (#90945) · d230d584
      Luke Sandberg authored
      ## Summary
      
      Update the workspace `tokio` dependency from 1.43.0 to ~1.47.3 (pinned to the 1.47.x LTS minor line).
      
      The tokio 1.43.x LTS line expires **March 2026**. This moves to the 1.47.x LTS line (supported until September 2026). The tilde version specifier (`~1.47.3`) ensures we stay on the 1.47.x minor version and only pick up patch releases (e.g. 1.47.4), not new minor versions.
      
      ### Key changes included in this bump
      
      - **Soundness fix**: broadcast channel clone race condition (1.44.2)
      - **`select!` is now budget-aware** (1.44) — cooperates with tokio's cooperative scheduling
      - **Stabilized runtime metrics**: `worker_total_busy_duration`, `worker_park_count`, `worker_unpark_count` (1.45)
      - **Performance**: improved `AtomicWaker::wake`, eliminated unnecessary `lfence` in task queue (1.46-1.47)
      - **New APIs**: `sync::SetOnce`, `Notify::notified_owned()`, `broadcast::WeakSender`, `biased` option for `join!`/`try_join!`
      - **`runtime::Handle` marked unwind-safe** (1.45)
      - Transitive dep bump: `socket2` 0.5 → 0.6, `windows-sys` 0.52 → 0.61
      
      ### Breaking changes (verified safe)
      
      - `from_std` now panics on blocking sockets — **no `TcpStream::from_std` calls in codebase**
      - `LocalSet::{poll,drop}` disallows blocking — **no `LocalSet` usage in codebase**
      - `select!` budget awareness — behavioral change, should improve fairness
      
      ### New duplicate dependencies
      
      - `socket2 v0.6.2` added (v0.4 and v0.5 already existed due to `hyper 0.14`)
      
      ## Test plan
      
      - [x] `cargo check` passes with no errors
      - [ ] CI build and test suite
      d230d584