- 07 Apr, 2026 28 commits
-
-
nextjs-bot authored
-
Luke Sandberg authored
### What? Replace the `RwLock`-based `is_empty()` check in `TurboPersistence` with a lock-free `AtomicBool` that mirrors the emptiness of `inner.meta_files`. ### Why? `is_empty()` is called on the hot read path (`lookup_task_candidates`) as a fast early-return before performing any real work. The previous implementation acquired a read lock on the inner `RwLock` purely to check whether `meta_files` is empty — a boolean state that changes infrequently (only on `load_directory` and `commit`). Taking a lock on every lookup, even a read lock, adds unnecessary contention and overhead. ### How? - Added an `is_empty: AtomicBool` field to `TurboPersistence`, initialized to `true` (a fresh database is always empty). - The atomic is updated at the two mutation points that change `meta_files`: - `load_directory()` — after reading meta files from disk into `inner.meta_files`. - `commit()` — after appending new meta files and retaining/removing old ones (under the write lock). - `is_empty()` now does a single `load(Ordering::Relaxed)` instead of acquiring a read lock. `Relaxed` ordering is appropriate because `is_empty()` is used as a performance hint, not a synchronization point. A briefly stale value only means a redundant hash computation, not a correctness issue. <!-- NEXT_JS_LLM_PR --> Co-authored-by:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
MK authored
## Summary - add a prominent note in the App Router Caching guide about runtime behavior on serverless deployments - clarify that `use cache` runtime entries are in-memory and may not persist across requests when requests hit different instances - link directly to `use cache: remote` as the durable/shared runtime caching option Closes #91959 ## Verification - **Manual/source verification** - Confirmed before change there was no mention of serverless runtime cache persistence in `docs/app/getting-started/caching`. - Confirmed after change the new callout appears immediately under the existing “Good to know” note in `docs/01-app/01-getting-started/08-caching.mdx`. - **Evidence screenshots (before/after + verification)** - Before: https://raw.githubusercontent.com/wwenrr/pr-evidence-images/main/next.js/issue-91959/2026-04-01/before.png - After: https://raw.githubusercontent.com/wwenrr/pr-evidence-images/main/next.js/issue-91959/2026-04-01/after.png - Verification keyword check: https://raw.githubusercontent.com/wwenrr/pr-evidence-images/main/next.js/issue-91959/2026-04-01/verification.png ## Notes - Formatting toolchain was not run in this environment because `pnpm` is unavailable on host (`pnpm: not found`). - Change is a minimal docs-only edit (single file, two inserted lines in a callout block). --------- Co-authored-by:
wwenrr <wwenrr@users.noreply.github.com> Co-authored-by:
Joseph Chamochumbi <joseph.chamochumbi@vercel.com> Co-authored-by:
Joseph <sephxd1234@gmail.com>
-
Benjamin Woodruff authored
This should fix the stats action: We were checking out Next.js 16.2.2, and that doesn't support the `--out` flag for `pnpm pack`. Let's just force pnpm 10.33.0 here for now. While we're here, I made some other updates and improvements: - Update dockerfile to use Ubuntu 24.04 - Update dockerfile to use corepack 0.34.6 - Fix an issue where `pnpm install`ing outside of the docker container could break the docker container build (use `--exclude=node_modules`) - Avoid using a shell with string interpolation (potential escaping issues) for `cd`ing, just set `cwd`.
-
Andrew Imm authored
-
JJ Kasper authored
## Summary - gate middleware invocation with configured next-routing matchers - normalize app request URLs in app-page routing paths - prevent static route matches from inheriting dynamic `routeMatches` - add test coverage for next-routing captures/resolve-routes/next-data and app-page URL normalization ## Validation - validated downstream in adapter-bun deploy E2E runs with `HEADLESS=1`, `--retries 0`, and `--debug`
-
nextjs-bot authored
-
Sebastian "Sebbie" Silbermann authored
-
Tobias Koppers authored
### What? Adds a `reply-and-resolve-thread` subcommand to `scripts/pr-status.js` that combines replying and resolving a review thread in a single command. Also updates the generated `thread-N.md` files to show this command alongside the existing separate `reply-thread` and `resolve-thread` options, and documents the command in the agent skill files. ### Why? When addressing PR review comments, the typical workflow is to reply with a description of what was done and then immediately resolve the thread. This previously required two separate commands: ```bash node scripts/pr-status.js reply-thread <id> "Done -- ..." node scripts/pr-status.js resolve-thread <id> ``` Having a single command reduces friction for agents (and humans) closing out review threads after addressing feedback. ### How? - Added `reply-and-resolve-thread` subcommand in `main()` that calls the existing `replyToThread()` and `resolveThread()` functions in sequence. - Updated `generateThreadMd()` to include a "Reply and resolve in one step" code block in the Commands section of each unresolved thread file (alongside the existing separate commands, not replacing them). - Updated `.agents/skills/pr-status-triage/SKILL.md` to mention the combined command in workflow step 6 and added a "Thread interaction" quick-command reference section. - Updated `.agents/skills/pr-status-triage/workflow.md` to show the one-step alternative in the "Resolving Review Threads" section. <!-- NEXT_JS_LLM_PR --> --------- Co-authored-by:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
Will Binns-Smith authored
### What? Fixes issues with `AppRouteRouteModule` that interact with `devRequestTiming` and Turbopack server HMR. 1. **Incorrect `devRequestTimingInternalsEnd` attribution**: The app-route template previously statically imported userland (`import * as userland from 'VAR_USERLAND'`), meaning module load time was included in the framework's startup overhead. The `devRequestTimingInternalsEnd` timestamp is now set immediately before `routeModule.handle()` is called, and userland is loaded lazily on the first request so the timing correctly captures the framework→application boundary. 2. **Stale route handlers after Turbopack server HMR**: After a Turbopack server HMR update, `devModuleCache` is updated with a fresh route module, but the entry chunk remains in Node.js `require.cache`. The lazy `_userlandFactory` only runs once and would cache the old module reference — so route handler changes were not reflected after HMR. This restores a synchronous per-request `getUserland` getter that calls `require('VAR_USERLAND')` on every request. Since `require()` is a synchronous `devModuleCache` lookup, it has negligible overhead and doesn't add async time that would be incorrectly attributed to `application-code`. 3. **Route handlers with top-level await**: `require()` returns a Promise for modules that use top-level await. The module now accepts a lazy factory for `userland` and handles this case via `ensureUserland()`, which is called before the first request is handled. 4. **`output: export` route validation**: With the lazy factory, validation errors (e.g. `dynamic = "force-dynamic"` on an exported route) were deferred to request time, returning a 500 instead of surfacing as a Redbox in dev. The constructor now eagerly calls the factory for `output: export` routes so `_initFromUserland()` throws at module-load time — preserving the Redbox error. 5. **`node:stream` in edge bundles** (CI fix): `render-result.ts` was missing a `NEXT_RUNTIME === 'edge'` compile-time guard around `require('node:stream')` / `__non_webpack_require__('node:stream')`, which prevented webpack from DCE-ing those branches in edge builds. Vercel's deploy adapter rejects edge functions that reference `node:stream`. The guard is now restored to match the canary pattern. ### Why? #91466 enabled server HMR for app route handlers and introduced `getUserland: () => import('VAR_USERLAND')` to pick up HMR updates on each request. However, the async `import()` adds latency incorrectly attributed to application-code time in `devRequestTiming`. This PR replaces `import()` with synchronous `require()` and also lazily loads userland on the first request for accurate `devRequestTimingInternalsEnd` placement. ### How? - **Template** (`app-route.ts`): Replaces the static `import * as userland` with a lazy `() => require('VAR_USERLAND')` factory. In Turbopack dev mode, also provides `getUserland: () => require('VAR_USERLAND')` — a synchronous getter called on every request to pick up server HMR updates. - **Module** (`module.ts`): - Accepts `userland` as either a direct module or a lazy factory. - For `output: export` routes, calls the factory eagerly in the constructor so `_initFromUserland()` validation errors throw at module-load time (Redbox) rather than at request time (500). - For async modules (top-level await), stores the pending Promise in `_pendingUserland` so `ensureUserland()` can await it before the first request. - Accepts optional synchronous `getUserland` for per-request live userland access (Turbopack dev HMR). - `handle()` calls `_getUserland?.()` at request start; if set, uses the result for handler resolution, `fetchCache`, `hasNonStaticMethods`, and `dynamic` — ensuring HMR changes to all exported values are immediately reflected. - Extracts `_initFromUserland()` helper to deduplicate initialization between lazy and eager paths. - **Route module base** (`route-module.ts`): Makes `isDev` public for template access. - **Test** (`app-custom-routes.test.ts` + fixture): Adds an integration test for route handlers that use top-level await, ensuring the handler is correctly resolved even when `require()` returns a Promise. - **`render-result.ts`**: Restores the `if (process.env.NEXT_RUNTIME === 'edge') { throw }` guard matching canary, so `node:stream` is DCE'd from edge builds. Fixes #91318 --------- Co-authored-by:Will Binns-Smith <wbinnssmith@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
Luke Sandberg authored
Add the 'family name' to spans produced by the turbo-persistence backend. Record a `reason` for the batch fetch. this might be overkill but i found it useful to know that certain spans were related to prefetching vs data updates
-
Luke Sandberg authored
## Summary Reworks how the turbo-tasks backend tracks modified tasks for persistence snapshots, reducing overhead and simplifying the snapshot lifecycle. **Key changes:** - **Replace `modified` DashMap with per-shard atomic counters + inline flags.** Instead of maintaining a separate `FxDashMap<TaskId, ModifiedState>` that mirrors every modification, track modifications via flags already on `TaskStorage` and use per-shard `AtomicU64` counters to skip unmodified shards during snapshot iteration. This eliminates a major source of memory overhead. - The downside here is needing to scan the map. per shard counters enable early exits but we will still need to scan entire shards. For a large site that means scanning thousands of - **Merge task cache writes into the snapshot pipeline.** New tasks now carry a `new_task` flag and their type hash in `SnapshotItem`, so task cache entries are written in the same batch as task data/meta — removing the separate `persisted_task_cache_log` (`Sharded<ChunkedVec<...>>`) and its associated locking. - **Remove `local_is_partial` optimization.** The backing storage layer already short-circuits on empty databases, and new tasks eagerly set `restored` flags at allocation time, making this redundant. - **Simplify `end_snapshot`.** Instead of a multi-pass retain/iterate/update cycle over the `modified` map, `end_snapshot` now just drains the small `snapshots` map (only tasks concurrently accessed during snapshot mode) and promotes their `modified_during_snapshot` flags. - **Delete unused utilities.** Removes `Sharded`, `ChunkedVec` (from backing_storage), and `swap_retain` import now that they're no longer needed. **Other cleanups:** - `initialize_new_task` sets restored + new_task flags at allocation time for both persistent and transient tasks - Fuzz test updated to use `active_tracking: true` and `StorageMode::ReadWrite` - New KV storage test for batch write+flush+reopen pattern - Minor fix: `SmallVec::into_boxed_slice()` instead of `into_vec().into_boxed_slice()` ## Build Benchmark Results Measured over 9 runs (1 warm-up discarded), macOS, `TURBOPACK_PERSISTENT_CACHE=1`. ### Cold build (`rm -rf .next/`) | | Time (avg) | Time (stddev) | MaxRSS (avg) | |---|---|---|---| | HEAD | 75.48s | 0.72s | 24,231 MiB | | This PR | 75.20s | 1.98s | 23,829 MiB | | **Delta** | −0.28s | — | **−402 MiB (−1.7%)** | ### Warm build (single file edit) | | Time (avg) | MaxRSS (avg) | |---|---|---| | HEAD | 23.79s | 8,764 MiB | | This PR | 23.67s | 8,766 MiB | | **Delta** | −0.12s | flat | Cold build time difference is within noise (< 1 stddev). The meaningful improvement is a **~400 MiB reduction in peak memory on cold builds**, consistent with the fixed overhead this PR targets. Warm builds are unaffected as expected. -
Luke Sandberg authored
<!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # -->
-
Tobias Koppers authored
### What? Re-lands #91576 ("turbo-tasks: add hashed cell mode for hash-based change detection without cell data"), which was reverted in #92103 due to a `FATAL` crash in the `filesystem-cache` test suite. Includes a bug fix on top: in `task_execution_completed_prepare`, skip updating `cell_type_max_index` when the task completed with an error. Also adds a `CellHash = [u8; 16]` type alias (requested in review) used throughout the hash pipeline. ### Why? **The original feature** (`serialization = "hash"` on `FileContent` and `Code`) stores a hash of the cell data instead of the full serialized value. On session restore, the hash is used to detect whether cell content has changed without needing the full data in memory. This avoids a large persistent cache size increase. **The bug** that caused the revert: When a task fails partway through re-execution (before recreating all the cells from its previous run), `cell_counters` only reflects the partially-executed state. The old code used those partial counters to update `cell_type_max_index`, removing entries for cell types that were not yet created at the point of failure. This caused downstream tasks that still held cell dependencies from the previous successful run to hit a hard "Cell no longer exists" error. **Concrete failure path** in `filesystem-cache rename app page` test: 1. `get_app_page_entry` runs for `/remove-me/page`, creating two `FileContent` cells (indices 0 and 1). `cell_type_max_index[FileContent] = 2` is persisted. 2. The folder is renamed (`app/remove-me` → `app/add-me`), dirtying the task. 3. On re-execution, `get_app_page_entry` fails at `config.await?` (the loader tree errors because the directory is gone) — before any `FileContent::cell()` calls. 4. `cell_counters` has no `FileContent` entry → old code removed `cell_type_max_index[FileContent]`. 5. The `parse` task tries to read `FileContent` cell 1 from `get_app_page_entry` → `cell_type_max_index` is `None` → **"Cell no longer exists" panic → FATAL error**. **Why it didn't crash before** `serialization = "hash"`: `FileContent` was previously serializable, so `parse` read stale cell data directly from `persistent_cell_data`, which `task_execution_completed_cleanup` already preserves on error. With `serialization = "hash"`, data is transient — readers fall back to `cell_type_max_index` for range validation, where a stale `None` caused the crash. ### How? #### Core feature: `serialization = "hash"` cell mode - New `SerializationMode::Hash` variant in `turbo-tasks-macros` — marks a value type as non-serializable but stores a `DeterministicHash` of the cell data for change detection. - `VcCellHashedCompareMode<T>` cell mode: compares values via `PartialEq` when available, falls back to hash comparison when transient data has been evicted. - `hashed_compare_and_update` / `hashed_compare_and_update_with_shared_reference` on `CurrentCellRef` compute and pass content hashes through the update pipeline. - Backend `update_cell` uses hash-based comparison to skip invalidation when the old cell data is unavailable but the hash matches. - `cell_data_hash: AutoMap<CellId, CellHash>` field in task storage persists hashes across sessions. - Stale `cell_data_hash` entries are cleaned up in `task_execution_completed_cleanup` alongside cell data removal. - `CellHash = [u8; 16]` type alias keeps alignment at 1 byte to avoid padding growth in `AutoMap`/`LazyField` enum variants. - Hash bytes use little-endian encoding (`to_le_bytes`) for cross-platform cache portability. #### Bug fix: preserve `cell_type_max_index` on task error In `task_execution_completed_prepare`, guard the `cell_type_max_index` update block with `if result.is_ok()`. This mirrors the existing `task_execution_completed_cleanup` behavior that already skips cell data removal when `is_error` is true, keeping `cell_type_max_index` consistent with the preserved transient cell data. #### Applied to `FileContent` and `Code` - `FileContent` uses `serialization = "hash"` — full content is persisted via a separate `PersistedFileContent` type when needed (e.g., in `DiskFileSystem::write`). - `Code` uses `serialization = "hash"` with `Arc<Vec<Mapping>>` for cheap cloning. `Code::cell_persisted()` creates a `PersistedCode` cell directly and returns `Vc<Code>` via `PersistedCode::to_code()`, avoiding an intermediate hash-mode cell. #### Other improvements - `DeterministicHash` impls for `SmallVec` and `()`. - `Xxh3Hash128Hasher::finish_bytes()` method returning `[u8; 16]`. - `hash = "manual"` option on `#[turbo_tasks::value]` to opt out of auto-deriving `DeterministicHash`. **Note:** The shutdown hang and cache poisoning fixes that were previously on this branch have been merged separately via #92254. ### Test plan - [x] `test/e2e/filesystem-cache/filesystem-cache.test.ts` passes (all 17 tests) - [x] New `turbopack/crates/turbo-tasks-backend/tests/hashed_cell_mode.rs` integration test verifies hash-based change detection: value changes trigger invalidation, equal values (same hash) do not - [x] `cargo check` passes for `turbo-tasks`, `turbo-tasks-backend`, `turbo-tasks-fs`, `turbopack-core`, `turbopack-ecmascript` - [x] CI green (attempt 2) <!-- 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? Fix a race condition in the Pages Router SSR path where styled-jsx styles were dropped from the rendered HTML. ### Why? `styledJsxInsertedHTML()` reads and flushes the styled-jsx style registry. Previously it was called concurrently with the page render via `Promise.all`: ```js const [rawStyledJsxInsertedHTML, content] = await Promise.all([ renderToString(styledJsxInsertedHTML()), (async () => { /* render the page */ })(), ]) ``` Because both ran at the same time, `styledJsxInsertedHTML()` could (and in practice did) execute and flush the registry **before** the page render had finished populating it. The result was that dynamic styled-jsx styles — those with interpolated expressions that compute their class names at runtime via DJB2 hashing — were silently dropped from the SSR output, causing a flash of unstyled content on first load. This is particularly visible in production deployments where all components use dynamic styled-jsx (numeric `jsx-*` class names), since those styles only exist in the registry after rendering completes. ### How? Serialize the two operations: render the page first, then call `styledJsxInsertedHTML()`. Since the registry is fully populated by the time it is read, all styles are captured correctly. A new e2e test (`test/e2e/styled-jsx-dynamic`) exercises this scenario with multiple nested components that all use dynamic styled-jsx with interpolated props, covering the exact FOUC pattern seen in production. <!-- NEXT_JS_LLM_PR --> Co-authored-by:Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
Sebastian "Sebbie" Silbermann authored
-
Tobias Koppers authored
### What? Implements [`quick_cache::Lifecycle`](https://docs.rs/quick_cache/latest/quick_cache/#lifecycle-hooks) hooks for the `BlockCache` in turbo-persistence. A new `BlockCacheLifecycle` struct overrides `is_pinned` to check whether the `ArcBytes` value's backing `Arc` has a strong count > 1, indicating it is still referenced outside the cache. When `is_pinned` returns `true`, the cache's eviction algorithm (Clock-PRO / S3-FIFO) skips the entry instead of evicting it. ### Why? Without pinning, the cache can evict blocks that are still in use — the caller holds an `ArcBytes` clone (which shares the `Arc` backing), so the data isn't lost, but the cache slot is wasted. When the caller finishes and the entry is looked up again, it results in an unnecessary cache miss and re-read/decompress from disk. By checking `Arc::strong_count > 1` in `is_pinned`, we avoid evicting entries that are actively referenced, improving cache hit rates under concurrent access. ### How? **`ArcBytes::is_shared()`** (`arc_bytes.rs`): - Returns `true` when the backing `Arc<[u8]>` has `strong_count > 1` (i.e., someone outside the cache holds a clone). - Mmap-backed entries always return `false` — the mmap `Arc` is shared across all slices from the same file, so checking its `strong_count` would make them permanently unevictable. This is fine because #92390 already drops mmap blocks from the cache entirely. **`BlockCacheLifecycle`** (`static_sorted_file.rs`): - Implements `quick_cache::Lifecycle<(u32, u16), ArcBytes>` with `RequestState = ()`. - `is_pinned` delegates to `val.is_shared()`. - `begin_request` and `on_evict` are no-ops since we only need the pinning behavior. **`BlockCache` type alias** updated to include `BlockCacheLifecycle` as the 5th generic parameter. All call sites use `Default::default()` for construction, so no call-site changes were needed. **Test cleanup**: Removed the redundant `TestBlockCache` type alias (and its unused imports) in the builder tests in favor of the existing `BlockCache` alias. <!-- NEXT_JS_LLM_PR --> --------- Co-authored-by:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
Joseph authored
<!-- CURSOR_AGENT_PR_BODY_BEGIN --> ### What? Adds an explicit note about Proxy's default matching behavior at the top of the **Matcher** section in the Proxy API reference — the first place users look when configuring which paths Proxy runs on. ### Why? Users have reported issues where Tailwind styles and other static assets fail to load because their Proxy auth logic intercepts `_next/static` requests and redirects them (see #92435). The existing docs mention that Proxy runs on "every route" but don't explicitly call out static assets, image optimizations, or public folder files — making this a common pitfall that gets misdiagnosed as a CSS/PostCSS problem. ### How? Added an inline paragraph at the top of the **Matcher** subsection explaining that without a `matcher`, Proxy matches every request — including `_next/static`, `_next/image`, and `public/` files — and that this can break asset loading. Links to the existing Negative matching section. Fixes #92435 <!-- NEXT_JS_LLM_PR --> <!-- CURSOR_AGENT_PR_BODY_END --> [Slack Thread](https://vercel.slack.com/archives/C0AA1U29GQ0/p1775539745696779?thread_ts=1775539745.696779&cid=C0AA1U29GQ0) <div><a href="https://cursor.com/agents/bc-263e5d8f-e356-5e3a-a247-856d00a78af4"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-263e5d8f-e356-5e3a-a247-856d00a78af4"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div> --------- Co-authored-by:
Cursor Agent <cursoragent@cursor.com> Co-authored-by:
Joseph <icyJoseph@users.noreply.github.com>
-
Luke Sandberg authored
When `next dev` is running we change the process name, we should do the same thing for builds. This is a small performance hit on MacOs, about 10ms, (See node issue: https://github.com/nodejs/node/issues/59678), but not on other platforms. `process.title` is also apparently not implemented on `Bun` or `Deno`
🤦 -
Benjamin Woodruff authored
Addresses this missed review comment: https://github.com/vercel/next.js/pull/92220#discussion_r3024004242 There's only so much context we can provide because there's a ton of different ways users could've installed node incorrectly.
-
Tobias Koppers authored
### What? Skip the `BlockCache` entirely for uncompressed (mmap-backed) SST blocks, and add a per-file CRC verification bitmap so checksums are verified at most once per file open for any block. ### Why? Uncompressed blocks produce an `ArcBytes` with `Backing::Mmap` — just an `Arc::clone` of the mmap handle plus a pointer into it. No heap allocation, no decompression. The cost of constructing one (an atomic refcount increment + pointer copy) is far less than a `BlockCache` hash + concurrent-map lookup + potential insertion. Bypassing the cache for these blocks: - Reduces lock contention on the shared `BlockCache` - Avoids polluting the cache with entries that are essentially free to recreate - Eliminates redundant mmap reads (the old code peeked at the header, then re-read it inside `read_block_generic`) Key blocks (index block + all key blocks) tend to be small and are frequently accessed. In practice, small key blocks are often stored uncompressed, so this optimization applies on the hot path. ### How? **Single mmap read per block access.** `get_or_cache_block` calls `get_raw_block_slice` exactly once to read the block header (with all `#[cfg(feature = "strict_checks")]` bounds guards), then branches on `uncompressed_length`: - `== 0` (uncompressed): verify CRC via bitmap, return mmap-backed `ArcBytes` directly - `> 0` (compressed): check `BlockCache`; on miss, verify CRC via bitmap, decompress, insert **CRC verification bitmap.** `StaticSortedFile` now holds a `Box<[AtomicU64]>` with one bit per block, set once the block's CRC has been verified. This prevents re-computing the checksum on every access for uncompressed blocks (which bypass the cache) and for compressed blocks that were evicted and re-read. `Relaxed` ordering suffices since racing first-time verifications are idempotent. **`ArcBlockCacheReader` wrapper.** A `Copy` struct bundling `&BlockCache` + `&[AtomicU64]` that implements `ValueBlockCache<ArcBytes>`, threading the bitmap through the existing generic lookup machinery without changing the trait signature. **`BlockWeighter` safety net.** The mmap-backed branch now has a `debug_assert!(!val.is_mmap_backed())` to catch accidental insertion, with a negligible weight (64) as a defensive fallback in release builds. <!-- NEXT_JS_LLM_PR --> --------- Co-authored-by:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com> Co-authored-by:
Luke Sandberg <lukesandberg@users.noreply.github.com>
-
nextjs-bot authored
-
Benjamin Woodruff authored
We want to start dogfooding `workerThreads`, but we can only safely do it if you have a new enough node version. We don't have any sort of strong enforcement around node.js version in front (e.g. you could have a misconfigured nvm or fnm), so we need to check the node version first. - https://github.com/napi-rs/napi-rs/issues/2555#issuecomment-3645173223 - https://github.com/nodejs/node/pull/55877 - https://github.com/nodejs/node/pull/61400 - https://github.com/nodejs/node/pull/61661 Looks like this:  Related Node.js version bump for front: https://github.com/vercel/front/pull/65059
-
Benjamin Woodruff authored
Having both `apply_effects` and `Effects::apply` is confusing. `apply_effect`'s API seems a bit bad/dangerous because it combines work that should be done inside of a strongly-consistent operation (collecting the effects and reading their `Vc`s) with work that should be done at the top-level outside of any operation or turbo-task function (applying the effects). The first commit in this PR removes the `apply_effect` API and tries to improve documentation, including adding a doctest that compiles. The second commit in this PR is an LLM-driven refactor to remove the `apply_effect` callsites.
-
Luke Sandberg authored
Bump the `turbo` dependency from `2.8.11` to `2.9.4` (latest stable).
-
Luke Sandberg authored
Syncing files at the end of `commit` can be slow, do it all in parallel Also sync the `directory` to ensure all our new files are consistently linked
-
Will Binns-Smith authored
### What? Fix server HMR becoming unresponsive after a metadata route is loaded in the same Node.js process as an app page. ### Why? Turbopack loads separate runtime chunks for app pages and metadata routes (`robots.ts`, `sitemap.ts`, `manifest.ts`, `icon.tsx`, etc.) in the same Node.js process. Each runtime chunk embeds `dev-nodejs.ts` and produces a distinct `__turbopack_server_hmr_apply__` closure bound to its own `moduleFactories` and `devModuleCache`. Previously each runtime simply overwrote `globalThis.__turbopack_server_hmr_apply__`, so the last chunk to load silently won. Navigating to `/robots.txt` before an HMR update caused the metadata route runtime to overwrite the page runtime's handler. Subsequent HMR updates were dispatched only to the metadata route runtime, which has no knowledge of the page module — the page appeared frozen and stopped reflecting file changes. ### How? Replace the bare assignment with a multicast registry: 1. Each runtime appends its own `__turbopack_server_hmr_apply__` handler to `globalThis.__turbopack_server_hmr_handlers__[]`. 2. The first runtime to register installs a shared dispatcher as `globalThis.__turbopack_server_hmr_apply__` that iterates all registered handlers at call time (not install time), so newly loaded runtimes are always included. 3. On full cache reset, `hot-reloader-turbopack.ts` resets `__turbopack_server_hmr_handlers__` to `[]` so stale handlers from evicted chunks don't accumulate into the next generation. Because `dev-nodejs.ts` is embedded into the Turbopack binary via `include_dir!`, this fix requires rebuilding the native binary. ### Tests `test/development/app-dir/server-hmr/server-hmr.test.ts` — extended with `metadata route hmr` tests that load a metadata route before patching a page file, verifying HMR updates still reach the page runtime after a second runtime chunk is loaded. --------- Co-authored-by:
Will Binns-Smith <wbinnssmith@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
Benjamin Woodruff authored
This will let us potentially use https://pnpm.io/settings#minimumreleaseage
-
- 06 Apr, 2026 8 commits
-
-
nextjs-bot authored
-
Josh Story authored
The old impl has a boolean arg that was always true. To support some fixes to routing I need to make the parser sometimes allow for slots but still not things like route groups. I am generalizing the function implementation to have a filter type that decides whether the input string is allowed to have certain types such as route groups and slot names. All the existing uses still disallow any non-url path segments.
-
Zack Tanner authored
These tests won't ever be run in a deployed environment, so this removes `skipDeployment` so it's easier to grok which tests are intentionally disabled because they don't work when deployed.
-
Luke Sandberg authored
## What Optimizes AMQF (Approximate Membership Query Filter) construction in `StreamingSstWriter` by deferring filter building to `close()` time and using qfilter's sorted `Builder` API. ## Why The previous approach inserted each key hash into the AMQF filter eagerly during `add()`, using random-access `insert_fingerprint` calls. The new qfilter `Builder` API supports sequential sorted insertion which is significantly faster, but requires fingerprints in non-decreasing order. ## How 1. **Deferred construction**: Instead of building the AMQF incrementally during `add()`, collect key hashes (truncated to `u32`) into a vec during writes, then build the filter in one pass at `close()` time. 2. **Sorted Builder insertion**: Sort collected hashes by fingerprint value, then feed them to `Builder::insert_fingerprint` in order. This uses the Builder's optimized sorted-insert path. 3. **u32 storage**: Since fingerprint size is always ≤32 bits, store collected hashes as `u32` instead of `u64`, halving memory usage and improving sort cache behavior. 4. **Exact sizing**: The Builder is constructed with the exact entry count (known at `close()` time) rather than the `max_entry_count` estimate, producing optimally-sized filters. ## Benchmark results (vs `filter_ref` baseline) `write/key_8/value_4/` benchmark: | Entries | filter_ref | sorted_insert | Change | |---------|-----------|---------------|--------| | 85K | 22.3 ms | 21.1 ms | **-5.3%** | | 853K | 149.2 ms | 111.9 ms | **-25.0%** | | 8.3M | 1049 ms | 998.8 ms | **-4.8%** | The 853K case (typical compacted SST size) shows the largest improvement as AMQF construction is a significant fraction of total write time at that scale.
-
nextjs-bot authored
-
JJ Kasper authored
## Summary - add production-route-shape fixture coverage for `/[teamSlug]/[project]/settings/domains` - add revalidation helpers (API and server action) and browser controls used by the regression test - reproduce the failing production sequence by priming, revalidating, then loading a page with in-view `next/link` and navigating repeatedly x-ref: https://github.com/vercel/next.js/pull/91627 x-ref: https://github.com/vercel/next.js/pull/91603 ## Testing - `IS_WEBPACK_TEST=1 NEXT_SKIP_ISOLATE=1 NEXT_TEST_MODE=start pnpm testheadless test/e2e/app-dir/segment-cache/vary-params-base-dynamic/vary-params-base-dynamic.test.ts -t "production route shape"` (passes) - `NEXT_ENABLE_ADAPTER=1 pnpm test-deploy test/e2e/app-dir/segment-cache/vary-params-base-dynamic/vary-params-base-dynamic.test.ts -t "production route shape"` - `NEXT_ENABLE_ADAPTER=1 pnpm test-deploy test/e2e/app-dir/segment-cache/vary-params-base-dynamic/vary-params-base-dynamic.test.ts` (fails in the two production-shape cases) --------- Co-authored-by:
Zack Tanner <1939140+ztanner@users.noreply.github.com>
-
Aurora Scharff authored
### What? Add an `AGENTS.md` file at the npm package root (`node_modules/next/AGENTS.md`) so AI agents can discover the bundled documentation. ### Why? AI coding agents naturally check the package root for `AGENTS.md` before searching subdirectories. Without a file at the root, `cat node_modules/next/AGENTS.md` fails and agents hit a dead end. The bundled docs at `dist/docs/` are already shipped with the package but are not discoverable from the root. ### How? - Add `packages/next/AGENTS.md` mirroring the same content `create-next-app` generates for the project root, with the path adjusted to point at `dist/docs/` relative to the package root. - Add `"AGENTS.md"` to the `files` array in `package.json` so it ships with the npm package. ### Improving Documentation - [x] Run `pnpm prettier-fix` to fix formatting issues before opening the PR. <!-- NEXT_JS_LLM_PR -->
-
Tim Neutkens authored
## What? The codepath would cause checks to fail during deployment because it tries to import `node:stream` even when not used. This adds a specific path for edge runtime to avoid that. --------- Co-authored-by:Zack Tanner <1939140+ztanner@users.noreply.github.com>
-
- 05 Apr, 2026 3 commits
-
-
nextjs-bot authored
-
Zack Tanner authored
<!-- CURSOR_AGENT_PR_BODY_BEGIN --> ## What? Adds documentation to the contributing guide explaining how deploy tests work and how to run them. ## Why? Deploy tests are an important part of the Next.js CI pipeline that verify the framework works correctly when deployed to Vercel. However, there was no documentation explaining: - How deploy tests are triggered on PRs - How to run deploy tests locally This came up in a Slack discussion where team members were debugging deploy test failures and sharing knowledge about how to trigger and run these tests. ## How? Added a new "Deploy Tests" section to `contributing/core/testing.md` that explains: 1. **Triggering Deploy Tests on PRs**: Deploy tests don't run on every PR by default. To trigger them, you can modify a test file in the deploy test suite, which causes CI to run deploy tests for that file. 2. **Running Deploy Tests Locally**: You can run deploy tests locally using: - `NEXT_TEST_VERSION` to test against a specific commit's pre-built tarball - `NEXT_TEST_DEPLOY_URL` to skip the deploy step and test against an existing deployment <!-- NEXT_JS_LLM_PR --> <!-- CURSOR_AGENT_PR_BODY_END --> [Slack Thread](https://vercel.slack.com/archives/C04KC8A53T7/p1775265710012189?thread_ts=1775265710.012189&cid=C04KC8A53T7) <div><a href="https://cursor.com/agents/bc-014a1052-4dfe-5db4-931d-86efa411016e"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-014a1052-4dfe-5db4-931d-86efa411016e"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div> --------- Co-authored-by:
Cursor Agent <cursoragent@cursor.com>
-
Tobias Koppers authored
### What? Adds deduplication and conflict detection to the asset emission stage in `crates/next-core/src/emit.rs`, and a new `IssueStage::Emit` variant in `turbopack-core`. Before emitting, assets are grouped by their output path. If multiple assets map to the same path: - If their content is identical, one is silently chosen (deduplication). - If their content differs, both versions are written to `<node_root>/<content_hash>.<ext>` and an `EmitConflictIssue` is raised for each conflict. All assets are still emitted — conflicts do not abort the build. ### Why? Previously, duplicate output assets for the same path were emitted unconditionally — whichever write happened last silently won. This masked build graph bugs where two different modules produced conflicting output files. Reporting conflicts as issues (rather than silently overwriting) makes them visible and easy to diagnose without breaking the build. ### How? - Collect all assets with their resolved paths via `try_flat_join`. - Bucket them into two `FxIndexMap<FileSystemPath, Vec<ResolvedVc<Box<dyn OutputAsset>>>>` — one for node-root assets and one for client assets. - For each bucket entry, call `check_duplicates`: compare every asset against the first using `assets_diff`. If content differs, emit an `EmitConflictIssue` as a turbo-tasks collectible — but still return the first asset so emission continues. - `assets_diff` is a `#[turbo_tasks::function]` that takes only `(asset1, asset2, extension, node_root)` — the `asset_path` stays out of the task key to avoid unnecessary task cardinality. When file content differs, it hashes each version with xxh3, writes them to `<node_root>/<hash>.<ext>`, and returns the paths in the detail message so the user can diff them. - `EmitConflictIssue` implements the `Issue` trait with `IssueStage::Emit` (new variant added to `turbopack-core`), `IssueSeverity::Error`, a descriptive title, and a detail message explaining the type of conflict. - Node-root and client assets are emitted in parallel via `futures::join!` (not `try_join!`) to ensure deterministic error reporting — both branches always run to completion so errors are reported in a consistent order. --------- Co-authored-by:
Tobias Koppers <sokra@users.noreply.github.com> Co-authored-by:
Claude <noreply@anthropic.com>
-
- 04 Apr, 2026 1 commit
-
-
nextjs-bot authored
-