Unverified Commit 162016b9 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

rage-restart followup (#92591)

### What?

Two behaviour changes to the rage-restart detection in `next dev`, plus
a refactor of the git helper code:

1. **Lower the rage-restart threshold from 120s to 90s.** The previous
window was too generous; 90 s is a better match for the workflow of
stopping and immediately restarting the dev server.

2. **Don't count a restart as a rage-restart if the git branch
changed.** A common workflow is: stop the dev server, `git checkout
<other-branch>`, restart. That sequence has nothing to do with
frustration — it's intentional. The dev state file now records the
current git branch on shutdown, and on startup the recorded branch is
compared to the current one. If they differ the restart is not flagged.
If either branch is unknown (detached HEAD, not a git repo, etc.) the
comparison is skipped and we fall back to time-only detection,
preserving the existing behaviour.

### Why?

The rage-restart signal is meant to detect genuine frustration with the
dev server (e.g. it's hanging or erroring on startup). Switching
branches is an intentional, deliberate action that happens to look the
same from a pure timing perspective. Capturing it as rage-restart
pollutes telemetry and could trigger unwanted recovery behaviour.

The git helper consolidation removes duplicated `spawnSync` / `execSync`
calls spread across unrelated files, centralises the `VERCEL_GIT_*`
env-var fallback logic, and makes it easy to add further git queries in
one place.

### How?

- `writeDevState()` in `next-dev.ts` now calls `getGitBranch(dir)` and
stores the result under a `gitBranch` key in the dev state file (omitted
when the branch is unknown).
- On startup, after reading the dev state file, the stored `gitBranch`
is compared to the freshly-read `getGitBranch(dir)`. `isRageRestart` is
only set when the branch either hasn't changed or couldn't be
determined.
- `packages/next/src/lib/helpers/git.ts` provides `gitExec()` (private),
`getGitBranch()`, and `getGitCommit()`. It replaces the deleted
`get-git-branch.ts` and the open-coded `child_process.spawnSync` calls
in `trace-uploader.ts`.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarWill Binns-Smith <wbinnssmith@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 054aa46c
...@@ -33,6 +33,7 @@ import { ...@@ -33,6 +33,7 @@ import {
isPortIsReserved, isPortIsReserved,
} from '../lib/helpers/get-reserved-port' } from '../lib/helpers/get-reserved-port'
import { getCacheDirectory } from '../lib/helpers/get-cache-directory' import { getCacheDirectory } from '../lib/helpers/get-cache-directory'
import { getGitBranch } from '../lib/helpers/git'
import os from 'os' import os from 'os'
import fs from 'node:fs' import fs from 'node:fs'
import { once } from 'node:events' import { once } from 'node:events'
...@@ -78,7 +79,15 @@ const sessionStarted = Date.now() ...@@ -78,7 +79,15 @@ const sessionStarted = Date.now()
const sessionSpan = trace('next-dev') const sessionSpan = trace('next-dev')
// If the user restarts the dev server within this window we count it as a "rage restart". // If the user restarts the dev server within this window we count it as a "rage restart".
const RAGE_RESTART_THRESHOLD_MS = 120_000 const RAGE_RESTART_THRESHOLD_MS = 90_000
// Shape of a single project entry in the dev-state.json file.
// All fields are optional so older entries without gitBranch are still valid.
type DevStateEntry = {
stopTime?: number
distDirPath?: string
gitBranch?: string
}
// Single shared file for all projects — keyed by project directory path. // Single shared file for all projects — keyed by project directory path.
const DEV_STATE_FILE = path.join( const DEV_STATE_FILE = path.join(
...@@ -279,13 +288,22 @@ const nextDev = async ( ...@@ -279,13 +288,22 @@ const nextDev = async (
if (fs.existsSync(DEV_STATE_FILE)) { if (fs.existsSync(DEV_STATE_FILE)) {
const allState = JSON.parse( const allState = JSON.parse(
fs.readFileSync(DEV_STATE_FILE, 'utf8') fs.readFileSync(DEV_STATE_FILE, 'utf8')
) as Record<string, { stopTime?: number; distDirPath?: string }> ) as Record<string, DevStateEntry>
const state = allState[dir] const state = allState[dir]
if ( if (
state?.stopTime && state?.stopTime &&
Date.now() - state.stopTime < RAGE_RESTART_THRESHOLD_MS Date.now() - state.stopTime < RAGE_RESTART_THRESHOLD_MS
) { ) {
isRageRestart = true // Only flag as a rage restart if the git branch hasn't changed. If
// either the stored or current branch is unknown, skip the comparison
// and fall back to time-only detection.
const storedBranch = state.gitBranch
const currentBranch = getGitBranch(dir)
const branchChanged =
storedBranch && currentBranch && storedBranch !== currentBranch
if (!branchChanged) {
isRageRestart = true
}
} }
if (state?.distDirPath && !fs.existsSync(state.distDirPath)) { if (state?.distDirPath && !fs.existsSync(state.distDirPath)) {
distDirCleared = true distDirCleared = true
...@@ -507,7 +525,7 @@ function writeDevState(): void { ...@@ -507,7 +525,7 @@ function writeDevState(): void {
try { try {
fs.mkdirSync(path.dirname(DEV_STATE_FILE), { recursive: true }) fs.mkdirSync(path.dirname(DEV_STATE_FILE), { recursive: true })
let state: Record<string, { stopTime: number; distDirPath: string }> = {} let state: Record<string, DevStateEntry> = {}
try { try {
state = JSON.parse(fs.readFileSync(DEV_STATE_FILE, 'utf8')) state = JSON.parse(fs.readFileSync(DEV_STATE_FILE, 'utf8'))
} catch { } catch {
...@@ -526,9 +544,11 @@ function writeDevState(): void { ...@@ -526,9 +544,11 @@ function writeDevState(): void {
} }
// Update current project // Update current project
const gitBranch = getGitBranch(dir)
state[dir] = { state[dir] = {
stopTime: Date.now(), stopTime: Date.now(),
distDirPath: path.join(dir, distDir ?? '.next'), distDirPath: path.join(dir, distDir ?? '.next'),
...(gitBranch ? { gitBranch } : {}),
} }
const { sync: writeFileAtomicSync } = const { sync: writeFileAtomicSync } =
......
import { execSync } from 'child_process'
function gitExec(args: string, cwd: string): string {
return execSync(`git ${args}`, {
cwd,
timeout: 2000,
stdio: ['ignore', 'pipe', 'ignore'],
})
.toString()
.trim()
}
/**
* Returns the current git branch name for the given working directory, or
* undefined if it cannot be determined (not a git repo, detached HEAD,
* git not installed, etc.). Prefers VERCEL_GIT_COMMIT_REF when set.
*/
export function getGitBranch(cwd: string): string | undefined {
if (process.env.VERCEL_GIT_COMMIT_REF) {
return process.env.VERCEL_GIT_COMMIT_REF
}
try {
// symbolic-ref --short HEAD: returns the branch name for regular branches,
// works on repos with no commits, and exits non-zero in detached HEAD state
// (caught below and treated as unknown).
return gitExec('symbolic-ref --short HEAD', cwd)
} catch {
return undefined
}
}
/**
* Returns the current git commit SHA for the given working directory, or
* undefined if it cannot be determined. Prefers VERCEL_GIT_COMMIT_SHA when
* set.
*/
export function getGitCommit(cwd: string): string | undefined {
if (process.env.VERCEL_GIT_COMMIT_SHA) {
return process.env.VERCEL_GIT_COMMIT_SHA
}
try {
return gitExec('rev-parse HEAD', cwd)
} catch {
return undefined
}
}
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import fsPromise from 'fs/promises' import fsPromise from 'fs/promises'
import child_process from 'child_process'
import assert from 'assert' import assert from 'assert'
import os from 'os' import os from 'os'
import { createInterface } from 'readline' import { createInterface } from 'readline'
import { createReadStream } from 'fs' import { createReadStream } from 'fs'
import path from 'path' import path from 'path'
import { getGitBranch, getGitCommit } from '../lib/helpers/git'
const COMMON_ALLOWED_EVENTS = ['memory-usage'] const COMMON_ALLOWED_EVENTS = ['memory-usage']
...@@ -128,23 +128,11 @@ interface TraceMetadata { ...@@ -128,23 +128,11 @@ interface TraceMetadata {
) )
const pkgName = projectPkgJson.name const pkgName = projectPkgJson.name
const git = os.platform() === 'win32' ? 'git.exe' : 'git'
const isVercelEnvironment = !!process.env.VERCEL const isVercelEnvironment = !!process.env.VERCEL
const commit = const commit = getGitCommit(projectDir) ?? ''
process.env.VERCEL_GIT_COMMIT_SHA ||
child_process const branch = getGitBranch(projectDir) ?? ''
.spawnSync(git, ['rev-parse', 'HEAD'])
.stdout.toString()
.trimEnd()
const branch =
process.env.VERCEL_GIT_COMMIT_REF ||
child_process
.spawnSync(git, ['rev-parse', '--abbrev-ref', 'HEAD'])
.stdout.toString()
.trimEnd()
const readLineInterface = createInterface({ const readLineInterface = createInterface({
input: createReadStream(path.join(projectDir, distDir, 'trace')), input: createReadStream(path.join(projectDir, distDir, 'trace')),
......
import { rmSync } from 'node:fs' import { rmSync, writeFileSync, mkdirSync } from 'node:fs'
import { join } from 'node:path' import { join, dirname } from 'node:path'
import { execSync } from 'node:child_process'
import { getCacheDirectory } from 'next/dist/lib/helpers/get-cache-directory' import { getCacheDirectory } from 'next/dist/lib/helpers/get-cache-directory'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { parseTraceFile } from '../../../lib/parse-trace-file' import { parseTraceFile } from '../../../lib/parse-trace-file'
...@@ -84,4 +85,37 @@ describe('rage restart trace attributes', () => { ...@@ -84,4 +85,37 @@ describe('rage restart trace attributes', () => {
expect(span?.tags?.['rage-restart']).toBe(true) expect(span?.tags?.['rage-restart']).toBe(true)
expect(span?.tags?.['missing-next-dir']).toBe(true) expect(span?.tags?.['missing-next-dir']).toBe(true)
}) })
it('should not set rage-restart when the git branch changed between sessions', async () => {
// next.testDir is a temp directory outside the repo, so it has no git
// context by default. Initialize a git repo there so getGitBranch() can
// return a known branch name for comparison.
execSync('git init && git checkout -b current-test-branch', {
cwd: next.testDir,
stdio: 'ignore',
})
// Write a dev-state entry that records a recent stop on a *different*
// branch, bypassing a full first session.
const devStateFilePath = getDevStateFilePath()
mkdirSync(dirname(devStateFilePath), { recursive: true })
const fakeState = {
[next.testDir]: {
stopTime: Date.now() - 1000, // 1 second ago — well within the threshold
distDirPath: join(next.testDir, '.next'),
gitBranch: 'previous-branch',
},
}
writeFileSync(devStateFilePath, JSON.stringify(fakeState))
// Start the server — the current branch ("current-test-branch") differs
// from the stored one ("previous-branch"), so this should NOT be flagged
// as a rage restart.
await next.start()
await next.render$('/')
await next.stop('SIGTERM')
const span = getStartDevServerSpan()
expect(span?.tags?.['rage-restart']).toBe(false)
})
}) })
...@@ -267,6 +267,7 @@ async function readNormalizedNFT(next, name) { ...@@ -267,6 +267,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/helpers/get-pkg-manager.js", "/node_modules/next/dist/lib/helpers/get-pkg-manager.js",
"/node_modules/next/dist/lib/helpers/get-registry.js", "/node_modules/next/dist/lib/helpers/get-registry.js",
"/node_modules/next/dist/lib/helpers/get-reserved-port.js", "/node_modules/next/dist/lib/helpers/get-reserved-port.js",
"/node_modules/next/dist/lib/helpers/git.js",
"/node_modules/next/dist/lib/helpers/install.js", "/node_modules/next/dist/lib/helpers/install.js",
"/node_modules/next/dist/lib/import-next-warning.js", "/node_modules/next/dist/lib/import-next-warning.js",
"/node_modules/next/dist/lib/inline-static-env.js", "/node_modules/next/dist/lib/inline-static-env.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