1. 19 May, 2026 16 commits
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.24 · 338d59cc
      next-js-bot[bot] authored
      338d59cc
    • Luke Sandberg's avatar
      [turbopack] Add trace metadata about the persist size (#93339) · a07cba75
      Luke Sandberg authored
      Record simple counters for how many items were persisted.
      
      This should be cheap enough to always do
      a07cba75
    • Luke Sandberg's avatar
      Stop pinning compiled chunk source on `EcmascriptBuildNodeChunkVersion`. · a9323da2
      Luke Sandberg authored
       (#93807)
      
      ## What
      
      Stop pinning compiled chunk source on `EcmascriptBuildNodeChunkVersion`.
      
      The struct previously held a `Vec<ReadRef<CodeAndIds>>` for every module
      in the chunk, even though the HMR update path only needs the bytes for
      the *changed* subset and the bytes are already on disk. That field was
      also forcing the upstream `CodeAndIds` / `BatchGroupCodeAndIds` tasks to
      stay `serialization = "skip"`, so warm restarts had to re-walk every
      module and re-hash its source to rebuild `entries_hashes`.
      
      This change mirrors the browser-side pattern: a new
      `EcmascriptBuildNodeChunkContentEntries` task lives on the chunk content
      and holds `ResolvedVc<Code>` + `ResolvedVc<u64>` per module. The version
      struct shrinks to `{ chunk_path, minify_type, entries_hashes }`, drops
      `serialization = "skip"`, and switches `chunk_path` from `String` to
      `RcStr`.
      `update_ecmascript_node_chunk_content` now resolves entries lazily, only
      when an added or modified module actually needs its code shipped.
      
      ## Why
      
      Two wins, both for dev sessions starting against a warm filesystem
      cache:
      
      - **Memory.** The version no longer transitively pins every module's
      compiled `Rope` in heap — those bytes can stay on disk until HMR
      actually needs them.
      - **Warm-restart CPU.** `entries_hashes` is sourced from the per-module
      `Code::source_code_hash()` task (already cached) and the version itself
      now round-trips through the persistent cache, so we don't re-hash
      anything on warm start.
      
      The HMR payload shape is unchanged.
      
      ## Perf
      This should speed up warm builds a bit but the major benefit is not
      recomputing node outputs and keeping them in ram
      
      measuring v0 after loading the main route
      Branch: Cold: 12.3G Warm: 7.34G
      Canary: Cold 12.3G Warm: 8.5G
      
      The trace file confirms the recomputations are gone and the heap
      measurements confirm we trimming ~1.1g of ram
      
      Using the devlow benchmarks i was able to confirm a possible small
      progression
      
      ```
      # canary
      chat dev startup build=warm: root page = 23.96 s (from root page/start)
      chat dev startup build=warm: root page = 21.21 s (from root page/start)
      chat dev startup build=warm: root page = 22.70 s (from root page/start)
      
      # branch
      chat dev startup build=warm: root page = 20.94 s (from root page/start)
      chat dev startup build=warm: root page = 19.43 s (from root page/start)
      chat dev startup build=warm: root page = 23.49 s (from root page/start)
      
      ```
      
      
      ## Tests
      
      I added a new integration test to ensure we don't accidentally regress
      here. Which confirms that 'clean warm builds' run nothing and 'clean
      warm dev sessions' just set up HMR session infra
      <!-- NEXT_JS_LLM_PR -->
      a9323da2
    • Luke Sandberg's avatar
      [turbopack-trace-server] Add memory samples to the mcp tool results (#93338) · f7dee1b8
      Luke Sandberg authored
      Expose memory data to the MCP tool for the turbo trace server
      f7dee1b8
    • Luke Sandberg's avatar
      Add MCP `compile_route` tool (#93337) · f49ed227
      Luke Sandberg authored
      ### What?
      
      Adds a `compile_route` MCP tool that triggers on-demand compilation of a
      specific route (app or pages) without issuing an HTTP request, and
      returns any compilation issues.
      
      ### Why?
      
      Coding agents and benchmarking workflows need a way to warm the module
      graph or measure compile time for a route without standing up a live
      backend to satisfy the request. The existing path — hitting the URL —
      requires the route's runtime dependencies to be available and couples
      compile timing to request handling.
      
      ### How?
      
      - New tool `mcp/compile_route` registered in
      `get-or-create-mcp-server.ts`, backed by a `compileRoute({ page,
      clientOnly })` callback plumbed from the Turbopack hot reloader
      - Reuses the dev server's existing on-demand entry path (`ensurePage` /
      `handleRouteType`), so the call path matches a first navigation.
      - Adds a `subscribeToChanges` opt-out on `ensurePage` and threads it
      through `handleRouteType` / `handlePagesErrorRoute`. One-shot MCP
      compilations skip HMR subscription wiring — without this, each call
      would leak a subscription that fires on every subsequent file change for
      the life of the dev server.
      - Telemetry: registers `mcp/compile_route` in the `McpToolName` union.
      - e2e test in
      `test/development/mcp-server/mcp-server-compile-route.test.ts`.
      
      <!-- NEXT_JS_LLM_PR -->
      f49ed227
    • Luke Sandberg's avatar
      make rcstrs on the heap/static slightly smaller (#93805) · 2af85b58
      Luke Sandberg authored
      ### What?
      
      Splits the previously unified `PrehashedString` (which held a `Payload`
      enum of `String | &'static str`) into two separate types:
      `StaticPrehashedString { value: &'static str, hash: u64 }` for atoms
      produced by `rcstr!` / `make_const_prehashed_string`, and
      `DynamicPrehashedString { value: Box<str>, hash: u64 }` for atoms held
      in an `Arc`. The static and dynamic paths were already distinguished by
      the `STATIC_TAG` / `DYNAMIC_TAG` bits in `RcStr`, so the runtime branch
      on enum discriminant was redundant.
      
      ### Why?
      
      - **16 bytes saved per heap-allocated `RcStr` value .** Dynamic atoms
      drop the `String::capacity` field (which was always equal to `len` since
      the contents are immutable) and because they are stored in a
      `triomphe::Arc` this drops the Arc payload to 32 bytes instead of 40
      which matches a mimalloc bucket (previously we were rounded up to a 48
      byte bucket) so we save 16 bytes.
      - **8 bytes saved per static `RcStr` value.** The linker will optimally
      align our 24 byte struct.
      - Removes a layer of dispatch on the hot path (`as_str`, `==`, `Hash`) —
      typed deref to the correct variant instead of matching on `Payload`.
      (i.o.w. one 'descreminent' traversal instead of 2)
      
      ### How?
      
      - `dynamic.rs`: `Payload` enum removed; two structs replace
      `PrehashedString`. `deref_from` split into `deref_static` and
      `deref_dynamic`. `restore_arc` returns `Arc<DynamicPrehashedString>`.
      - `lib.rs`: `as_str` and `into_owned` dispatch on `tag()` (STATIC vs
      DYNAMIC vs INLINE) rather than `location()`. New `heap_hash_and_str`
      helper for `PartialEq` and `Hash` to share the static/dynamic branch.
      `into_owned`'s `try_unwrap` arm uses `String::from(Box<str>)` which
      reuses the box allocation (still O(1)).
      - `turbo-rcstr-macros`: emit `::turbo_rcstr::StaticPrehashedString`
      instead of `::turbo_rcstr::PrehashedString`.
      - Added a comment on `DynamicPrehashedString` noting the future move to
      `triomphe::ThinArc` to fold the two heap allocations (Arc header + boxed
      bytes) into one. Deferred because that change would make
      `RcStr::from(String)` copy the bytes, invalidating the documented cheap
      `String -> RcStr -> String` round-trip — wants a separate evaluation.
      
      
      <!-- NEXT_JS_LLM_PR -->
      2af85b58
    • Hendrik Liebau's avatar
      b8c2854d
    • Will Binns-Smith's avatar
      devlow: add run sampling snapshots and comparison reports (#93833) · 925e24e5
      Will Binns-Smith authored
      A lot of this was written with Claude. We lean a lot on published
      libraries for the statistics, so I've got confidence in them.
      
      This adds top-level commands to devlow, `run`, and `compare`, though
      we're still backwards compatible with `run` being the default if no
      command is specified.
      
      - `--n=<N>` runs each variant N times, `--warmup=<N>` discards the first
      N runs (don't use on cold-start metrics). Default behavior is unchanged
      at n=1.
      - Every run now writes a snapshot CSV to
      `.devlow-bench/snapshots/<ts>.csv` (long format, one row per sample, so
      mixed-unit metrics share a file). Override with `--snapshot=<path>`.
      - `--compare` prints a side-by-side table at the end of a run against
      the newest snapshot. `--baseline=<path>` points at a specific file or
      directory.
      - `devlow-bench compare <baseline.csv> <current.csv>` is a separate
      subcommand for diffing two existing snapshots without rerunning
      anything.
      
      For every scenario/variant/metric combination, it shows baseline vs
      current `mean / p50 / p90 (n)`, the absolute and percent delta, and two
      p-values.
      925e24e5
    • Josh Story's avatar
      Enable rootParams by default (#93863) · 079df0f6
      Josh Story authored
      rootParams is now available by default. the flag is removed.
      
      There are still intentional limitations. For instance rootParams cannot
      be used in route handlers and Server Actions. The feature will be
      expanded with some support for this in the future.
      079df0f6
    • Hendrik Liebau's avatar
      Fix cross-param leak with `prefetch={true}` and `cachedNavigations` (#93940) · 085311e3
      Hendrik Liebau authored
      When both `cachedNavigations` and `varyParams` are enabled and a `<Link
      prefetch={true}>` points to a page with fallback params, the resulting
      Full prefetch could leak param-specific content into the cache entry of
      a different param value. As of today, `varyParams` tracking only works
      within the static stage portion of a response. A Full prefetch response
      covers all stages, so the server-reported set is incomplete and can't be
      trusted — it may arrive empty. The client then re-keys the entry under a
      vary path where every path param is replaced with `<Fallback>`, so a
      subsequent lookup for a different param value collides on that entry and
      reads the previously prefetched page's content.
      
      This change makes `fulfillEntrySpawnedByRuntimePrefetch` skip the
      re-keying when `fetchStrategy === FetchStrategy.Full` and keep the entry
      pinned to its concrete vary path. That aligns Full prefetches with how
      they're already keyed when `cachedNavigations` is disabled, where the
      server sends no `varyParams` and the client never re-keys. The trade-off
      is that we miss out on cross-param sharing for Full prefetches even when
      a segment genuinely doesn't depend on a given param. Ideally we'd track
      `varyParams` through the dynamic stage too, but that's not possible
      today: the `varyParams` thenable would need to resolve before the render
      completes, while React waits for the thenable to resolve before
      completing the render — a deadlock in the Flight response.
      
      This limitation should naturally go away as `prefetch={true}` evolves
      under Cache Components, where it will likely become a runtime prefetch —
      a render aborted at a known stage — at which point we can track
      `varyParams` properly across stages for these requests, likely switching
      from a thenable to an async iterable.
      085311e3
    • Darpan Kakadia's avatar
      [otel] honor traceparent for verbose mode spans (#93874) · a722ae9f
      Darpan Kakadia authored
      ## Problem
      Fixes the trace propagation issue reported in
      https://github.com/vercel/otel/issues/107.
      
      `NEXT_OTEL_VERBOSE=1` opened the `NextServer.getRequestHandler` span
      before request header propagation, so incoming `traceparent` was ignored
      and framework spans started a new trace.
      
      ## Solution
      Extract propagated request context before wrapper request-handler spans.
      Add focused e2e coverage in the existing OpenTelemetry suite for verbose
      spans inheriting the incoming `traceparent`, including the parent span
      id.
      
      Validated with `pnpm --filter=next build` and `pnpm test-dev-turbo
      test/e2e/opentelemetry/instrumentation/opentelemetry.test.ts`.
      
      <!-- NEXT_JS_LLM_PR -->
      a722ae9f
    • Josh Story's avatar
      Remove vercel approvers (#93921) · 4aeea622
      Josh Story authored
      Outdated. we don't really use these
      4aeea622
    • Niklas Mischkulnig's avatar
      Add nextConfig.instrumentationClientInject (#93785) · 944e4548
      Niklas Mischkulnig authored
      This allows injecting client bootstrap code using only next.config.js
      (without writing to any user source files).
      944e4548
    • Tim Neutkens's avatar
      Use node streams for server inserted HTML (#93934) · 7f7175ba
      Tim Neutkens authored
      ### What?
      
      Routes server-inserted HTML rendering through the app-render stream-ops
      Fizz helpers instead of calling `renderToReadableStream` directly.
      
      ### Why?
      
      This lets server-inserted HTML use Node streams when
      `__NEXT_USE_NODE_STREAMS` is enabled, matching the runtime stream
      selection used elsewhere in app render.
      
      ### How?
      
      Imports `renderToNodeFizzStream`, `renderToWebFizzStream`, and
      `streamToString` from `./stream-ops`, then selects the appropriate Fizz
      renderer based on `process.env.__NEXT_USE_NODE_STREAMS` while preserving
      the existing progressive chunk size.
      
      
      <!-- NEXT_JS_LLM_PR -->
      7f7175ba
    • Tim Neutkens's avatar
      Add create PR skill (#93937) · 1c081802
      Tim Neutkens authored
      ### What?
      
      Adds a repo-local `$create-pr` skill for turning local changes into
      draft pull requests, and links it from the Specialized Skills section in
      `AGENTS.md`.
      
      ### Why?
      
      This captures the branch, commit, push, and PR creation workflow for
      future agents, including the Next.js PR body format and Codex app Git
      directives.
      
      ### How?
      
      Adds `.agents/skills/create-pr/SKILL.md` with a concise step-by-step
      workflow and updates `AGENTS.md` with a one-line `$create-pr` reference.
      
      <!-- NEXT_JS_LLM_PR -->
      1c081802
    • Tim Neutkens's avatar
      docs: update agent test guidance (#93924) · cafbb1ad
      Tim Neutkens authored
      ## Summary
      
      - remove agent guidance for shortcut test commands based on local test
      harness env vars
      - steer local test guidance toward explicit mode-specific scripts
      - keep CI reproduction guidance focused on matching CI mode and command
      
      ## Testing
      
      - git diff --check -- AGENTS.md
      - lint-staged via pre-commit hook
      
      <!-- NEXT_JS_LLM_PR -->
      cafbb1ad
  2. 18 May, 2026 9 commits
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.23 · 90827408
      next-js-bot[bot] authored
      90827408
    • Tobias Koppers's avatar
      Rename TaskExecutionReason::Initial to Root (#93922) · 148c7ff0
      Tobias Koppers authored
      ### What?
      
      Renames the `TaskExecutionReason::Initial` variant to
      `TaskExecutionReason::Root` in turbo-tasks, and updates its `as_str()`
      representation from `"initial"` to `"root"`.
      
      ### Why?
      
      The variant's doc comment already describes it as "A root task was
      initially scheduled and is executed". The name `Initial` is misleading
      because it suggests "first execution of any task", which overlaps
      semantically with other variants like `ActivateInitial` (a task
      activated for the first time with no output yet). `Root` accurately
      reflects that this reason is specifically used when a root task is
      scheduled, making the enum easier to read and reason about at call sites
      and in traces.
      
      ### How?
      
      - `turbopack/crates/turbo-tasks/src/task_execution_reason.rs`: rename
      the enum variant `Initial` → `Root` and update the `as_str()` mapping to
      return `"root"`.
      - `turbopack/crates/turbo-tasks-backend/src/backend/storage_schema.rs`:
      update the single construction site that used
      `TaskExecutionReason::Initial` when scheduling a root task.
      
      No behavioral changes — this is a pure rename. The other `*Initial`
      variant (`ActivateInitial`) is intentionally left untouched because it
      describes a different concept (first-time activation of a non-root
      task).
      
      Verified with `cargo check` and `cargo clippy` on `turbo-tasks` and
      `turbo-tasks-backend`.
      
      Closes NEXT-
      Fixes #
      Co-authored-by: 's avatarv-work-app[bot] <262237222+v-work-app[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      148c7ff0
    • Luke Sandberg's avatar
      Eval next.config export functions in the try catch (#93884) · 0114ea24
      Luke Sandberg authored
      Move next.config evaluation inside the try catch where we import and
      transform it
      
      This ensures we print an appropriate help link if the export function
      throws
      0114ea24
    • Aurora Scharff's avatar
      Distinguish in-navigation errors in the instant error overlay (#93843) · 15d2272c
      Aurora Scharff authored
      ### What?
      
      When instant validation flags a route that can't load instantly, the
      overlay shows a warning. This PR (1) distinguishes nav-phase warnings
      from initial-render ones in the overlay text, and (2) clears the
      nav-phase warnings on route change so they don't accumulate after the
      user has moved on.
      
      ### Why?
      
      The redbox previously couldn't tell whether a route's instant warning
      was raised while rendering it directly or while navigating into it — the
      text and stack looked the same. And once one was surfaced, it stuck
      around even after the user navigated elsewhere, where it was no longer
      actionable. The two changes together make each warning describe the
      phase that produced it and only stay visible while it's still relevant.
      
      ### Demo
      
      - Subnav under Suspense:
      [cookies](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/41-subnav-cookies)
      ·
      [fetch](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/42-subnav-fetch)
      
      ### How
      
      - New in-navigation variants of the body factory messages ("during the
      initial render or a navigation") let the overlay tell nav warnings apart
      from initial-render ones. The diagnostic clause stays aligned ("accessed
      outside of \`<Suspense>\`"); only the phase and consequence change.
      - The overlay reads the phase off the message, picks a matching
      headline, and on route change drops nav warnings while keeping
      initial-render errors in the redbox stack.
      - Renames the \`GuidanceVariant\` value (\`'navigation' → 'dynamic'\`)
      that collided with the new in-nav phase concept.
      
      ---------
      Co-authored-by: 's avatarCursor <cursoragent@cursor.com>
      15d2272c
    • Niklas Mischkulnig's avatar
      Pass projectDir to adapter modifyConfig (#93916) · f46db1c4
      Niklas Mischkulnig authored
      Adapters implementing `modifyConfig` may need to know the absolute
      project directory to perform path resolution or apply directory-specific
      configuration logic. Without this value, adapters had no reliable way to
      determine where the application lives on disk.
      
      onBuildComplete already received the directory as a parameter.
      f46db1c4
    • Hendrik Liebau's avatar
      [test] split `og-api` test suite into default and standalone variants (#93915) · 2ca0d5df
      Hendrik Liebau authored
      The fixture's `next.config.js` had `output: 'standalone'` hardcoded,
      which is meaningless on Vercel deployments (the standalone directory is
      ignored) but became a build-time crash after #93684 made the Turbopack
      NFT generator skip `next-server.js.nft.json` whenever an adapter is
      configured. With `output: 'standalone'` still active,
      `writeStandaloneDirectory` then fails with `ENOENT` when it tries to
      read that file
      ([x-ref](https://github.com/vercel/next.js/actions/runs/26006483168/job/76441905221)).
      
      This PR splits the `og-api` E2E suite into a default variant and a
      `standalone.test.ts` wrapper that enables `output: 'standalone'` via the
      `TEST_OUTPUT_STANDALONE` env var, and excludes the standalone wrapper
      from the deploy test manifest.
      
      The default variant still runs in `deploy` mode and preserves coverage
      of `next/og` from Pages Router API routes, App Router route handlers
      (edge and node), and middleware — paths not covered by the metadata-*
      fixtures. The standalone variant continues to exercise the trace-copy
      assertion in `next start` mode.
      
      ---------
      Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
      2ca0d5df
    • Tobias Koppers's avatar
      turbopack: emit assets before duplicate check in emit_assets (#93875) · 75d2ed53
      Tobias Koppers authored
      ### What?
      
      Reworks `emit_assets` in `crates/next-core/src/emit.rs` so that:
      
      - The actual `emit()` / `emit_rebase()` write runs **before**
      `check_duplicates()`.
      - Per-duplicate diff checks inside `check_duplicates` run in parallel.
      - At most one `EmitConflictIssue` is emitted per asset path, even when
      multiple duplicates conflict.
      - The conflict-issue emission is wrapped in a `turbo_tasks::function`
      and reported via `as_side_effect()`.
      
      ### Why?
      
      Under eventual consistency, all children might be removed from
      `emit_assets`. This causes all `content()` and `emit()` tasks being
      inactive and keeping the stale value (which is potentially an error).
      
      On recomputation of `emit_assets()` this only makes very few `content()`
      tasks active, as tasks are still in a stale error state and make
      `emit_assets()` exit early. So it takes N recomputations of
      `emit_assets()` to be up-to-date, where N is the number of duplicate
      assets. This can slow down builds drastically and did cause build time
      up to 30min.
      
      Emitting the asset first ensures the file is written to disk even if the
      subsequent duplicate diagnostic crashes under eventual consistency.
      Doing the diff checks in parallel and folding conflicts into a single
      issue keeps the diagnostic path cheap and avoids noisy duplicate output
      for the same path. Tracking the issue emission as a turbo-tasks side
      effect means it is properly attributed to a task instead of being
      emitted ad-hoc from `emit_assets`.
      
      ### How?
      
      - Swap the order in both branches of `emit_assets` (server-side `emit`
      and client-side `emit_rebase`) so the write happens first, then
      `check_duplicates` runs as a diagnostic afterwards. A comment is left
      explaining the ordering requirement.
      - `check_duplicates` now returns `Result<()>` instead of returning the
      picked asset. The caller picks `assets.first()` directly, since
      `check_duplicates` only validated equivalence — it didn't choose a
      different asset.
      - The inner loop in `check_duplicates` uses `iter.map(async |next| { ...
      }).try_flat_join().await?` to run the diff comparisons in parallel and
      collect conflict details. `ext` is computed once before the loop and
      cloned into each task.
      - Only the first conflict from the collected list is reported, instead
      of one issue per conflicting asset.
      - The `EmitConflictIssue` emission is moved into a local
      `#[turbo_tasks::function] fn emit_conflict_issue(...)` invoked via
      `.as_side_effect().await?`, so the issue is tracked as a task side
      effect.
      
      <!-- NEXT_JS_LLM_PR -->
      
      ---------
      Co-authored-by: 's avatarClaude Opus 4.7 (1M context) <noreply@anthropic.com>
      75d2ed53
    • Tobias Koppers's avatar
      [Turbopack] Add graph-based CSS chunking algorithm behind… · e2fca6c6
      Tobias Koppers authored
      [Turbopack] Add graph-based CSS chunking algorithm behind experimental.cssChunking: "graph" (#93606)
      
      ### What?
      
      Adds an alternative CSS chunking algorithm to Turbopack, opted into via:
      
      ```js
      // next.config.js
      module.exports = {
        experimental: {
          cssChunking: 'graph',
          // or, with explicit cost overrides:
          // cssChunking: { type: 'graph', requestCost: 20_000, moduleFactorCost: 1 },
        },
      }
      ```
      
      The new algorithm is **off by default** — Turbopack still uses the
      existing
      "loose"/dependencies algorithm unless this flag is set, so this PR is a
      pure
      addition for users that don't opt in.
      
      While we were here, the `experimental.cssChunking` shape was also
      generalized
      so every existing string accepts an object form too:
      
      | Value | Bundler | Notes |
      |---|---|---|
      | `true` / `'loose'` / `{ type: 'loose' }` | both | default
      heuristic-based chunking |
      | `'strict'` / `{ type: 'strict' }` | webpack | unchanged |
      | `false` | webpack | unchanged (one chunk per CSS module) |
      | `'graph'` / `{ type: 'graph', requestCost?, moduleFactorCost? }` |
      Turbopack | new |
      
      Cross-bundler combinations are rejected at config-validation time:
      - `'graph'` with webpack throws.
      - `'strict'` and `false` with Turbopack throw.
      
      ### Why?
      
      The existing Turbopack CSS chunker (loose / dependencies) is good at
      preserving CSS ordering but doesn't share chunks across pages well —
      every
      page tends to load its own chunk per CSS module, which scales poorly for
      apps
      with many pages and shared component libraries.
      
      The new "graph" algorithm models the per-chunk-group CSS ordering as a
      weighted DAG over modules, then greedily merges adjacent runs in the
      global
      topological order whenever the merge reduces total cost. The cost model
      charges every CSS request and overshipped byte, with two tunable knobs
      (`requestCost` and `moduleFactorCost`).
      
      **Trade-off vs. the loose default.** With the default cost parameters
      (`requestCost: 20_000`, `moduleFactorCost: 1`) the graph algorithm
      typically
      ships **less CSS per chunk group at the cost of more requests** than the
      loose algorithm. The cost model is tuned to avoid overshipping unrelated
      CSS
      into pages that don't need it; on apps where the loose algorithm was
      already
      collapsing a lot into one big chunk that some pages didn't actually use,
      the
      graph algorithm will split it. Apps that prefer fewer requests can raise
      `requestCost`; apps that prefer less overshipping can raise
      `moduleFactorCost`.
      
      This is opt-in and Turbopack-only because:
      - The cost model is sensitive to per-app properties (number of pages,
      size
      distribution of CSS modules, …) — keeping it experimental gives us room
      to
        tune defaults from real usage.
      - Webpack already has its own `CssChunkingPlugin` and `'strict'` mode
      that
        cover the equivalent design space; we don't want to fork that.
      
      ### Performance
      
      Measured on `vercel.com` (the full graph algorithm spans
      `create_graph → make_acyclic → linearize → split_into_chunks →
      assemble`):
      
      - **~3s** end-to-end for the synchronous chunking pipeline on a
      realistic
        production input.
      
      Implementation choices that matter for that throughput:
      
      - Tarjan SCC uses `Vec<u32>` / `Vec<bool>` scratch arrays indexed by
        `NodeIndex` — no hashing on `indices` / `lowlinks` / `on_stack`.
      - `make_acyclic` batches multiple cuts per SCC pass by seeding
      successive
      short-cycle searches at the previous cut's target, only re-running
      Tarjan
        when no further cycle is reachable from the seed.
      - `find_short_cycle` is a bidirectional Dijkstra over a `BinaryHeap`
      with
      predecessor pointers (no path cloning) and skips its refinement loop for
        trivial 2-cycles.
      - `split_into_chunks` picks the next merge from a `BinaryHeap` keyed on
      the
        cost delta instead of an O(N) linear scan per merge.
      - `chunk_cost` reads a once-built `module_to_groups` inverse index
      instead of
      scanning every chunk group on every call; the GlobalStyle leakage check
      uses binary search on the inverse index rather than scanning each
      group's
        module list.
      
      ### How?
      
      #### Module layout (`turbopack/crates/turbopack-core/src/module_graph/`)
      
      The two algorithms are deliberately split so neither imports from the
      other:
      
      - `style_groups/` — algorithm-neutral output types (`StyleGroups`,
        `StyleItemInfo`, `make_style_groups`). Both algorithms produce these.
      - `style_groups_loose/` — the existing ("loose") algorithm plus the
      shared
        config types (`StyleGroupsAlgorithm`, `StyleGroupsConfig`,
        `F32TaskInput`).
      - `style_groups_graph/` — the new algorithm. Pure Rust, no `Vc`, with
        `petgraph::DiGraph` plus a thin `SubgraphView` wrapper and a small
        `ReadonlyGraph` trait that lets the same pipeline run against either a
        `&DiGraph` or a filtered view of one SCC.
      
      #### Algorithm
      
      ```text
      create_graph → make_acyclic → linearize → split_into_chunks → assemble batches
      ```
      
      1. **`create_graph`** — for each chunk group, every `(later, earlier)`
      pair
         inside the group's CSS-module list becomes an edge `later → earlier`
         (weight 1, accumulated). Heavy edges = strong co-occurrence.
      2. **`make_acyclic`** — co-occurrence almost always introduces cycles;
      each
      multi-node SCC has its lowest-weight cycle edge cut until the graph is a
         DAG.
      3. **`linearize`** — Kahn-style topological sort with a tie-break on
      edge
      weight, so strongly co-occurring modules end up adjacent in the global
         order.
      4. **`split_into_chunks`** — greedy bottom-up merger over the global
      order.
         At every active split point we score the merge as
      `cost(merged) - cost(left) - cost(right)`, take the most-negative score
         from a min-heap, and repeat until no merge would reduce cost.
         `max_chunk_size` and "global CSS must not leak into unrelated chunk
         groups" are enforced as `+infinity` cost.
      
      The cost model is:
      
      ```text
      cost_per_group(chunk, group)
        = chunk_size
        + (chunk_size / group_total_size) * module_factor_cost
        + request_cost
      ```
      
      summed over the chunk groups that load the chunk.
      
      #### Wiring
      
      - `StyleGroups::shared_chunk_items` is a
        `FxIndexMap<ChunkItemWithAsyncModuleInfo, StyleItemInfo>` where
        `StyleItemInfo { order: Option<u32>, batch: Option<…> }`. The graph
      algorithm fills `order` so `style_production.rs` can stable-sort chunks
      globally; the legacy algorithm leaves `order = None`, which makes the
      sort
      a no-op for it. `flatten_and_sort` returns the `StyleItemInfo`
      references
      alongside each chunk item so the per-item loop doesn't re-query the map.
      - A new `StyleGroupsAlgorithm` enum on `ChunkingConfig` selects the
        algorithm at chunking time; `ModuleGraph::style_groups` dispatches
      to either `compute_style_groups` (existing) or
      `compute_style_groups_graph`
        (new).
      - `next-core` exposes `NextConfig::css_chunking() ->
      Vc<CssChunkingAlgorithm>`
      resolving the JS `experimental.cssChunking` to the Rust enum, with cost
      defaults applied (`requestCost: 20_000`, `moduleFactorCost: 1`). All
      three
        chunking-context constructors (`next_client`, `next_edge`,
        `next_server`) thread it through.
      
      #### Configuration
      
      - `experimental.cssChunking` zod schema accepts the new shapes; cost
      params
        are `z.number().nonnegative().finite().optional()`.
      - `config-shared.ts` exports a `CssChunkingConfig` type alias and a
      `resolveCssChunkingMode(value)` helper that normalizes any input to one
      of `'off' | 'loose' | 'strict' | 'graph'`. Both `webpack-config.ts`
      (plugin
        wiring) and `config.ts` (bundler-compat validation) use the helper.
      - New `errors.json` entries for the three bundler-compatibility
      validation
        errors (E1193 graph-on-webpack, E1194 strict-on-Turbopack, E1195
        false-on-Turbopack).
      
      #### Tests
      
      - 53 Rust unit tests in `style_groups_graph/tests.rs` cover
      `create_graph`,
      Tarjan SCC, `find_short_cycle` (bidirectional Dijkstra), `make_acyclic`,
        `linearize`, `split_into_chunks`, and end-to-end pipeline scenarios.
      - `test/e2e/app-dir/css-order/css-order.test.ts` is parametrised over
      `[label, value]` pairs. The Turbopack matrix now includes `'graph'` and
      an
      object-form `{ type: 'graph', requestCost: 1, moduleFactorCost: 1 }` in
      addition to the existing default. Per-page expectations grew a
      `requests`
      object encoding distinct request counts for `loose` and `graph` where
      they
        differ.
      - A new `sandwich` e2e fixture (`/sandwich/a`, `/sandwich/b`) exercises
      the
      case where two pages share a leading and trailing chunk around a unique
      middle stylesheet — including a global stylesheet that the algorithm
      must
      not leak into unrelated chunk groups. The graph algorithm hits the
      optimal
        3 chunks per page on this fixture; loose mode falls short.
      
      #### Documentation
      
      - `ExperimentalConfig.cssChunking` JSDoc describes every accepted shape
      and
        what each cost knob does.
      - The `style_groups_graph` module-level docs describe the pipeline, cost
        model and constraints with diagrams.
      
      Closes NEXT-
      
      <!-- NEXT_JS_LLM_PR -->
      
      ---------
      Co-authored-by: 's avatarv-work-app[bot] <262237222+v-work-app[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      e2fca6c6
    • Tim Neutkens's avatar
      Convert more tests from createNext -> nextTestSetup (#93799) · 7da98e13
      Tim Neutkens authored
      ## What?
      
      Converts more tests that use `createNext` to `nextTestSetup`
      
      Follow-up to #93767
      
      ---------
      Co-authored-by: 's avatarCursor <cursoragent@cursor.com>
      7da98e13
  3. 17 May, 2026 2 commits
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.22 · 247bd079
      next-js-bot[bot] authored
      247bd079
    • Tobias Koppers's avatar
      turbo-tasks: prioritize recomputed tasks with Recomputation priority (#93876) · 703d4da4
      Tobias Koppers authored
      ### What?
      
      Introduces a new `Recomputation` priority in `TaskPriority` that
      schedules recomputed tasks (tasks re-run because their output or cell
      wasn't available when read) ahead of all invalidation phases. Also
      documents every `TaskExecutionReason` variant and removes the unused
      `Local` variant.
      
      ### Why?
      
      When a task is recomputed because a downstream consumer needed its
      output/cell, that recomputation should run before lower-priority
      invalidations so the consumer can make progress. Previously these
      recomputations were scheduled with `Initial` priority, which placed them
      alongside fresh work and behind ongoing invalidation phases, hurting
      latency for the task actually being awaited.
      
      Care is needed so the new priority doesn't spread virally: any
      invalidation triggered during a `Recomputation` task must not itself be
      tagged `Recomputation`, otherwise the priority would leak across the
      graph and break ordering. The change therefore resets the priority to
      `Initial` for invalidations triggered from a recomputation context.
      
      ### How?
      
      - `turbo-tasks/src/manager.rs`: Add `TaskPriority::Recomputation`
      variant, ordered before `Invalidation`. Update `Display` and `update`
      impls.
      - `turbo-tasks-backend/src/backend/mod.rs`: Schedule
      output-not-available and cell-not-available recomputations with
      `TaskPriority::Recomputation` instead of `Initial`.
      - `turbo-tasks-backend/src/backend/operation/invalidate.rs`: When
      `make_task_dirty_internal` runs under a parent task with `Recomputation`
      priority, downgrade the propagated priority to `Initial` so the
      recomputation marker does not spread. Also tighten the "already dirty"
      branch so a stored `Initial` priority is always replaced by a more
      specific parent priority.
      - `turbo-tasks/src/task_execution_reason.rs`: Document each variant and
      drop the unused `Local` variant (and its `as_str` arm).
      
      Closes NEXT-
      
      <!-- NEXT_JS_LLM_PR -->
      703d4da4
  4. 15 May, 2026 6 commits
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.21 · ec0279c7
      next-js-bot[bot] authored
      ec0279c7
    • Yavor Punchev's avatar
      Redesign dev overlay: cleaner shell + instant fix-card guidance (#93755) · 495c3183
      Yavor Punchev authored
      ## Summary
      
      ### Error overlay shell
      - Clean up nav, dialog frame, footer placement, and button styles across
      the overlay
      - Remove unused `fader` and notch components
      - Tighten layout spacing throughout the dialog
      
      ### Instant error guidance (fix cards)
      - New data-driven fix-card grid for instant errors: each card has a
      `group` (Stream / Cache / Block / Static / Dynamic / Client / Defer /
      Measure / Prerender), an icon, a color, and an optional docs link
      - Whole card is clickable when a docs link is present, with an
      always-visible external-link indicator
      - Centralized group metadata (label / color / icon) in
      `instant-guidance-data.ts` so cards stay consistent across the overlay
      and the docs surface
      - Outlined SVG icons live in a dedicated `fix-card-icons.tsx`
      - Snippets refined: cache cards trimmed to 3 lines, client sync-IO defer
      cards use block-body arrow syntax so longer expressions don't overflow
      
      ### Code frame
      - Restore the red bar / caret on the errored line (parser previously
      only matched storybook synthetic frames)
      - Fix caret alignment with `codeFrameColumns` output
      - Style inline error code snippets
      
      ### Storybook & examples
      - Add error examples and instant-error fixtures for development/testing
      - Align all 11 instant storybook fixtures with canary factory output and
      the matching test-app routes
      
      ---------
      Co-authored-by: 's avatarAurora Scharff <aurora.sofie@gmail.com>
      Co-authored-by: 's avatarCursor <cursoragent@cursor.com>
      Co-authored-by: 's avatarAurora Scharff <66901228+aurorascharff@users.noreply.github.com>
      495c3183
    • Hendrik Liebau's avatar
      Trace middleware/proxy source files in webpack NFT pipeline (#93871) · f3f56ece
      Hendrik Liebau authored
      Webpack's source-level NFT pass in `next-trace-entrypoints-plugin.ts`
      previously ran only for `pages/` and `app/` entries, so middleware fell
      back to the post-bundle chunk trace in `collect-build-traces.ts`. That
      trace cannot see through webpack's numeric module-ID indirection (`f =
      c(3024)` where module 3024 re-exports `require("node:fs")`), so runtime
      file references inside Node middleware — e.g.
      `fs.readFile(path.join(process.cwd(), 'package.json'))` — never made it
      into `middleware.js.nft.json`. Vercel deploys then 500'd with `ENOENT
      '/var/task/package.json'` because the file was not shipped into the
      function bundle. Turbopack avoids this through its own pre-bundle asset
      graph trace, which is why only the webpack deploy path was affected; the
      test that surfaced it (the `/test-node-fs` case in
      `test/e2e/middleware-general`) had been skipped on deploy until #93614
      re-enabled it.
      
      The fix extends the Pass 1 entry filter to also process middleware
      entries, keyed off `isMiddlewareFilename` and using
      `buildInfo.route.absolutePagePath` as the entry source — middleware
      lives at the project root rather than under `pagesDir`/`appDir`, so
      `getPageFilePath` does not apply. The existing `createTraceAssets`
      emission and the `collect-build-traces.ts` merge already handle
      arbitrary entry names, so no further changes are needed downstream.
      
      `test/e2e/middleware-general/app/middleware-node.js` is also cleaned up
      to use static `import * as fs from 'node:fs'` / `node:path`, drop the
      redundant `process.env.NEXT_RUNTIME === 'nodejs'` guard, and wrap the
      callback `fs.readFile` in a Promise. `@vercel/nft`'s symbol table only
      recognizes the callback and sync `fs` APIs, not `fs.promises.*`, so the
      call site has to remain a direct `fs.readFile(...)` for the path
      argument to be backtracked into the trace; a TODO references the
      upstream gap.
      f3f56ece
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.20 · 518e6f8d
      next-js-bot[bot] authored
      518e6f8d
    • Sam Selikoff's avatar
    • Josh Story's avatar
      Remove partialFallbacks config flag (#93859) · d698d658
      Josh Story authored
      Flag is already defaulted true. Removes option to disable
      d698d658
  5. 14 May, 2026 7 commits
    • Josh Story's avatar
      Instant Insights: only report non-validatable if dev render is error free (#93858) · 4e75a9c3
      Josh Story authored
      When an error prevents validation from happening that same error likely
      shows up in the main dev render. To avoid double reporting in dev we
      silence notices about validation being incomplete if the main render has
      errors to report to the user. If no user facing errors exist then we
      will report the lack of validation as it's own issue to confront.
      4e75a9c3
    • Jude Gao's avatar
      Mark .agents/skills as internal so external `npx skills add` hides them (#93856) · 30421ba1
      Jude Gao authored
      Adds `metadata.internal: true` to all 12 `.agents/skills/*/SKILL.md` files so external `npx skills add /path/to/next.js` no longer lists Next.js framework-dev skills — only `next-compile` remains visible.
      
      <!-- NEXT_JS_LLM_PR -->
      30421ba1
    • Aurora Scharff's avatar
      Fix `Date.now()` cause shadowing in sync IO error overlay (#93857) · 27dbc903
      Aurora Scharff authored
      ## What
      
      When a user writes `Date()` or `new Date()` in a Server Component and
      instant validation surfaces a sync IO error, the dev overlay incorrectly
      labels the cause as `Date.now()`.
      
      ```tsx
      return <p>{new Date().toString()}</p>
      ```
      Overlay headline says: `Next.js encountered Date.now() without an
      explicit rendering intent.`
      
      ## Why
      
      `getBlockingRouteErrorDetails` in `errors.tsx` classifies the API by
      scanning the error message with `String.prototype.includes` against
      `SYNC_IO_APIS` in order, first match wins. The time-type factory always
      embeds `Date.now()` in the `elapsedTimeBullet` text (`Measure elapsed
      time with \`performance.now()\` instead of \`Date.now()\``) regardless
      of which API the user called. Because `Date.now()` was first in the
      array, it matched the bullet text and shadowed the real expression.
      
      Fix: put `new Date()` and `Date()` before `Date.now()` so the
      more-specific entries win when both appear in the message.
      
      User-visible cards and docs URL are unaffected — all three time variants
      map to the same card set — only the cause label was wrong.
      
      ---------
      Co-authored-by: 's avatarCursor <cursoragent@cursor.com>
      27dbc903
    • Josh Story's avatar
      Instant Insights: When unable to complete validation provide a filename for the… · e2b0d2ea
      Josh Story authored
      Instant Insights: When unable to complete validation provide a filename for the unvalidated boundary (#93770)
      
      The error message previously did not say which parallel route slot
      couldn't be validated. Now it poitns to the nearest segment below the
      validation boundary. The idea is you go look abive this and figure out
      if it is intentional that this segment isn't rendered in the current
      context. If so you can ignored the warning (it should ideally not even
      be presented as a normal error) but if it is unintentional you
      investigate why you aren't SSRing this slot or you mark the slot as
      intentionally blocking so it doesn't get validated.
      e2b0d2ea
    • Hendrik Liebau's avatar
      Fix server action forwarding loop with middleware rewrites (#93792) · 20892dd4
      Hendrik Liebau authored
      Reopens #93710 from a branch on this repo so the required deploy test
      matrix can run — GitHub Actions doesn't expose secrets to fork PRs, and
      those deploy jobs are required checks. All commits and credit carry
      forward from the original PR by @elishagreenwald, which built on earlier
      attempts by @LiamBoz in #84525 and @claygeo in #92053.
      
      When middleware rewrites a Server Action POST to a page that doesn't
      bundle the action, the receiving worker forwards the request to a worker
      that does. The forwarded request hits middleware again and gets
      rewritten the same way, so the new receiving worker forwards again —
      looping until undici's headers timeout (~300s) or memory pressure brings
      the server down (#84504). The fix is two related changes on the
      forwarding code path. The first is an `!actionWasForwarded` guard in
      `action-handler.ts` so a request carrying `x-action-forwarded: 1` is
      never forwarded a second time. The second is a new branch in
      `createForwardedActionResponse` that copies the
      `x-nextjs-action-not-found` header and 404 status onto the originating
      response when the forwarded worker can't find the action either; without
      it the client would see a generic "unexpected response" error instead of
      the `UnrecognizedActionError` that the rest of the framework expects.
      
      The e2e test at `test/e2e/app-dir/action-forward-loop` reproduces the
      scenario. A `proxy.ts` rewrites POSTs to `/with-action` so GETs still
      render the page normally; the page renders a `<form>` with an inline
      server action wrapped in a React error boundary that branches on
      `unstable_isUnrecognizedActionError`. The test clicks the button and
      waits for `#action-not-found-error`. Without the loop guard the test
      times out at 10s, and without the pass-through the boundary catches a
      generic error and the assertion fails — so both changes are individually
      load-bearing.
      
      This is a short-term fix. The mid-term direction is to remove
      server-side action forwarding altogether and have the client dispatch
      each Server Action to the route that actually bundles it, which makes
      the entire forwarding code path (and this bug surface) unnecessary.
      #90549 is the draft exploring that approach.
      
      Fixes #84504
      
      Closes #93710
      Closes #84525
      Closes #92053
      
      ---------
      Co-Authored-By: 's avatarElisha Greenwald <ejgreenwald@gmail.com>
      Co-Authored-By: 's avatarLiamBoz <thisamazingnow@gmail.com>
      Co-Authored-By: 's avatarkmaclip <kmartclips@proton.me>
      20892dd4
    • Janka Uryga's avatar
      [CC] fix: cachedNavigations missing asyncApiPromises in resumes (#93827) · 448347a3
      Janka Uryga authored
      When rendering dynamically for `cachedNavigations`, we do a staged
      render so that we can recover a static prefetch from the stream.
      However, we weren't delaying params properly because we were missing
      `asyncApiPromises` and `fallbackParams` from the store, so dynamic
      params would incorrectly resolve in the static stage.
      
      This was masked in the tests, which accidentally had a bunch of `await
      setTimeout(300)` delays left in. so components that were meant to test
      when params resolve were always resolving in the dynamic stage, because
      timeouts are tasky.
      
      I'm not confident in the fix for missing `fallbackParams`, it's
      robot-assisted and i'm not very familiar with those bits, but it seems
      to work
      448347a3
    • Luke Sandberg's avatar
      fetch: respect HTTP Cache-Control headers with TTL-based invalidation (#91729) (#93228) · 2e90936d
      Luke Sandberg authored
      ## Summary
      
      This is a re-application of the HTTP fetch part of #91729. Stacked on
      #93227.
      
      ### Fix fetch to respect HTTP `Cache-Control` headers
      
      Previously, `fetch` results were cached indefinitely, meaning results
      would never be refreshed (unless the cache was invalidated). Now they
      are `session_dependent` with a TTL to ensure we respect HTTP cache
      settings (e.g. Google Fonts with `max-age=86400`).
      
      New two-task pattern:
      - **`fetch_inner`** (NOT `session_dependent`): Performs the HTTP
      request, grabs an `Invalidator` for itself, and returns the response +
      invalidator + absolute deadline. Cached across sessions.
      - **`fetch`** (`network`, `session_dependent`): Reads the cached
      `fetch_inner` result and spawns a timer to invalidate when the TTL
      expires.
      
      On warm cache restore, `fetch` re-executes (session-dependent), reads
      the persisted deadline from `fetch_inner`'s cached result, computes
      remaining TTL, and spawns a timer — no HTTP request unless the TTL has
      already expired. Mid-session, the timer fires and triggers a re-fetch.
      
      Error handling: On fetch failure, `fetch_inner` takes a dependency on
      `Completion::session_dependent()` so transient errors (network down, DNS
      failure) are retried on the next session without busy-looping.
      
      ## Test Plan
      
      3 new integration tests in `turbo-tasks-fetch/tests/fetch.rs`:
      - `ttl_invalidates_within_session` — mock server returns `max-age=1`,
      body changes, verifies re-fetch after TTL
      - `ttl_invalidates_on_session_restore` — fetches with TTL, stops TT,
      waits for expiry, warm restores with new TT, verifies re-fetch
      - `errors_retried_on_session_restore` — server returns 500, stops TT,
      fixes server, warm restores, verifies success
      - Existing 6 fetch tests continue to pass
      
      
      
      <!-- NEXT_JS_LLM_PR -->
      2e90936d