- 18 Apr, 2026 3 commits
-
-
nextjs-bot authored
-
Tobias Koppers authored
### What? Adds a new "Native Binary" section to the `Stats from current PR` comment posted by the `generate-pull-request-stats` GitHub Action. The section reports the size of the SWC native binary (`packages/next-swc/native/*.node`) built for the PR and the change relative to the latest value recorded on `canary`. Example row: > | Metric | Canary | PR | Change | Trend | > |:-------|-------:|---:|-------:|:-----:| > | SWC Binary Size | 113 MB | 121 MB |
🔴 +7.34 MB (+6%) | ▁▃▅▇█ | ### Why? The `.node` binary is a sizable, user-facing artifact (it ships with `next`). Today there's no visibility on its size in PRs, so regressions from Rust/Cargo changes are easy to miss. Surfacing the size (and a diff vs. canary) in the existing stats comment gives immediate feedback on any change that affects the binary. ### How? - **Measurement (`.github/actions/next-stats-action/src/run/index.js`):** After the action copies the pre-built native binary into the working dirs, sum the size of every `*.node` file under the action's `native/` directory and store it as `General.swcBinarySize` on both the canary and PR stat sets. - **Canary baseline via KV history (`.github/actions/next-stats-action/src/add-comment.js`):** The workflow downloads a single pre-built binary and copies it into both the canary and PR checkouts, so an in-run diff would always be zero. Instead, for PR runs we override `mainRepoStats.General.swcBinarySize` with the most recent `swcBinarySize` from the Vercel KV history (the same store already used for other canary metrics). Canary runs keep the measured value, and the existing persistence path (`saveToHistory` / `General`) writes it back so future PRs see an updated baseline. If no history exists yet, the Canary column renders `N/A` and no change is shown. - **Rendering:** New `generateNativeBinarySection` emits a `<details>`-wrapped section styled like Bundle Sizes / All Metrics, rendered right after the Bundle Sizes block. It reuses `prettify`, `formatChange`, and `generateTrendBar` so formatting, thresholds, and sparklines are consistent with the rest of the comment. A tight threshold entry (`swcBinarySize: { absoluteMin: 10 KB, percentMin: 0.5%, percentOnly: 0.05% }`) is added so meaningful movement is flagged while tiny determinism noise is ignored. - **Top-line summary:** Because `swcBinarySize` lives on `General`, the existing `generateChangeSummary` automatically promotes significant changes into the headline regression/improvement table at the top of the comment, using the label `SWC Binary Size`. - **Sharded runs:** The workflow runs two sharded jobs (Webpack and Turbopack). The binary is bundler-independent, so both shards report the same value; `aggregate-results.js` merges `General` via `Object.assign`, which is correct here (last-writer-wins on an identical value). No workflow changes are required — the existing `pull_request_stats.yml` already downloads the `next-swc-binary` artifact and copies it into the action's `native/` directory. ### Verification Smoke-tested `add-comment.js` locally with `LOCAL_STATS=1` in two scenarios: - No KV history configured → Canary column renders `N/A`, PR value renders, Change is `-`, section still shown. - Mocked KV history containing prior `swcBinarySize` values → full diff rendered in both the Native Binary section and the top-level significance summary, with a sparkline of the last 5 historical entries. Closes NEXT- <!-- NEXT_JS_LLM_PR --> --------- Co-authored-by:Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
Tobias Koppers authored
### What? Improve the trace span attributes for "make root node" operations in the turbo-tasks backend. Instead of recording only the raw `task_id`, the spans now include a human-readable task description (type name + task ID) via `debug_get_task_description`. ### Why? When profiling or debugging with tracing tools, raw task IDs are opaque and require additional lookups to understand which task is being processed. Including a human-readable task description (e.g. `TaskId(42) MyFunction(args...)`) makes traces immediately actionable. Two spans were affected: - `"make root node for strongly consistent read"` in `backend/mod.rs` - `"make root node for removing collectible"` in `backend/operation/update_collectible.rs` ### How? - Added `debug_get_task_description` method to the `ExecuteContext` trait in `operation/mod.rs` - Implemented it on `ExecuteContextImpl` by delegating to the existing `backend.debug_get_task_description` method (already used in other tracing spans) - Replaced `%task_id` (which formats only the ID) with `task = self.debug_get_task_description(task_id)` / `task = ctx.debug_get_task_description(task_id)` in both span definitions <!-- NEXT_JS_LLM_PR -->
-
- 17 Apr, 2026 19 commits
-
-
nextjs-bot authored
-
Joseph authored
Still drafting this one. We want to show good patterns, and effects are often a last resource. We favor here resetting in an event handler.
-
Josh Story authored
CI is failing on a modal not showing up after navigation. It looks like a timing bug. This adds retry to wait for the UI to show up
-
Josh Story authored
prefetching is now controlled with the prefetch export and this option is inert on the instant export. this removes the prefetch option as a valid property on the instant config type. also updates the ts plugin for this export and adds the definition for the previously landed prefetch export
-
Matt Mastracci authored
## What - Use `cargo binstall` instead of `cargo install` for Rust tools in the Docker image - Download pre-built vercel/sccache from GitHub releases instead of compiling from git ## Why `cargo install` compiles from source which is slow on cache miss. `cargo binstall` downloads pre-built binaries in seconds. The vercel/sccache fork now publishes release binaries, eliminating the need for the `build-sccache` turbo task (~2-3 min compile). ## Changes **Dockerfile:** - Install cargo-binstall at pinned version (1.18.1), use it for cargo-rustflags - Remove sccache from Docker image (not needed inside container) **CI sccache:** - Download pre-built binary from `vercel/sccache` GitHub releases (~11MB) - Cache in `~/.cache/sccache-<version>` on self-hosted runners - Delete `scripts/build-sccache.js`, remove turbo task and package.json entry - `scripts/sccache-version` now contains just the release tag <!-- NEXT_JS_LLM_PR -->
-
Aurora Scharff authored
### What? Redesigns the blocking-route error overlay for instant navigation errors with a distinct "Instant" overlay path, visual technique cards, and updated error wording framed around navigation impact. ### Why? The current overlay dumps every possible cause and fix in one block of text. The new design is friendlier — amber "Instant" badge, a short headline framed around navigation, and responsive code snippet cards showing each fix pattern. ### Demo - **Runtime template** (e.g. `cookies()`): https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/26-cookies-ssr-no-instant - **Dynamic template** (e.g. uncached `fetch`): https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/27-fetch-ssr-no-instant ### How? **Overlay** - New early-return path in `errors.tsx` for `blocking-route` errors without refinement — renders `InstantRuntimeError` with CodeFrame → description → technique cards → CallStack → ErrorCause - `InstantGuidance` component with responsive CSS grid of fix technique cards (3 per variant) - Color-coded cards with colored borders and matching highlight text (blue, purple, red) - "Make route params static" card (runtime only) has a dashed border indicating it's conditional **Build & CLI messages** - Build output messages extracted into `blocking-route-messages.ts` and deduplicated across `dynamic-rendering.ts` - `dynamicOrRuntimeBodyMessage` added for build-time static validation where the specific cause can't be pinpointed — lists all APIs (`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, `connection()`) - `isRuntimeVariant()` replaces the old `includes('cookies()')` heuristic which broke because both templates mention `cookies()` - `logBuildDebugHint()` extracted and shared between `logDisallowedDynamicError` and instant validation — adds "run `next dev`" and "`next build --debug-prerender`" hints to instant validation build output Results: <img width="2094" height="1478" alt="Google Chrome 2026-04-17 16 37 00" src="https://github.com/user-attachments/assets/04f126c5-250c-4e6e-bad0-d6960496cd13" /> <img width="1978" height="1512" alt="Google Chrome 2026-04-17 16 36 37" src="https://github.com/user-attachments/assets/46a502d8-9500-4055-814b-3efb739949db" /> --------- Co-authored-by:
Janka Uryga <lolzatu2@gmail.com>
-
Zack Tanner authored
With the new `partialFallbacks` heuristic, routes that weren't part of `generateStaticParams` will now upgrade their shells to include the params as if they had been in `generateStaticParams`, but only when the page with the unknown param was lazily visited. This tweaks the heuristic to allow segment prefetches to also trigger the upgrade behavior. This will ensure subsequent clients, when prefetching the upgraded route, will receive the entry with params filled in rather than showing the generic fallback. In a subsequent PR, we'll make it so that the requesting client that triggers the upgrade path can also benefit from the params being upgraded, as the client router currently has no awareness that a background revalidation completed.
-
Hendrik Liebau authored
With #71286, we implemented deduping of cache entries under certain circumstances. For example, the following constructed example was fixed with the PR: ```js async function getCachedRandom() { 'use cache' return Math.random() } const rand1 = await getCachedRandom() const rand2 = await getCachedRandom() assert(rand1 === rand2) ``` However, this implementation relied on awaiting the two calls sequentially. When rendering components, this can usually not be guaranteed. E.g. the following example was not properly deduped: ```jsx async function Cached() { 'use cache' return <p>{Math.random()}</p> } export default function Page() { return ( <> <Cached /> <Cached /> </> ) } ``` This did render the same value, but only because we triggered two render passes, and the last cached value was used for both elements in the final render pass. But during the first render pass, the `Cached` function was called twice, and the cache entry was also set twice. With #75786, we also fixed the render scenario by wrapping the cached function in `React.cache`. This however did not work for route handlers. E.g. the first example rewritten as follows, and used in a route handler, still wouldn't be deduped: ```js const [rand1, rand2] = await Promise.all([ getCachedRandom(), getCachedRandom(), ]) ``` Furthermore, with this solution, nested cached functions could not be deduped across different outer cache scopes. This is because each cache scope creates its own `React.cache` scope. Example: ```jsx async function Inner() { 'use cache' return <p>{Math.random()}</p> } async function Outer1() { 'use cache' return <Inner /> } async function Outer2() { 'use cache' return <Inner /> } export default function Page() { return ( <> <Outer1 /> <Outer2 /> </> ) } ``` This PR introduces two-layer invocation tracking that deduplicates these cases without changing how cache handlers are implemented. Only the first invocation (the "leader") performs the cache handler lookup and generation. Subsequent invocations ("joiners") tee the leader's result stream instead. The deduplication scope starts after the Resume Data Cache (RDC) lookup and before the cache handler `get`. The RDC phase is excluded because it throws synchronous errors (dynamic usage errors) that need individual stack traces per call site, and RDC lookups are local with no network savings from deduplication. Intra-request deduplication is stored on the `WorkStore` and keyed by `serializedCacheKey` (the coarse key, which is safe because root params are identical within a single request). Cross-request deduplication is stored in a module-scope map keyed by `cacheHandlerKey`, which may include root params on the warm path. Cross-request joiners must await metadata for root param verification before forking the stream. If the key mismatches (different root params), the joiner retries with a recomputed key. Because metadata is checked before `fork()` is called, a mismatched joiner never consumes a stream from the wrong entry. Stream tee-ing is lazy via the `SharedCacheEntry` class: the leader calls `fork()` to get its copy, and each joiner calls `fork()` on demand. If no joiners exist, only one tee occurs. The `SharedCacheResult` discriminated union wraps either a `SharedCacheEntry` (for the cached case) or a hanging promise (for `prerender-dynamic`). Each invocation still decodes the stream independently via `createFromReadableStream` with its own `temporaryReferences`, because sharing the decoded result would cause cache poisoning when components receive different non-serializable props (e.g. `children`). Admittedly, this adds significant complexity to the `cache()` function. Two classes help keep it manageable: - `SharedCacheEntry` encapsulates stream ownership and lazy tee-ing so that call sites don't need to reason about which streams have been consumed or need cloning. - `ResolvableSharedCacheResult` manages the deferred promise, map registration, and lazy cleanup. Entries stay in the dedup maps until collection completes (so late-arriving invocations can join while the leader streams), then clean up automatically on resolve or reject. A follow-up refactoring to extract the cache handler lookup and generation into a separate function would help break up the function's size. closes #78703 -
Josh Story authored
"auto" mode is the default. It does not need to be explicitly exported "force-" modes suggest overriding framework heuristics "force-disabled" disables prefetching for this segment "force-static" forces any prefetching of this segment to be static "force-runtime" forces any prefetching of this segment to do runtime prefetching It's worth noting that when runtime prefetching we fetch the necessary segment and all child segments in a single request. This means that a deeper segment might specify disabled or static and still get conditionally rendered as a runtime prefetch. This was already the behavior of runtime prefetching and not changing in this PR just something to call out since it may be confusing to folks trying to understand how the implementation of prefetching actually work
-
nextjs-bot authored
-
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 ```
-
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
-
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:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
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:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
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 -->
-
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:Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
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:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
Luke Sandberg authored
s/MagicAny/DynTaskInputs/ essentially
-
Zack Tanner authored
This test was erroneously added in https://github.com/vercel/next.js/pull/92920 which already exists [here](https://github.com/vercel/next.js/blob/canary/test/e2e/rewrite-request-smuggling/rewrite-request-smuggling.test.ts).
-
- 16 Apr, 2026 16 commits
-
-
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 -
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.
-
nextjs-bot authored
-
Benjamin Woodruff authored
I guess next.js used `yarn` a long time ago? We don't need to support this anymore.
-
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 -->
-
Sebastian "Sebbie" Silbermann authored
-
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 -->
-
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.
-
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 -->
-
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:
Sebastian "Sebbie" Silbermann <sebastian.silbermann@vercel.com>
-
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
-
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 --> -
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
-
nextjs-bot authored
-
Niklas Mischkulnig authored
-
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:Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com> Co-authored-by:
Niklas Mischkulnig <mischnic@users.noreply.github.com>
-
- 15 Apr, 2026 2 commits
-
-
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)
-
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`.
-