Unverified Commit a7b04690 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

gitignore .next-profiles (#95256)

### What?

When profiling is enabled (`--experimental-cpu-prof` /
`--internal-trace`, or the `NEXT_CPU_PROF` / `NEXT_TURBOPACK_TRACING`
env vars), Next.js writes a `.gitignore` containing `*` into
`.next-profiles/` as it creates the directory. This keeps the profiling
output out of git and out of the way of tools that scan the project
tree.

### Why?

`.next-profiles` is a sibling of `.next`, so it's intentionally *not*
covered by the `.gitignore` create-next-app ships. The motivation was
that profiles wouldn't bloat `.next` and wouldn't be silently ignored.
But a sibling dir full of large profile/trace files turns out to be a
liability:

- **Ecosystem tools scan it.** Tailwind v4 aggressively auto-scans files
and has opened a `trace-turbopack.bin` and crashed; Turborepo <2.8.13
hashes the file and OOMs, and >=2.8.13 fails to start `dev` watchers
because reading the large trace is too slow. (workflow watchers are
likely affected too.)
- **Turbopack NFT globbing** can read/hash the file via overly broad
`fs.read` patterns.
- **Accidental commits.** Pushing a multi-GB trace would be miserable
for a customer helping us debug.

These have each gotten point bandaids (#94587, #94570), but the real fix
preserves the original motivation: a nested `.gitignore` with `*` keeps
the files off git **and** makes gitignore-respecting tools (Tailwind,
Turborepo) skip the whole subtree, which resolves the scanning failures.
Reverting to `.next/profiles` was the alternative; the gitignore
approach keeps the existing path.

### How?

- `ensureProfilesDir()` (`packages/next/src/lib/profiles-dir.ts`)
creates `.next-profiles` and writes the `.gitignore` (only if absent, so
user edits survive). Single source of truth.
- `bin/next.ts` calls a `setupProfilesDir()` helper on build/dev/start,
gated on the env vars so both the CLI flags and direct env-var usage are
covered. Skipped when `NEXT_TURBOPACK_TRACING_PATH` redirects trace
output.
- Rust keeps `create_dir_all` as a backstop for the trace dir; the
`.gitignore` is written in JS only.
- Docs switched from `NEXT_TURBOPACK_TRACING=1` to `next dev
--internal-trace`, and the stale `trace-turbopack` filename corrected to
`trace-turbopack.bin`.

<!-- NEXT_JS_LLM_PR -->
parent d6f4cd33
......@@ -20,7 +20,7 @@ Alternatively, any directives syntax supported by [`tracing_subscriber::filter::
>
> For the more detailed tracing a custom Next.js build is required. See [Developing] for more information on how to create one.
With this environment variable, Next.js will write a `.next-profiles/trace-turbopack` file with the tracing information in a binary format.
With this environment variable, Next.js will write a `.next-profiles/trace-turbopack.bin` file with the tracing information in a binary format.
[presets]: https://github.com/vercel/next.js/blob/c506c0de1d6f17ad400ad5aa85edaae23b6b44d2/packages/next-swc/crates/napi/src/next_api/project.rs#L218
[directives]: https://tracing.rs/tracing_subscriber/filter/struct.envfilter#directives
......@@ -28,17 +28,17 @@ With this environment variable, Next.js will write a `.next-profiles/trace-turbo
## Viewer
To visualize the content of `.next-profiles/trace-turbopack`, use the [turbo-trace-viewer].
To visualize the content of `.next-profiles/trace-turbopack.bin`, use the [turbo-trace-viewer].
A video showing how to use the tool [is available here][youtube-tutorial].
This tool connects a WebSocket on port 57475 on localhost to connect to the trace-server. You can start the trace-server with the following command:
```sh
cargo run --bin turbo-trace-server --release -- /path/to/your/trace-turbopack
cargo run --bin turbo-trace-server --release -- /path/to/your/trace-turbopack.bin
# or
pnpm next internal trace .next-profiles/trace-turbopack
pnpm next internal trace .next-profiles/trace-turbopack.bin
```
Once the server is started, open <https://trace.nextjs.org/> in your browser.
......
......@@ -510,6 +510,9 @@ pub fn project_new(
let subscriber = subscriber.with(FilterLayer::try_new(&trace).unwrap());
// For the default `.next-profiles` location the JS CLI already created
// this directory (with its `.gitignore`) before invoking the binding; this
// is a safety net and also covers a `NEXT_TURBOPACK_TRACING_PATH` override.
std::fs::create_dir_all(&trace_dir)
.with_context(|| {
format!(
......
......@@ -236,34 +236,34 @@ It provides detailed information about the time taken for each module to compile
1. Generate a Turbopack trace file:
```bash package="pnpm"
NEXT_TURBOPACK_TRACING=1 pnpm dev
pnpm dev --internal-trace
```
```bash package="npm"
NEXT_TURBOPACK_TRACING=1 npm run dev
npm run dev -- --internal-trace
```
```bash package="yarn"
NEXT_TURBOPACK_TRACING=1 yarn dev
yarn dev --internal-trace
```
```bash package="bun"
NEXT_TURBOPACK_TRACING=1 bun dev
bun dev --internal-trace
```
1. Navigate around your application or make edits to files to reproduce the problem.
1. Stop the Next.js development server.
1. A file called `trace-turbopack` will be available in the `.next-profiles` folder.
1. A file called `trace-turbopack.bin` will be available in the `.next-profiles` folder.
1. You can interpret the file using `npx next internal trace [path-to-file]`:
```bash
npx next internal trace .next-profiles/trace-turbopack
npx next internal trace .next-profiles/trace-turbopack.bin
```
On versions where `trace` is not available, the command was named `turbo-trace-server`:
```bash
npx next internal turbo-trace-server .next-profiles/trace-turbopack
npx next internal turbo-trace-server .next-profiles/trace-turbopack.bin
```
1. Once the trace server is running you can view the trace at https://trace.nextjs.org/.
......
......@@ -926,19 +926,19 @@ Additionally, a lockfile mechanism prevents multiple `next dev` or `next build`
The [Turbopack tracing command](/docs/app/guides/local-development#turbopack-tracing) should be:
```bash package="pnpm"
pnpm next internal trace .next-profiles/trace-turbopack
pnpm next internal trace .next-profiles/trace-turbopack.bin
```
```bash package="npm"
npx next internal trace .next-profiles/trace-turbopack
npx next internal trace .next-profiles/trace-turbopack.bin
```
```bash package="yarn"
yarn next internal trace .next-profiles/trace-turbopack
yarn next internal trace .next-profiles/trace-turbopack.bin
```
```bash package="bun"
bunx next internal trace .next-profiles/trace-turbopack
bunx next internal trace .next-profiles/trace-turbopack.bin
```
## Parallel Routes `default.js` requirement
......
......@@ -406,13 +406,13 @@ For more in-depth configuration examples, see the [Turbopack config documentatio
## Generating trace files for performance debugging
If you encounter performance or memory issues and want to help the Next.js team diagnose them, you can generate a trace file by appending `NEXT_TURBOPACK_TRACING=1` to your dev command:
If you encounter performance or memory issues and want to help the Next.js team diagnose them, you can generate a trace file by adding the `--internal-trace` flag to your dev command:
```bash
NEXT_TURBOPACK_TRACING=1 next dev
next dev --internal-trace
```
This will produce a `.next-profiles/trace-turbopack` file. Include that file when creating a GitHub issue on the [Next.js repo](https://github.com/vercel/next.js) to help us investigate.
This will produce a `.next-profiles/trace-turbopack.bin` file. Include that file when creating a GitHub issue on the [Next.js repo](https://github.com/vercel/next.js) to help us investigate.
## Summary
......
......@@ -32,7 +32,27 @@ import type { NextAnalyzeOptions } from '../cli/next-analyze.js'
import type { NextBuildOptions } from '../cli/next-build.js'
import type { NextTypegenOptions } from '../cli/next-typegen.js'
import type { NextPostBuildOptions } from '../cli/next-post-build.js'
import { mkdirSync } from 'fs'
import { ensureProfilesDir } from '../lib/profiles-dir'
/**
* Create `.next-profiles` (with its `.gitignore`) when profiling/tracing is
* enabled — whether via the CLI flags or the env vars directly — so the
* gitignore logic lives in one place. Also points CPU profiles at the directory.
* Skipped for tracing when `NEXT_TURBOPACK_TRACING_PATH` redirects the output.
*/
function setupProfilesDir(dir: string): void {
const cpuProf = !!process.env.NEXT_CPU_PROF
const turbopackTrace =
!!process.env.NEXT_TURBOPACK_TRACING &&
!process.env.NEXT_TURBOPACK_TRACING_PATH
if (!cpuProf && !turbopackTrace) {
return
}
const profilesDir = ensureProfilesDir(dir)
if (cpuProf) {
process.env.NEXT_CPU_PROF_DIR = profilesDir
}
}
if (process.env.NEXT_RSPACK) {
// silent rspack's schema check
......@@ -227,11 +247,6 @@ program
if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'build-main'
const { join } = require('path') as typeof import('path')
const dir = directory || process.cwd()
const cpuProfileDir = join(dir, '.next-profiles')
mkdirSync(cpuProfileDir, { recursive: true })
process.env.NEXT_CPU_PROF_DIR = cpuProfileDir
}
if (options.internalTrace) {
process.env.NEXT_TURBOPACK_TRACING =
......@@ -239,6 +254,7 @@ program
? 'turbo-tasks'
: String(options.internalTrace)
}
setupProfilesDir(directory || process.cwd())
// ensure process exits after build completes so open handles/connections
// don't cause process to hang
......@@ -380,11 +396,6 @@ program
if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'dev-main'
const { join } = require('path') as typeof import('path')
const dir = directory || process.cwd()
const cpuProfileDir = join(dir, '.next-profiles')
mkdirSync(cpuProfileDir, { recursive: true })
process.env.NEXT_CPU_PROF_DIR = cpuProfileDir
}
if (options.internalTrace) {
process.env.NEXT_TURBOPACK_TRACING =
......@@ -392,6 +403,7 @@ program
? 'turbo-tasks'
: String(options.internalTrace)
}
setupProfilesDir(directory || process.cwd())
const portSource = _optionValueSources.port
import('../cli/next-dev.js').then((mod) =>
mod.nextDev(options, portSource, directory)
......@@ -470,12 +482,8 @@ program
if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'start-main'
const { join } = require('path') as typeof import('path')
const dir = directory || process.cwd()
const cpuProfileDir = join(dir, '.next-profiles')
mkdirSync(cpuProfileDir, { recursive: true })
process.env.NEXT_CPU_PROF_DIR = cpuProfileDir
}
setupProfilesDir(directory || process.cwd())
return import('../cli/next-start.js').then((mod) =>
mod.nextStart(options, directory)
)
......
......@@ -16,6 +16,7 @@ import {
} from '../server/lib/utils'
import * as Log from '../build/output/log'
import { getProjectDir } from '../lib/get-project-dir'
import { ensureProfilesDir } from '../lib/profiles-dir'
import path from 'path'
import { traceGlobals } from '../trace/shared'
import { Telemetry } from '../telemetry/storage'
......@@ -416,7 +417,7 @@ const nextDev = async (
...(options.experimentalCpuProf
? {
NEXT_CPU_PROF: '1',
NEXT_CPU_PROF_DIR: path.join(dir, '.next-profiles'),
NEXT_CPU_PROF_DIR: ensureProfilesDir(dir),
__NEXT_PRIVATE_CPU_PROFILE: 'dev-server',
}
: undefined),
......
import { existsSync, mkdirSync, writeFileSync } from 'fs'
import { join } from 'path'
/**
* Name of the directory at the project root where profiling output (CPU
* profiles and Turbopack traces) is written when profiling is enabled (see the
* `--experimental-cpu-prof` and `--internal-trace` CLI flags). It is a
* fixed-name sibling of `distDir`, not configurable.
*
* Keep this in sync with `DIST_PROFILES_DIR_NAME` in
* `crates/next-core/src/next_config.rs`.
*/
export const PROFILES_DIR_NAME = '.next-profiles'
const GITIGNORE_CONTENTS = `# Created automatically by Next.js. Profiling output should not be committed.
*
`
/**
* Create the `.next-profiles` directory under `dir` and return its absolute
* path. This is the single place that creates the directory — the Rust trace
* writer relies on it already existing.
*
* Also writes a `.gitignore` containing `*` (if one isn't already there) so the
* potentially large profiling output is excluded from git and gitignore-aware
* tools (Tailwind, Turborepo, ...) skip the subtree instead of reading it and
* hanging/OOMing.
*/
export function ensureProfilesDir(dir: string): string {
const profilesDir = join(dir, PROFILES_DIR_NAME)
mkdirSync(profilesDir, { recursive: true })
const gitignorePath = join(profilesDir, '.gitignore')
if (!existsSync(gitignorePath)) {
try {
writeFileSync(gitignorePath, GITIGNORE_CONTENTS)
} catch {
// A missing .gitignore must not abort a profiling run.
}
}
return profilesDir
}
......@@ -50,9 +50,8 @@ export function saveCpuProfile(): void {
let outputPath: string
if (cpuProfileDir) {
if (!fs.existsSync(cpuProfileDir)) {
fs.mkdirSync(cpuProfileDir, { recursive: true })
}
// The CLI created `cpuProfileDir` (with its `.gitignore`) before setting
// NEXT_CPU_PROF_DIR, so it already exists in these build workers.
outputPath = path.join(cpuProfileDir, filename)
} else {
outputPath = `./${filename}`
......
import { nextTestSetup, isNextDeploy } from 'e2e-utils'
import { pathExists, readdir } from 'fs-extra'
import { pathExists, readdir, readFile } from 'fs-extra'
import { join } from 'path'
describe('CPU Profiling - next build', () => {
......@@ -23,6 +23,14 @@ describe('CPU Profiling - next build', () => {
await next.build()
})
it('should write a .gitignore into .next-profiles', async () => {
const gitignore = join(next.testDir, '.next-profiles', '.gitignore')
expect(await pathExists(gitignore)).toBe(true)
// `*` keeps the (potentially large) profiling output out of git and away
// from gitignore-respecting tools that would otherwise scan it.
expect(await readFile(gitignore, 'utf8')).toContain('*')
})
it('should create CPU profile files after build', async () => {
const profileDir = join(next.testDir, '.next-profiles')
......
......@@ -328,6 +328,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/pick.js",
"/node_modules/next/dist/lib/picocolors.js",
"/node_modules/next/dist/lib/pretty-bytes.js",
"/node_modules/next/dist/lib/profiles-dir.js",
"/node_modules/next/dist/lib/realpath.js",
"/node_modules/next/dist/lib/recursive-copy.js",
"/node_modules/next/dist/lib/recursive-delete.js",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment