1. 17 Apr, 2026 10 commits
    • nextjs-bot's avatar
      v16.3.0-canary.0 · 430588c2
      nextjs-bot authored
      430588c2
    • Zack Tanner's avatar
      [ci]: fix backport sync script (#92942) · 20e51129
      Zack Tanner authored
      Fixes a few things:
      
      - semver wasn't available because deps weren't being installed
      - Fixed it to compare latest release with latest canary -- it was
      erroneously marking a backport as not a backport.
      
      Test plan:
      Dry run results here:
      https://github.com/vercel/next.js/actions/runs/24571828615/job/71846911677
      
      ```
      should_dispatch=true
      reason=Dispatching canary preminor release because stable release 16.2.4 is ahead of 16.2.1-canary.46
      released_version=16.2.4
      current_canary_version=16.2.1-canary.46
      dispatch_input=false
      auto_dispatch_enabled=true
      ```
      20e51129
    • Josh Story's avatar
      remove flag guarding `unstable_io` (#92923) · 9f2779ec
      Josh Story authored
      removes the flag guarding `unstable_io`.
      
      The API isn't likely to change semantic meaning but could still be
      removed. Do not rely on it extensively yet
      9f2779ec
    • Tobias Koppers's avatar
      Turbopack: optimize SelfTimeTree performance, memory usage, and fix range query boundaries (#92931) · 3d3def23
      Tobias Koppers authored
      ### What?
      
      Optimize the `SelfTimeTree` data structure in the Turbopack trace server
      for better performance and lower memory usage when loading large trace
      files, and fix a correctness bug in range queries.
      
      ### Why?
      
      Two issues were identified:
      
      1. **Performance**: The tree was splitting and rebalancing on every
      insert during bulk loading, and each `distribute_entries` call
      recursively triggered further split checks per entry, creating
      significant overhead.
      
      2. **Correctness**: Range query boundary conditions used exclusive
      comparisons (`<`/`>`), incorrectly excluding entries that touched the
      exact start or end timestamp of the queried range.
      
      ### How?
      
      **Performance optimizations:**
      
      1. **Batch split checks**: Add `insert_without_check` for inserting
      entries without triggering a split check per entry. In
      `distribute_entries`, entries are moved to children using
      `insert_without_check`, and `check_for_split` is called once per child
      after all entries are distributed (rather than once per entry).
      
      2. **Lazy optimization with memory reclamation**: Add an `optimize()`
      method and a `for_each_in_range_optimize()` traversal method that
      distribute and rebalance nodes lazily:
      - `store.optimize()` is called when the reader reaches end-of-data
      (before waiting for more), doing a bulk pass to properly structure the
      tree after initial load. After distributing entries to children, each
      node calls `shrink_to_fit()` on its entries vec to release excess
      capacity.
      - `for_each_in_range_optimize()` distributes and rebalances each node it
      visits, so query paths are progressively optimized during normal use.
      
      3. **Fix `rebalance()` bug**: `check_for_split()` was incorrectly called
      after merging subtrees during rebalance — replaced with
      `distribute_entries()` since the node already has children and needs
      redistribution, not a fresh split.
      
      **Correctness fix:**
      
      All range boundary comparisons in `for_each_in_range`,
      `for_each_in_range_optimize`, and `lookup_range_count` updated from
      exclusive (`<`/`>`) to inclusive (`<=`/`>=`), ensuring entries with
      timestamps exactly equal to the range endpoints are included in results.
      
      <!-- NEXT_JS_LLM_PR -->
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      3d3def23
    • Tobias Koppers's avatar
      turbo-trace-server: reduce allocation overhead when loading large trace files (#92896) · e2e8ba9a
      Tobias Koppers authored
      ### What?
      
      Reduces allocation overhead in `turbo-trace-server` when reading large
      trace files. Measured improvement: **114 MB/s → 156 MB/s** (~37%
      throughput increase) on a 16 GB trace with 46 million spans.
      
      ### Why?
      
      Profiling showed the reader thread spending significant time in heap
      allocation and deallocation during the initial bulk-load phase. The hot
      spots were:
      
      1. `to_string()` / `into_owned()` in `process_internal_row_queue`
      allocating a new `String` for every span name, category, and arg
      key/value — even when the same string (e.g. `"turbo_tasks::function"`)
      appeared in millions of spans.
      2. `Vec<SelfTimeEntry>::push` growing one-at-a-time, triggering many
      `realloc` calls.
      3. `OnceLock<Box<SpanTimeData>>` — inherent to the lazy-init design;
      mitigated by the allocator switch.
      4. `Vec<TraceRow>::push` in the deserialization loop re-growing during
      the initial read.
      5. `process_internal_row` allocating a fresh `Vec` queue on every call
      (one per row).
      6. `Vec<Span>::push` and hash map rehashing in `Store::add_span`.
      7. `into_static()` cloning forcing borrowed `Cow` strings to heap for
      queued rows.
      
      ### How?
      
      **1. mimalloc as global allocator (`main.rs`, `Cargo.toml`)**
      
      Added `turbo-tasks-malloc` as a dependency with a default-on
      `custom_allocator` feature (matching the pattern in `turbopack-cli` and
      `turbopack-nft`). Set `#[global_allocator] static ALLOC: TurboMalloc =
      TurboMalloc`. Also wired `TurboMalloc::thread_stop()` via rayon's
      `exit_handler` so each worker thread returns its mimalloc thread-local
      heap to the global pool on exit.
      
      **2. `RcStrInterning` in `turbo-rcstr`**
      
      New `RcStrInterning` struct backed by `FxHashSet<RcStr>`. Methods:
      `intern(&str)`, `intern_cow(Cow<str>)`, `intern_display(&Display)`.
      Strings shorter than the inline threshold (7 bytes on 64-bit) are
      already zero-allocation inline atoms and skip the set entirely.
      
      **3. `String` → `RcStr` for span fields**
      
      Changed `Span.name`, `Span.category`, and `Span.args` key/value types
      from `String`/`Vec<(String, String)>` to `RcStr`/`Vec<(RcStr, RcStr)>`.
      Same for `SpanNames` and `SpanBottomUpBuilder`. All `to_string()` /
      `into_owned()` calls in `process_internal_row_queue` are replaced with
      `interner.intern()` / `intern_cow()` / `intern_display()` calls on a
      per-`TurbopackFormat` `RcStrInterning`. Repeated names like
      `"turbo_tasks::function"` now share a single allocation via refcount
      bump instead of a fresh heap allocation each time. The `into_static()`
      path for queued rows also benefits: cloning an already-interned `RcStr`
      is a refcount increment, not a string copy.
      
      **4. Capacity hints**
      
      Pre-allocated major collections to avoid repeated reallocation during
      the initial bulk load:
      - `Store::spans`: `Vec::with_capacity(131_072)`
      - `TurbopackFormat::id_mapping`: `with_capacity(131_072)`
      - `TurbopackFormat::outdated_spans`: `with_capacity(8_192)`
      - `TurbopackFormat::queued_rows`: `with_capacity(1_024)`
      - `TurbopackFormat::thread_stacks`, `thread_allocation_counters`:
      `with_capacity(64)`
      - `TurbopackFormat::self_time_started`: `with_capacity(256)`
      
      **5. Reused queue Vec (hot spot #8)**
      
      `TurbopackFormat` now holds `row_queue: Vec<InternalRow<'static>>` as a
      field. `process_internal_row` takes it via `take` and puts it back after
      the loop, retaining the allocated capacity across calls instead of
      allocating a new `Vec::new()` for every row processed.
      
      **6. `TraceFormat::create_reused()` hook (hot spot #4)**
      
      Added an overridable `create_reused()` method to the `TraceFormat`
      trait. `TurbopackFormat` overrides it to return
      `Vec::with_capacity(4_096)`, giving the row deserialization buffer
      reasonable initial capacity to avoid repeated doubling during the
      initial bulk read.
      
      **7. `SelfTimeTree` leaf capacity (hot spot #2)**
      
      New child nodes created at split time get
      `Vec::with_capacity(SPLIT_COUNT / 2)` = 64 entries, matching the
      expected post-split occupancy and avoiding incremental doubling after
      every split.
      
      <!-- NEXT_JS_LLM_PR -->
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      e2e8ba9a
    • Tim Neutkens's avatar
      Perf: Simplify static metadata handling (#92630) · 7873aeaa
      Tim Neutkens authored
      ### What?
      
      Avoid running the generic `fillMetadataSegment(..., true)` path for
      static metadata routes.
      
      This PR adds a dedicated static metadata URL resolver, uses it from the
      existing TypeScript static call sites, and precomputes static metadata
      URLs in Turbopack loader tree codegen instead of waiting on
      `props.params` at runtime.
      
      ### Why?
      
      Static metadata files like `favicon.ico`, `icon.png`, and other static
      metadata images do not need request-time dynamic path interpolation.
      
      The old path reused logic that was designed to also support dynamic
      metadata routes, which meant extra route-regex work even when the final
      URL was already statically known apart from the existing `-` placeholder
      and route-group / parallel-route suffix semantics.
      
      ### How?
      
      - Added a static-only metadata URL helper in `get-metadata-route.ts`
      that:
        - normalizes app path segments,
        - replaces dynamic and catch-all segments with `-`,
      - preserves the existing metadata filename suffix logic for route groups
      and parallel routes.
      - Kept `fillMetadataSegment()` for dynamic metadata routes, but
      short-circuited the `isStatic` path to the new helper.
      - Switched TypeScript static metadata call sites to use the static
      helper directly:
        - build tree display path generation,
        - dev bundler static metadata mapping,
        - webpack static metadata image loader output.
      - Updated Turbopack static metadata codegen to emit the final static URL
      string instead of calling `fillMetadataSegment(..., true)` with `await
      props.params`.
      - Added focused coverage for:
        - root favicon,
        - static metadata under dynamic parents,
        - route-group / parallel-route suffix behavior,
        - unchanged dynamic metadata interpolation.
      
      Closes NEXT-
      Fixes #
      
      <!-- NEXT_JS_LLM_PR -->
      7873aeaa
    • Tobias Koppers's avatar
      Refactor trace server sort to SortMode enum (execution order / value / name) (#92873) · 1de67d8b
      Tobias Koppers authored
      ### What?
      
      Replaces the boolean `sort` flag in the trace server with a `SortMode`
      enum supporting three modes:
      - **`ExecutionOrder`** — no sorting, spans appear in natural/execution
      order (previous `false`)
      - **`Value`** — sort by corrected duration descending (previous `true`)
      - **`Name`** — sort alphabetically by span name (title), then by
      category
      
      ### Why?
      
      The boolean `sort` only allowed toggling duration-based sorting on/off.
      Adding alphabetical sorting by name makes it easier to find duplicate
      spans and locate a specific span by name in the trace viewer. The enum
      is extensible for future sort modes without breaking changes.
      
      ### How?
      
      **Rust (`turbopack-trace-server`):**
      - Added `SortMode { ExecutionOrder, Value, Name }` enum to both `lib.rs`
      (for the query API) and `viewer.rs` (for the WebSocket viewer).
      - `ViewMode` variants changed from `sorted: bool` to `sort_mode:
      SortMode`.
      - `sort_children()` now returns `SortMode` instead of `bool`; all 10
      sorting branches in `viewer.rs` converted from `if/else` to a 3-arm
      `match`.
      - `Name` sort uses `nice_name()` — sorts by title first, then category,
      both ascending.
      - `SpanEventRef::SelfTime` and `SpanGraphEventRef::SelfTime` (which have
      no name) sort as `("", "")` under `Name` mode.
      
      **WebSocket protocol (backward compatible):**
      - `-sorted` suffix → `SortMode::Value` (existing clients unaffected)
      - `-sorted-by-value` suffix → `SortMode::Value`
      - `-sorted-by-name` suffix → `SortMode::Name`
      - no suffix → `SortMode::ExecutionOrder`
      
      **napi bindings (`next-napi-bindings`):**
      - `TraceQueryOptions.sort` changed from `Option<bool>` to
      `Option<String>` (`"value"` | `"name"` | omit).
      
      **TypeScript:**
      - `generated-native.d.ts`: `sort?: 'value' | 'name'`
      - MCP tool schema: `z.enum(['value', 'name']).optional()`
      - CLI: `--sort <mode>` with `.choices(['value', 'name'])` replacing the
      boolean `--sort` flag
      - Tests updated; added new test cases for `sort: 'name'` and `--sort
      name`
      
      <!-- NEXT_JS_LLM_PR -->
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      1de67d8b
    • Tobias Koppers's avatar
      turbopack: reduce EffectStateStorage memory by storing u128 content hashes (#92902) · 68bac2a7
      Tobias Koppers authored
      ### What?
      
      In `turbo-tasks-fs`, the `WriteEffect` and `WriteLinkEffect` structs now
      store a precomputed `u128` xxh3 content hash instead of returning the
      full `ReadRef<PersistedFileContent>` / `ReadRef<LinkContent>` from their
      `Effect::value()` implementations.
      
      The associated type `Effect::Value` is changed from
      `ReadRef<PersistedFileContent>` / `ReadRef<LinkContent>` to `u128` for
      both effect types.
      
      `LinkContent` gains a `DeterministicHash` derive to support hashing via
      `hash_xxh3_hash128`.
      
      ### Why?
      
      `EffectStateStorage` stores the last-applied value for each effect key
      in `last_applied: Mutex<Option<Box<dyn Any + Send + Sync>>>` to enable a
      double-checked deduplication fast path (skip re-writing a file if
      content hasn't changed). In long-running sessions this map grows
      continuously and holds onto a lot of memory because it stores full file
      content (`ReadRef<PersistedFileContent>`) or full link content
      (`ReadRef<LinkContent>`) for every file ever written.
      
      Storing a `u128` hash (16 bytes) instead of the full content
      significantly reduces memory usage while preserving the deduplication
      semantics (hash equality implies content equality with negligible
      collision probability).
      
      ### How?
      
      - Added `content_hash: u128` field to `WriteEffect` and
      `WriteLinkEffect`, computed at construction time using
      `hash_xxh3_hash128` (xxh3 128-bit non-cryptographic hash, already used
      elsewhere in turbopack for content addressing).
      - Changed `Effect::Value = u128` for both effect types; `value()`
      returns `&self.content_hash`.
      - The `EffectStateStorage` now stores `Box<u128>` (24 bytes on the heap)
      per entry instead of `Box<ReadRef<...>>` which held a reference-counted
      pointer into potentially large file content.
      - No changes to `EffectStateStorage`, `Effects::apply()`, or `DynEffect`
      vtable — the existing `Any`/`DynPartialEq` machinery works transparently
      with `u128`.
      
      <!-- NEXT_JS_LLM_PR -->
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      68bac2a7
    • Luke Sandberg's avatar
      rename MagicAny (#92918) · 7b52536c
      Luke Sandberg authored
      s/MagicAny/DynTaskInputs/ essentially
      7b52536c
    • Zack Tanner's avatar
  2. 16 Apr, 2026 16 commits
    • Matt Mastracci's avatar
      [ci] Cache passing test results so CI retries skip them (#92832) · 7c966537
      Matt Mastracci authored
      ## What
      
      Cache each passing test file's result in turbo's remote cache during CI runs. On retry attempts (`GITHUB_RUN_ATTEMPT > 1`), skip tests that already passed.
      
      ## Why
      
      When `retry_test.yml` calls `rerun-failed-jobs`, the entire test shard re-runs from scratch — 20+ minutes to retry one flaky test. With this change, only the failed tests actually re-run on retry.
      
      ## How
      
      - Cache key: `sha256(commit + test file + env fingerprint)` where env fingerprint includes `NEXT_TEST_MODE`, `IS_WEBPACK_TEST`, `IS_TURBOPACK_TEST`, etc.
      - Cache value: `{"passed": true, "time": N}` (~50 bytes per test)
      - On first attempt: all tests run normally, passes are cached
      - On retry: cached passes are skipped, failures re-run. Newly passing tests get cached for further retries
      - All caching gated on `CI` + `TURBO_TOKEN` + `GITHUB_SHA` — zero impact on local runs
      - Uses existing `scripts/turbo-cache.mjs` client, all cache operations are fire-and-forget with try/catch
      7c966537
    • Steven's avatar
      fix(next/image): ensure `images.maximumResponseBody` applies to local images too (#92920) · 4e08dc7b
      Steven authored
      In a previous PR https://github.com/vercel/next.js/pull/88183, we added
      `images.maximumResponseBody` but in only applied to external images.
      
      This PR ensures the same config also applies to internal images.
      4e08dc7b
    • nextjs-bot's avatar
      v16.2.1-canary.46 · f81a1476
      nextjs-bot authored
      f81a1476
    • Benjamin Woodruff's avatar
      CI: Remove dead yarn support from next-stats-action (#92587) · f609c4d4
      Benjamin Woodruff authored
      I guess next.js used `yarn` a long time ago? We don't need to support this anymore.
      f609c4d4
    • Luke Sandberg's avatar
      turbo-tasks: Reduce allocations on cache hits (#92756) · 31a1b635
      Luke Sandberg authored
      ### What?
      
      Reduce heap allocations when turbo-tasks functions get cache hits (~85% of calls).
      
      ### Why?
      
      Every turbo-tasks function call (generated by `#[turbo_tasks::function]`) was boxing its arguments into `Box<dyn MagicAny>` before looking up the task cache. This allocation is wasted on cache hits, which are the overwhelmingly common case.
      
      ### How?
      
      **Deferred boxing via `StackMagicAny` trait object:**
      
      Introduce a `StackMagicAny` trait that abstracts over a stack-resident `Option<T>`:
      
      - `as_ref(&self) -> &dyn MagicAny` — borrow the argument for hash/equality (cache lookup)
      - `take_box(&mut self) -> Box<dyn MagicAny>` — move the value to the heap (zero clones)
      - `as_any_mut(&mut self) -> &mut dyn Any` — downcast to concrete type without boxing
      
      The data flow:
      
      1. **Callsite** (macro-generated): creates `StackMagicAnySlot::new((args...))` on the stack, calls `dynamic_call(..., &mut arg)`
      2. **`dynamic_call`**: checks resolution via `arg.as_ref()`, routes to `native_call` (resolved) or boxes via `arg.take_box()` for `LocalTaskSpec` (unresolved)
      3. **Backend `get_or_create_task_inner`**: does a read-only `raw_get` lookup using `hash_from_components` + `eq_components` with the borrowed `&dyn MagicAny`. On cache hit (~85%), returns immediately — **zero heap allocation**. On cache miss, re-checks under write lock using the same borrowed reference, and only calls `arg.take_box()` in the vacant entry case (true cache miss).
      
      Boxing is now deferred past all of these:
      - **Memory cache hit** — the common case, no allocation at all
      - **Backing storage hit** — found in persistent storage, no allocation needed
      - **Lost race under write lock** — another thread inserted while we upgraded; we use their task_id, still no allocation
      - **Trait method dispatch (no filtering)** — `filter_owned` is now `Option<FilterOwnedArgsFunctor>`; when `None` (the common case where all args are used), the original `&mut dyn StackMagicAny` passes straight through to `dynamic_call` without boxing
      
      **Optimized `filter_owned` for traits:**
      
      When trait methods *do* need argument filtering (unused `_`-prefixed parameters), the old path did `take_box()` → `downcast_args_owned()` → dereference → repack. This is an unnecessary heap round-trip. The new `downcast_stack_args_owned()` function uses `as_any_mut()` to downcast directly to `&mut StackMagicAnySlot<T>` and calls `take()` on the inner `Option`, skipping the intermediate `Box` entirely.
      
      **Additional changes:**
      - `Backend::get_or_create_*_task` now takes decomposed parameters (`native_fn`, `this`, `&mut dyn StackMagicAny`) instead of a pre-constructed `CachedTaskType`
      - Persistent and transient task creation merged into a shared `get_or_create_task_inner(transient: bool)`
      - `connect_child` uses eagerly-set `persistent_task_type` from `initialize_new_task`
      - `OwnedMagicAny` adapter wraps already-boxed args (from async resolution tasks) to fit the `StackMagicAny` interface
      - Both `dynamic_call` and `trait_call` take `&mut dyn StackMagicAny` (trait dispatch also benefits)
      - `CachedTaskType::hash_encode` now delegates to `hash_encode_components` (deduplicated)
      - Removed `try_native_call`, `native_call_if_consistent`, `try_get_or_create_*` — the deferred boxing approach subsumes these
      
      ### Binary size
      
      Binary size is neutral (linux-x86_64, `--release`, stripped + gzipped: 30.9 MB on both canary and this branch).
      
      ### Overhead benchmark (turbo-tasks-backend, median, lower is better)
      
      Measured on an isolated Firecracker microVM (linux-x86_64). Variance is nontrivial on this environment, but the direction is consistently positive across all turbo-tasks benchmarks.
      
      | Benchmark | Canary | This PR | Delta |
      |---|---|---|---|
      | `turbo-cached-same-keys/1` | 512.6 ns | 490.2 ns | -4.4% |
      | `turbo-cached-same-keys/10` | 493.4 ns | 483.8 ns | -2.0% |
      | `turbo-cached-same-keys/100` | 502.1 ns | 484.9 ns | -3.4% |
      | `turbo-cached-same-keys/1000` | 1.31 µs | 774.2 ns | -41.0% |
      | `turbo-cached-different-keys/1` | 1.02 µs | 1.00 µs | -1.4% |
      | `turbo-cached-different-keys/10` | 1.13 µs | 1.11 µs | -1.8% |
      | `turbo-cached-different-keys/100` | 1.29 µs | 1.24 µs | -3.8% |
      | `turbo-cached-different-keys/1000` | 2.37 µs | 2.32 µs | -2.5% |
      | `turbo-uncached/1` | 23.43 µs | 20.47 µs | -12.6% |
      | `turbo-uncached/10` | 32.23 µs | 29.71 µs | -7.8% |
      | `turbo-uncached/100` | 126.01 µs | 124.95 µs | -0.8% |
      | `turbo-uncached/1000` | 1.079 ms | 1.048 ms | -2.9% |
      | `turbo-uncached-parallel/1` | 6.16 µs | 5.67 µs | -8.0% |
      | `turbo-uncached-parallel/10` | 5.47 µs | 5.12 µs | -6.4% |
      | `turbo-uncached-parallel/100` | 14.65 µs | 14.55 µs | -0.7% |
      | `turbo-uncached-parallel/1000` | 132.09 µs | 129.13 µs | -2.2% |
      
      <!-- NEXT_JS_LLM_PR -->
      31a1b635
    • Sebastian "Sebbie" Silbermann's avatar
    • Matt Mastracci's avatar
      [ci] Skip Playwright system deps install on subsequent self-hosted runs (#92893) · 30b305e2
      Matt Mastracci authored
      ## What
      
      Use a stamp file to skip `playwright install --with-deps` after the
      first successful run on a self-hosted runner.
      
      ## Why
      
      `--with-deps` runs `sudo apt-get install` for Playwright's system
      dependencies every time, even when they're already installed. On
      self-hosted runners this takes ~10s of no-op `apt-get` checking. After
      the first install, subsequent runs only need `playwright install` (which
      downloads browser binaries if the version changed, and is instant when
      cached).
      
      The assumption is that on most of the runners, `playwright` will be the
      same version on each, and the deps that are installed are compatible
      within each version.
      
      Most of the time this step is ~3s, when everything is healthy and
      up-to-date.
      
      Occasionally these steps will hiccup on builds when we're already really
      got these deps installed so this chops a little bit off each one. This
      also helps when APT mirrors go down.
      
      ## How
      
      - First run: `playwright install --with-deps` + write
      `~/.cache/playwright-deps-installed`
      - Subsequent runs: stamp file exists, run `playwright install` without
      `--with-deps`
      - The stamp persists on self-hosted runners across jobs
      - Fresh/reimaged runners don't have the stamp, so they get the full
      install
      - The cache is ignored if the most recently installed playwright version
      doesn't match
      
      <!-- NEXT_JS_LLM_PR -->
      30b305e2
    • Benjamin Woodruff's avatar
      Turbopack: Use an async lock in the filesystem watcher (#92906) · 844af6c9
      Benjamin Woodruff authored
      We know that we have a lot of lock contention when creating watchers, because many watchers are often set up at roughly the same time near the start of building a route. Internal discussion thread: https://vercel.slack.com/archives/C09R44U5HQW/p1776271283799709
      
      @lukesandberg's suggestion was that the lock is held over syscalls and file IO, so it's possible that this could starve the Tokio worker threads, so we should use an async lock so that we can yield back the worker thread.
      
      Because this would simply unblock *other* work, and because this codepath is only used in `dev`, there's no sane way to benchmark or measure this, so we'll just have to hope and pray it's an improvement.
      
      This PR is entirely AI-generated.
      844af6c9
    • Andrew Clark's avatar
      Enable prefetchInlining by default (#92863) · b301d3cf
      Andrew Clark authored
      Flips the `experimental.prefetchInlining` default from `false` to
      `true`. This is the first step toward removing the flag entirely.
      
      Tests that explicitly set `prefetchInlining: true` have been cleaned up
      since they now match the default. Any CI failures from this PR will be
      addressed in follow-up PRs by temporarily opting out individual tests
      with `prefetchInlining: false` until they are migrated.
      
      <!-- NEXT_JS_LLM_PR -->
      b301d3cf
    • Aurora Scharff's avatar
      [devtools] Preserve full code frames in browser overlay (#92621) · ce33784b
      Aurora Scharff authored
      Summary:
      - stop devtools code frames from inheriting the server terminal width
      - allow the overlay code frame to scroll horizontally instead of
      clipping content
      
      Problem:
      The browser error overlay requests originalCodeFrame from the dev
      server. That code frame was being generated with process.stdout.columns
      as the default max width, so if the dev server terminal was narrow the
      browser overlay received an already-truncated frame with collapsed
      ellipsis segments.
      
      Fix:
      - pass a large explicit maxWidth when generating devtools code frames on
      the server
      - switch the overlay code frame container to horizontal scrolling
      instead of hidden overflow
      
      Result:
      The overlay no longer changes based on the terminal size running next
      dev, and long source lines remain inspectable in the browser.
      
      Before:
      <img width="1350" height="1076" alt="Google Chrome 2026-04-10 17 51 17"
      src="https://github.com/user-attachments/assets/197fee70-3e11-4b90-ac4b-aa878578f961"
      />
      
      After:
      <img width="1260" height="1194" alt="CleanShot 2026-04-10 at 18 16
      48@2x"
      src="https://github.com/user-attachments/assets/86b7271c-6e63-4e9f-b7b8-608a3f54beda"
      />
      
      ---------
      Co-authored-by: 's avatarSebastian "Sebbie" Silbermann <sebastian.silbermann@vercel.com>
      ce33784b
    • Hendrik Liebau's avatar
      Fix dev mode hydration failure when page is served from HTTP cache (#92892) · 67f4f5ed
      Hendrik Liebau authored
      PR #88182 introduced an experimental option to use `Cache-Control:
      no-cache` instead of `no-store` in dev mode, and PR #91503 made it the
      default. With `no-cache`, browsers may serve the page from HTTP cache on
      back-forward navigation or tab duplication. The HTML, including the
      inline RSC payload, is restored from cache and all scripts re-execute.
      
      In dev mode, React's Flight client uses a debug channel (a
      WebSocket-backed stream delivering component debug info) that adds
      dependencies to model chunk initialization. On a fresh page load, the
      WebSocket delivers this data and the dependencies resolve normally. On
      HTTP cache restore, however, the bootstrap script re-executes and
      creates a new debug channel stream, but the WebSocket doesn't re-send
      debug data for the cached payload's request ID. The debug dependencies
      are never fulfilled, blocking the entire model tree from initializing,
      so `hydrateRoot` is never called and the page loses all interactivity.
      
      This is dev-only — production builds have no debug channel, so there are
      no stuck dependencies and no issue.
      
      The fix buffers debug channel chunks in memory as they flow through the
      `TransformStream` in `getOrCreateDebugChannelReadableWriterPair`. Once
      all chunks have been received, the buffer is eagerly persisted to
      `sessionStorage`. When the page detects it was served from HTTP cache
      (via `PerformanceNavigationTiming.transferSize === 0`),
      `createDebugChannel` restores the debug data from `sessionStorage` and
      replays it as a synthetic `ReadableStream` instead of expecting it from
      the WebSocket. If the restore fails (e.g., quota exceeded during the
      earlier write, or the entry was overwritten by another page), the page
      falls back to `location.reload()` to get a fresh page from the server.
      
      A regression test is included that navigates to an external page and
      verifies interactivity is preserved after clicking the browser back
      button. Tab duplication (which triggers the same HTTP cache restore)
      cannot be simulated in Playwright and was verified manually.
      
      fixes #92238
      fixes #91982
      fixes #92687
      67f4f5ed
    • Tobias Koppers's avatar
      turbo-tasks: add info_span for blocking waits during task restore (#92878) · 4dd1fcb1
      Tobias Koppers authored
      ### What?
      
      Adds a `tracing::info_span!("blocking")` around `listener.wait()` calls
      in `ExecuteContextImpl::task()` when a task is still being restored from
      backing storage.
      
      ### Why?
      
      When a task is locked for restoration by another thread, the current
      thread spins in a loop and calls `listener.wait()` until notified. CPU
      time accounting treats this waiting time as active CPU usage, which
      skews profiling results.
      
      By wrapping the wait in a `"blocking"` span, the tracing infrastructure
      can correctly exclude this idle blocking time from CPU time — ensuring
      CPU metrics reflect actual computation rather than time spent waiting
      for another thread to finish restoring a task.
      
      ### How?
      
      Import `tracing::info_span` and enter a `"blocking"` span immediately
      before `listener.wait()` in the restore-wait loop in
      `turbopack/crates/turbo-tasks-backend/src/backend/operation/mod.rs`. The
      span is dropped when the wait returns (or when the loop continues to
      re-check the condition).
      
      <!-- NEXT_JS_LLM_PR -->
      4dd1fcb1
    • Niklas Mischkulnig's avatar
      Support type cast expressions in page static info extractor (#92837) · a2265319
      Niklas Mischkulnig authored
      So that
      ```ts
      export const runtime = "node" as const
      export const runtime = "node" as string
      export const runtime = "node" satisfies string // was already working
      ```
      works
      a2265319
    • nextjs-bot's avatar
      v16.2.1-canary.45 · 40a4e666
      nextjs-bot authored
      40a4e666
    • Niklas Mischkulnig's avatar
    • Tobias Koppers's avatar
      turbopack: cache TransformPlugin in narrow-scoped turbo-tasks functions (#92842) · f4972228
      Tobias Koppers authored
      ### What?
      
      Refactor all usages of
      `EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(...) as _))`
      across `next-core` and `turbopack-tests` so that `TransformPlugin` cells
      are created inside dedicated `#[turbo_tasks::function]` functions rather
      than inline at call sites.
      
      Additionally:
      - Introduce a `JsonValue` newtype wrapping `serde_json::Value` that
      implements `TaskInput`, enabling the SWC wasm plugin list to be passed
      through a turbo-tasks function boundary and properly cached.
      - Replace the `bool` roundtrip in `next_strip_page_exports` with an
      `ExportFilterInput` enum that derives `TaskInput`, mirroring
      `ExportFilter` exhaustively (so a new upstream variant is a compile
      error, not a silent fallback).
      - Derive `TaskInput` on `ActionsTransform` and pass it directly to the
      cached function instead of converting to `is_server: bool` at the call
      site.
      - Replace all `.expect("... config must exist")` panics in option-gated
      plugin functions (`emotion`, `styled_components`,
      `react_remove_properties`, `remove_console`, `relay`) with
      `.context(...)?` for proper error propagation.
      - Add `// TODO: use get_ecma_transform_rule instead` comments to the ~10
      transform functions that manually inline the same `ModuleRule::new` +
      `ExtendEcmascriptTransforms` pattern that `get_ecma_transform_rule`
      abstracts.
      
      ### Why?
      
      `TransformPlugin` is not serializable and not comparable. When a
      `TransformPlugin` is `cell`ed inline (i.e.
      `ResolvedVc::cell(Box::new(...) as _)`) inside a turbo-tasks function, a
      new cell is created on every invocation of the enclosing function,
      because the framework has no way to detect that the value is the same as
      before. This causes every task that depends on the `TransformPlugin`
      cell to be invalidated unnecessarily.
      
      By moving the `Vc::cell(...)` call into its own narrow-scoped
      `#[turbo_tasks::function]`, turbo-tasks can cache the cell by the
      function's inputs. If the inputs haven't changed, the function won't
      re-run, the existing cell is reused, and downstream tasks are not
      invalidated.
      
      ### How?
      
      Each inline `ResolvedVc::cell(Box::new(SomeTransformer { ... }) as _)`
      is replaced with:
      
      ```rust
      some_transform_plugin(args).to_resolved().await?
      
      #[turbo_tasks::function]
      fn some_transform_plugin(args: ...) -> Vc<TransformPlugin> {
          Vc::cell(Box::new(SomeTransformer { ... }) as Box<dyn CustomTransformer + Send + Sync>)
      }
      ```
      
      Where a cached function needs to store a `ResolvedVc` in the resulting
      transformer struct, the parameter is declared as `ResolvedVc<T>`
      directly in the `#[turbo_tasks::function]` signature. The turbo_tasks
      macro rewrites `ResolvedVc<T>` → `Vc<T>` in the external call-site
      signature, and the call site passes a dereferenced `*resolved_vc`. This
      avoids a redundant `.to_resolved().await?` inside the function body.
      
      For the SWC wasm plugin case, `serde_json::Value` (used for per-plugin
      config) doesn't implement `Hash` or `TaskInput`. A `JsonValue` newtype
      is introduced with:
      - `#[bincode(with = "turbo_bincode::serde_self_describing")]` for
      serialization
      - Manual `Hash` impl that hashes the JSON string representation
      - Manual `TaskInput` impl (`is_transient = false` since the type
      contains no `Vc`s)
      
      <!-- NEXT_JS_LLM_PR -->
      
      ---------
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      Co-authored-by: 's avatarNiklas Mischkulnig <mischnic@users.noreply.github.com>
      f4972228
  3. 15 Apr, 2026 14 commits
    • Zack Tanner's avatar
      [ci]: add workflow to bump canary after backport (#92801) · a584bb87
      Zack Tanner authored
      This adds an automated path to keep canary semver-ahead after a
      successful stable backport publish.
      
      Today, a backport release can produce a stable version that is newer
      than the current canary version, which creates confusing version
      ordering for tooling. This change adds a follow-up workflow that
      evaluates completed backport publishes and, when appropriate, triggers a
      canary preminor release on canary.
      
      The `Sync Canary After Backport Release` workflow evaluates whether a
      completed `build-and-deploy` run should trigger a canary sync.
      
      The evaluation only triggers when:
      - the upstream `Potentially publish release` job succeeded
      - the head commit is a stable release commit
      - the published stable version is a backport relative to next@latest
      - the current canary version is not already semver-ahead
      - there is not already a queued or in-progress Trigger Release run on
      canary
      
      When all checks pass, the workflow dispatches trigger_release.yml on
      canary with:
      - releaseType=canary
      - semverType=minor
      - force=true
      
      (This is currently gated behind an env flag so we can dry-run it)
      a584bb87
    • Benjamin Woodruff's avatar
      Turbopack: Use lld again on ARM64 glibc Linux (#92860) · f381e3e5
      Benjamin Woodruff authored
      `lld` is much faster than the default gnu `ld` linker on most Linux
      systems.
      
      Timeline:
      - https://github.com/vercel/next.js/pull/91477 removed these flags as
      part of cleanup because they're now default on x86-64 glibc linux.
      However, they are not default on arm64.
      - https://github.com/vercel/next.js/pull/91799 removed these flags from
      musl, and lost the comment explaining reason for the `gnu-lld-cc`
      option.
      
      Without this change, doing a dev build of a trivial change to
      `crates/next-napi-bindings/src/lib.rs` can take over a minute.
      
      I tested this by looking at htop near the end of a build and observing
      `lld` instead of `ld`.
      f381e3e5
    • nextjs-bot's avatar
      v16.2.1-canary.44 · 852c145b
      nextjs-bot authored
      852c145b
    • Mukunda Rao Katta's avatar
      docs: add documentation for no-typos ESLint rule (#92809) · 219c0bce
      Mukunda Rao Katta authored
      ## Summary
      
      The `@next/next/no-typos` rule ships in `@next/eslint-plugin-next` but has no corresponding page under `errors/`, so users who click through from ESLint config inspectors (or from other rule-docs links) hit a 404.
      
      This adds `errors/no-typos.mdx` describing:
      - What the rule catches (`getStaticProps` / `getStaticPaths` / `getServerSideProps`)
      - A standard before/after example
      - A **casing** example (since the rule uses a 1-char edit-distance threshold — casing typos like `getServerSideprops` also trip it)
      
      ## Context
      
      This re-attempts #89436 (closed, not merged) with @lukesandberg's two review comments applied:
      
      1. **Title** shortened from *"No typos in Next.js data fetching functions"* → **"No Typos"**, matching other sibling rule docs in `errors/`.
      2. **Casing example** now actually contains a casing error (`getServerSideprops`); the previous version listed `getServerSideProps` as "incorrect casing", which had no casing error.
      
      Fixes #67342
      
      ## Test plan
      
      - [x] File lives under `errors/` alongside sibling rule docs (`no-document-import-in-page.mdx`, `no-unwanted-polyfillio.mdx`, etc.)
      - [x] Frontmatter + heading structure matches sibling docs
      - [x] Code fences use the same `filename=...` convention as sibling docs
      - [x] No manifest file under `errors/` — sibling additions (e.g. `no-unwanted-polyfillio.mdx`) did not touch an index
      219c0bce
    • Joseph's avatar
      docs: restructure instant nav guide for clarity (#92684) · 845485a9
      Joseph authored
      Reordered DevTools section, improved code examples and db queries, added
      component breakdowns in the fix section, editorial improvements
      throughout.
      845485a9
    • Hendrik Liebau's avatar
      Warn for non-deterministic `"use cache"` args during final prerender (#92820) · 662c6d57
      Hendrik Liebau authored
      When a `"use cache"` function receives arguments that differ between the
      cache warming phase and the final prerender, the cache key changes and
      the Resume Data Cache (RDC) entry from the prospective prerender is
      missed.
      
      This can happen for various reasons, for example when concurrent async
      operations push results into a shared array in non-deterministic order,
      and that array is then passed as an argument to a cached function.
      
      Without a `cacheSignal` to keep the render alive, the final prerender
      aborts the cache entry generation, producing an incomplete RSC stream
      that causes "Connection closed" errors.
      
      This change detects that scenario (an RDC miss during the final
      prerender where `cacheSignal` is `null`) and returns a hanging promise
      instead of generating a broken cache entry. A warning is logged to help
      developers identify the non-deterministic arguments. By making the
      cached function a dynamic hole rather than erroring, the prerender can
      still complete and produce at least a partial shell if there is a
      Suspense boundary above. This affects both on-demand prerendering and
      runtime prefetching.
      
      To avoid false positives, cache keys that were intentionally skipped
      during the prospective prerender (e.g. because the cached function
      accessed fallback params) are tracked in a `dynamicCacheKeys` set on the
      RDC. During the final prerender, a known dynamic key is returned as a
      hanging promise early without logging a warning. This also serves as a
      performance optimization, since it avoids trying to regenerate the
      entry. This set is intentionally not serialized, as cache misses for
      dynamic keys should generate fresh entries during the resume at request
      time.
      662c6d57
    • Niklas Mischkulnig's avatar
      Turbopack: move assignment_scopes computation into ImportMap (#92835) · bf4de72c
      Niklas Mischkulnig authored
      I'm moving all of the export-related logic into `EvalContext` (and thus `ImportMap`) so that `VarGraph` is only needed for computing the references, and not the exports.
      
      The change in the snapshots is 
      ```diff
      -*anonymous function 170* (const after eval) = (...) => [file]
      +*anonymous function 170* = (...) => [file]
      ```
      which is fine, since computing the "is reassigned" data for something that isn't actually a variable was non-sensical anyway.
      bf4de72c
    • Vercel Release Bot's avatar
      Update Rspack development test manifest (#92673) · 5fc848b3
      Vercel Release Bot authored
      This auto-generated PR updates the development integration test manifest used when testing Rspack.
      5fc848b3
    • Vercel Release Bot's avatar
      Update Rspack production test manifest (#92674) · ec150fb7
      Vercel Release Bot authored
      This auto-generated PR updates the production integration test manifest used when testing Rspack.
      ec150fb7
    • Niklas Mischkulnig's avatar
      Turbopack: analyzer improvement followups (#92834) · 69b9c4bc
      Niklas Mischkulnig authored
      - defer computing the `EsmAssetReference` issue source from the `Span`. means that we have to pass less arguments around as well
      - make `mangle("default export")` a "constant" and use that everywhere instead
      
      Some snapshots changed, because the test runner had `source: None`, so now there are some duplicate module references in there because the new always-set `span` field forces it to be a new entry in the `data.references` hashmap.
      69b9c4bc
    • Niklas Mischkulnig's avatar
      Turbopack: remove StarImportAnalyzer (#92830) · 45e5ad76
      Niklas Mischkulnig authored
      There is actually no reason to compute `full_star_imports` before the `visit_with(&mut analyzer)`: it's only used later on by references/mod.rs which calls `should_import_all`.
      So we can just do it in the same traversal
      45e5ad76
    • Matt Mastracci's avatar
      [ci] Skip sccache on Windows runners (#92847) · 92b0789b
      Matt Mastracci authored
      ## What
      
      Skip the sccache setup step when running on Windows.
      
      ## Why
      
      sccache is currently not "winning" with cache hits when building on
      Windows which is increasing the size of the turborepo cache. In
      addition, sccache servers appear to be lingering on some of the windows
      runners.
      92b0789b
    • Tim Neutkens's avatar
      Revert "Node.js streams: Add forkpoint for prerenderToStream" (#92845) · c5ddf825
      Tim Neutkens authored
      Reverts vercel/next.js#92513
      c5ddf825
    • Tobias Koppers's avatar
      fix(trace-server): default MCP port to --port + 1 to avoid conflicts (#92831) · 28f96a4f
      Tobias Koppers authored
      ### What?
      
      When `--mcp-port` is not explicitly provided to `next internal trace`,
      the MCP HTTP server now defaults to `--port + 1` (the WebSocket port
      plus one) instead of the hardcoded value `5748`.
      
      The `DEFAULT_WS_PORT` remains `5747`, so when neither flag is passed the
      behavior is unchanged: WS=5747, MCP=5748.
      
      ### Why?
      
      Starting the trace server twice with different `--port` values (e.g. to
      analyze two trace files simultaneously) caused both instances to attempt
      to bind the same hardcoded MCP port `5748`:
      
      ```
      Error: MCP port 5748 is already in use. Use --mcp-port to specify a different port.
      ```
      
      Making the MCP port default relative to the WS port means each
      invocation with a unique `--port` automatically gets a unique
      `--mcp-port` without any extra flags.
      
      ### How?
      
      In `startTurboTraceServerCli`, changed:
      ```ts
      const httpPort = mcpPort ?? DEFAULT_MCP_PORT  // always 5748
      ```
      to:
      ```ts
      const httpPort = mcpPort ?? wsPort + 1        // e.g. 5748, 6001, 7001, …
      ```
      
      The now-unused `DEFAULT_MCP_PORT` constant in `turbo-trace-server.ts`
      was removed. The identical constant in `query-trace.ts` is kept — it is
      the client-side default for *connecting* to an MCP server and `5748`
      remains a sensible default there.
      
      The `--mcp-port` help text was updated to reflect the dynamic default.
      
      <!-- NEXT_JS_LLM_PR -->
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarClaude <noreply@anthropic.com>
      28f96a4f