Unverified Commit 1a028f7f authored by dan's avatar dan Committed by GitHub

[internal] Add a skill for benching changes in a sandbox (#95943)

Vibed. This should help with running React PRs on sandboxes to measure
impact on `bench/`.

## Usage

```
use bench skill to to measure impact of https://github.com/react/react/pull/37066
```

- Should be able to point at React or Next PRs
- Compares against mergebase
- Grabs React builds from CI when possible
- Before benching, asserts both React builds are green, or that tests
pass
- Runs on many sandboxes with interleaved runs
- Caches reusable stuff (builds) between sandboxes
- Uses `bench/` examples with realistic payloads

## Test Plan

Running a bench:

<img width="1445" height="584" alt="Screenshot 2026-07-20 at 03 08 02"
src="https://github.com/user-attachments/assets/ac8b6aac-1e62-4695-9a59-fd0577a8a441"
/>

Bench that shows good results:

<img width="1078" height="725" alt="Screenshot 2026-07-20 at 03 46 20"
src="https://github.com/user-attachments/assets/ce49a806-f1b1-497c-a3dd-e5f8d08ea25b"
/>

Neutral bench:

<img width="1032" height="455" alt="Screenshot 2026-07-20 at 03 47 27"
src="https://github.com/user-attachments/assets/de3b700c-4875-4c70-b1c1-55cdddd73a1a"
/>

---------
Co-authored-by: 's avatarClaude Fable 5 <noreply@anthropic.com>
parent e1fbb180
This diff is collapsed.
# Statistical methodology
The design decisions below are what make the numbers trustworthy.
They follow standard rigorous-benchmarking practice (Kalibera & Jones,
"Rigorous Benchmarking in Reasonable Time"; Georges et al.,
"Statistically Rigorous Java Performance Evaluation"; JMH's forks
model) — don't relax them to save wall-clock without understanding
what they protect against.
## The VM boot is the unit of replication
JIT state, code layout, GC rhythm, host hardware, and phase order are
random effects fixed at boot time. Iterations within a boot share all
of them, so they are not independent samples — treating them as
independent produces confident nonsense (a p<1e-4 effect in one run
that vanishes in the next). The harness therefore:
- computes each metric's delta per boot (mean of that boot's paired
within-boot deltas), and
- runs t-based inference across boots (`bench-stats.mjs`); the CI and
p-value you see are boot-level.
The `within-run p` printed in brackets is a diagnostic only. It tells
you the pairing worked; it cannot support a claim.
Allocation follows from this: more boots × fewer runs beats fewer
boots × more runs at fixed budget, and boots run in parallel — adding
them costs money, not wall-clock, so don't be shy with them when
sensitivity matters (CI shrinks with sqrt of boots). Defaults: e2e 16
VMs × 1 block × 2
runs. Both arms always run in the SAME VM, interleaved ABBA, paired
per (vm, run) — hosts differ by up to ~20%, so cross-VM comparisons
are meaningless; VMs exist to replicate, not to compare.
## Claims
- A claim requires boot-level p < 0.01, reported with its CI, on a
team/config whose boot-level inference an A/A run has validated.
- Anything that will drive a decision (merge, revert, ship) gets one
independent confirmation cell first (standard perf-CI practice —
Mozilla/Chrome retrigger, MongoDB change-point detection — nobody
alerts off one detection).
- Everything else is "noise-compatible", reported as no detected
difference — not as a small effect.
## Percentiles
A per-run p95/p99 from a small load phase is a near-max order
statistic, not a distribution estimate. Compare percentiles only at
boot level; p99 needs ~1k+ samples per boot to mean anything at all.
Tail effects are also where phase carryover lives (a route's serial
tail depends on the previous route's load phase) — investigate tails
with `--isolate-routes`, which restarts the server between routes.
## A/A validation
Before claiming anything on a new team/config, run an A/A cell (same
ref as both arms) at default allocation:
```sh
node scripts/sandbox-e2e.mjs --arms base=<ref>,cand=<ref> --label aa
```
The A/A validates the inference itself: with identical arms, no
route/phase/metric cell should reach p < 0.01 (beyond the nominal
false-positive rate). Cells that do mean boots are sharing conditions
and the CIs are too narrow — fix the allocation (more spread-out
boots) before claiming; a magnitude gate is not a substitute. The A/A
CIs also tell you what effect sizes this config can resolve. Re-run
the A/A when the platform changes (VM hardware generation, node
version, bench app changes).
## Interim progress display
The launcher's progress digest shows, per route/phase, the running rps
effect and a directional confidence — P(candidate is actually
faster/slower | boots so far), the Student-t posterior under a flat
prior (not a p-value). It appears from 4 completed boots. Display
only: runs complete their planned allocation, and claims come only
from the final fixed-n analysis.
## Fingerprints
Every result row records a build fingerprint (dist-file hash + version
string) read from the tree that actually served requests. The analysis
header verifies them: inconsistent fingerprints within an arm
invalidate the run (a VM measured the wrong build). Identical
fingerprints across arms with different version strings can be
legitimate — the hash covers the compiled server files, so client-only
changes don't move it; check the version strings before declaring an
accidental A/A.
## Honest reporting
- State the platform (e.g. "x86 Xeon sandbox VMs") next to any number.
Magnitudes are platform-dependent — GC's share of request time
scales with CPU speed — so direction and mechanism transfer between
platforms, percentages do not.
- Print per-boot values; if boots disagree in sign, the mean is not a
finding, and say so.
- Never conclude anything from the live streaming estimates. Peeking
at sequential results and stopping when p looks good is a classic
way to manufacture false positives.
#!/usr/bin/env node
// Post-hoc (re-)analysis of runs at the boot level. Reads ONLY the
// results db: a run-dir argument is imported (idempotently) and
// verified first, a bare run id analyzes what the db already holds.
// node bench-analyze.mjs <runDir|runId> [--base <arm>] [--cand <arm>]
import fs from 'node:fs'
import path from 'node:path'
import { analyzeE2eRows } from './bench-stats.mjs'
import { openDb, importRun, loadRows, runMeta, verify } from './bench-db.mjs'
const argv = process.argv.slice(2)
const target = argv.find((a) => !a.startsWith('--'))
const get = (name) => {
const i = argv.indexOf(name)
return i >= 0 ? argv[i + 1] : undefined
}
if (!target) {
console.error(
'usage: node bench-analyze.mjs <runDir|runId> [--base arm] [--cand arm]'
)
process.exit(1)
}
const db = openDb()
let runId
if (fs.existsSync(target)) {
runId = importRun(db, target).runId
} else {
runId = path.basename(target)
}
const { failures, notes } = verify(db, runId)
for (const n of notes) console.log(`note: ${n}`)
if (failures.length) {
console.error(`RESULTS DB VERIFY FAILED:\n ${failures.join('\n ')}`)
process.exit(1)
}
const rows = loadRows(db, runId)
const arms = [...new Set(rows.map((r) => r.arm))]
if (arms.length !== 2) {
console.error(`expected exactly 2 arms, found: ${arms.join(', ')}`)
process.exit(1)
}
// Which arm is base? Row order cannot answer this (ABBA runs the
// candidate first), so require an explicit source: the run's meta,
// a conventional name, or the --base flag.
const meta = runMeta(db, runId)?.meta
const base =
get('--base') ??
(meta && arms.includes(meta.base) ? meta.base : undefined) ??
['base', 'synced'].find((n) => arms.includes(n))
if (!base) {
console.error(
`cannot determine the base arm from {${arms.join(', ')}}: ` +
'no meta, no arm named "base"/"synced" — pass --base <arm>'
)
process.exit(1)
}
const cand = get('--cand') ?? arms.find((a) => a !== base)
const boots = new Set(rows.map((r) => r.vm)).size
console.log(`${runId} boots=${boots} arms: ${base} (base) vs ${cand}`)
if (meta?.pr)
console.log(
`PR: ${meta.pr.title ? `"${meta.pr.title}" — ` : ''}${meta.pr.url}`
)
for (const a of meta?.arms ?? [])
if (a.title) console.log(` ${a.name}: "${a.title}"`)
if (rows[0].route === '') {
// Micro (sandbox-ab) samples: phase holds the payload name.
analyzeE2eRows(rows, base, cand, ['mean', 'p50', 'p95', 'p99', 'gcMs'])
} else {
// No p99 for e2e: the load phases are far too small for it.
analyzeE2eRows(rows, base, cand, [
'rps',
'median',
'mean',
'p95',
'ttfb',
'docKb',
'gzipKb',
'flightKb',
'rss',
'rssHw',
])
}
#!/usr/bin/env node
// Recover a run whose local launcher died (session teardown, crash):
// the remote VMs keep executing their detached loops regardless, so the
// data is usually still there. Reads the run's status.json for the VM
// names, waits for each VM's loop to finish, downloads its results,
// removes the VM, and runs the boot-level analysis.
//
// node bench-collect.mjs <runDir> [--deadline-min 280]
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import fs from 'node:fs'
import path from 'node:path'
import { loadConfig, sandboxScope } from './config.mjs'
const execFileP = promisify(execFile)
const CONFIG = loadConfig()
const SCOPE = sandboxScope(CONFIG)
const argv = process.argv.slice(2)
const dir = argv.find((a) => !a.startsWith('--'))
const deadlineMin = argv.includes('--deadline-min')
? Number(argv[argv.indexOf('--deadline-min') + 1])
: 280
if (!dir || !fs.existsSync(path.join(dir, 'status.json'))) {
console.error('usage: node bench-collect.mjs <runDir with status.json>')
process.exit(1)
}
const statusPath = path.join(dir, 'status.json')
const st = JSON.parse(fs.readFileSync(statusPath, 'utf8'))
const vms = Object.keys(st.vms ?? {})
function writeStatus(patch) {
Object.assign(st, patch, { updatedAt: new Date().toISOString() })
fs.writeFileSync(statusPath, JSON.stringify(st, null, 2))
}
writeStatus({ phase: 'collecting (recovery)', pid: process.pid })
if (vms.length === 0) {
console.error(
'status.json lists no VMs — the run died before measurement; nothing to collect. ' +
'Check for a leaked snapshot builder with sandbox-sweep.mjs and relaunch the run.'
)
process.exit(1)
}
async function sb(args) {
const scoped = ['sandbox', ...args]
const sep = scoped.indexOf('--')
scoped.splice(sep < 0 ? scoped.length : sep, 0, ...SCOPE)
const { stdout } = await execFileP(CONFIG.vercelBin, scoped, {
maxBuffer: 1 << 26,
})
return stdout
}
const pending = new Map(vms.map((vm, i) => [vm, i]))
const collected = []
const deadline = Date.now() + deadlineMin * 60000
while (pending.size > 0 && Date.now() < deadline) {
for (const [vm, idx] of [...pending]) {
let out
try {
out = await sb([
'exec',
vm,
'--timeout',
'2m',
'--',
'bash',
'-c',
'cat /vercel/sandbox/loop.done 2>/dev/null || echo RUNNING',
])
} catch (e) {
// VM gone (timed out or removed): its data is lost; say so and move on.
console.error(
`${vm}: unreachable (${e.message.split('\n')[0].slice(0, 100)}) — boot lost`
)
st.vms[vm] = { ...st.vms[vm], state: 'lost' }
writeStatus({})
pending.delete(vm)
continue
}
const state = out.trim().split('\n').pop()
if (state === 'RUNNING') continue
if (state === 'LOOPOK') {
const local = path.join(dir, `results-vm${idx}.jsonl`)
await sb(['cp', `${vm}:/vercel/sandbox/results.jsonl`, local])
if (fs.existsSync(local) && fs.statSync(local).size > 500) {
collected.push(local)
st.vms[vm] = { ...st.vms[vm], state: 'done' }
writeStatus({})
console.error(`${vm}: collected -> ${local}`)
} else {
console.error(`${vm}: results too small; keeping VM for inspection`)
pending.delete(vm)
continue
}
} else {
const tail = await sb([
'exec',
vm,
'--timeout',
'2m',
'--',
'bash',
'-c',
'tail -c 1500 /vercel/sandbox/loop.log',
])
console.error(`${vm}: loop ended ${state}; log tail:\n${tail}`)
}
try {
await sb(['rm', vm])
console.error(`${vm}: removed`)
} catch (e) {
console.error(
`${vm}: rm failed: ${e.message.split('\n')[0].slice(0, 100)}`
)
}
pending.delete(vm)
}
if (pending.size > 0) await new Promise((r) => setTimeout(r, 60000))
}
for (const [vm] of pending)
console.error(`${vm}: deadline exceeded, left running`)
if (collected.length === 0) {
console.error('nothing collected')
process.exit(1)
}
writeStatus({
phase: `done (recovered ${collected.length}/${vms.length} boots)`,
})
console.log(`\ncollected ${collected.length}/${vms.length} boots; analysis:`)
const { stdout } = await execFileP(
'node',
[
path.join(
path.dirname(new URL(import.meta.url).pathname),
'bench-analyze.mjs'
),
dir,
],
{ maxBuffer: 1 << 24 }
)
console.log(stdout)
This diff is collapsed.
// Shared statistics for the sandbox bench harnesses.
//
// Unit of analysis: the VM BOOT. Iterations within a boot share JIT
// state, heap layout, host, and phase-sequence position, so they are
// not independent samples (Kalibera & Jones, "Rigorous Benchmarking in
// Reasonable Time"; JMH forks). Each boot contributes ONE delta per
// metric (the mean of its paired within-boot deltas); confidence
// intervals and p-values are computed across boots. Within-boot
// statistics are printed as a diagnostic only — never as the claim.
// Two-sided critical values of Student's t at 97.5% (df 1..30).
const T975 = [
12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201,
2.179, 2.16, 2.145, 2.131, 2.12, 2.11, 2.101, 2.093, 2.086, 2.08, 2.074,
2.069, 2.064, 2.06, 2.056, 2.052, 2.048, 2.045, 2.042,
]
function tCritical975(df) {
if (df < 1) return Infinity
if (df <= 30) return T975[df - 1]
return 1.96 + 2.4 / df // adequate approximation past df=30
}
// Two-sided p for a one-sample t test against zero, via numerical
// integration of the t pdf (small-df accuracy is what matters here —
// boots are few).
export function tTestP(values) {
const n = values.length
if (n < 2) return 1
if (values.some((v) => !Number.isFinite(v))) return 1
const mean = values.reduce((a, b) => a + b, 0) / n
const sd = Math.sqrt(
values.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1)
)
if (sd === 0) return mean === 0 ? 1 : 0
const t = Math.abs(mean / (sd / Math.sqrt(n)))
const df = n - 1
if (df === 1) {
// Student t with df=1 is Cauchy; the closed form avoids the fat
// tail truncating a numerical integration.
return Math.min(1, Math.max(0, 1 - (2 / Math.PI) * Math.atan(t)))
}
if (!Number.isFinite(t) || t > 45) {
// p underflows well past any claim threshold; also guards the
// integration loop below, whose step size vanishes against huge t.
return 0
}
const pdf = (x) => Math.exp(-((df + 1) / 2) * Math.log(1 + (x * x) / df))
let integral = 0
const STEP = 0.001
for (let x = t; x < t + 60; x += STEP) integral += pdf(x + STEP / 2) * STEP
let norm = 0
for (let x = 0; x < 80; x += STEP) norm += pdf(x + STEP / 2) * STEP
return Math.min(1, integral / norm)
}
// Anytime-valid confidence sequence for a running mean (asymptotic CS,
// Waudby-Smith & Ramdas). Unlike a t-CI, this interval is valid at
// EVERY peek simultaneously, so interim displays built on it cannot
// manufacture significance through repeated looking. Tuned to be
// tightest around ~12 boots.
export function confidenceSeq(values, alpha = 0.05) {
const n = values.length
// Below 6 samples the estimated variance is too unstable for the
// asymptotic guarantee; show nothing rather than something wrong.
if (n < 6) return null
const mean = values.reduce((a, b) => a + b, 0) / n
let sd = Math.sqrt(values.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1))
if (!Number.isFinite(sd)) return null
// Small-sample variance inflation (t-style): keeps the sequence
// honest at the n this harness actually runs (6..32 boots).
sd *= Math.sqrt((n - 1) / Math.max(1, n - 3))
const nOpt = 16
const rho2 = (2 * Math.log(2 / alpha)) / nOpt
const width =
sd *
Math.sqrt(
((2 * (n * rho2 + 1)) / (n * n * rho2)) *
Math.log((Math.sqrt(n * rho2 + 1) * 2) / alpha)
)
return { mean, lo: mean - width, hi: mean + width, n }
}
// What each metric measures and which direction is an improvement.
// Deltas are always relative (%), so the unit answers "% of what".
export const METRICS = {
rps: { unit: 'req/s', better: 'higher' },
docKb: { unit: 'KB', better: 'lower' },
gzipKb: { unit: 'KB', better: 'lower' },
flightKb: { unit: 'KB', better: 'lower' },
median: { unit: 'ms', better: 'lower' },
mean: { unit: 'ms', better: 'lower' },
p95: { unit: 'ms', better: 'lower' },
p99: { unit: 'ms', better: 'lower' },
ttfb: { unit: 'ms', better: 'lower' },
gcMs: { unit: 'ms', better: 'lower' },
p50: { unit: 'ms', better: 'lower' },
rss: { unit: 'MB', better: 'lower' },
rssHw: { unit: 'MB peak', better: 'lower' },
}
// One metric in one phase: per-boot arrays of paired deltas in, verdict out.
export function bootLevelStats(perBootDeltas) {
const boots = perBootDeltas.filter((d) => d.length > 0)
const bootMeans = boots.map((d) => d.reduce((a, b) => a + b, 0) / d.length)
const n = bootMeans.length
if (n === 0) return null
const mean = bootMeans.reduce((a, b) => a + b, 0) / n
const all = boots.flat()
const result = {
mean,
boots: n,
bootMeans,
pairs: all.length,
withinP: tTestP(all),
}
if (n >= 2) {
const sd = Math.sqrt(
bootMeans.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1)
)
result.ci95 = (tCritical975(n - 1) * sd) / Math.sqrt(n)
result.p = tTestP(bootMeans)
} else {
result.ci95 = Infinity
result.p = 1
}
return result
}
export function formatStat(name, candName, baseName, s) {
if (s === null) return ` ${name.padEnd(6)} (no data)`
const pct = (x) => `${(x * 100).toFixed(1)}%`
const ci = s.ci95 === Infinity ? '±∞' : `±${(s.ci95 * 100).toFixed(1)}`
const m = METRICS[name]
const meta = m
? ` [${m.unit}; ${s.mean > 0 === (m.better === 'higher') ? 'IMPROVEMENT' : 'regression'} if real]`
: ''
// Byte metrics are deterministic per build, so a ±0.0 near-zero cell
// with p=0 is normal; the absolute values say whether it matters.
const abs =
s.absBase !== undefined && m?.unit === 'KB'
? ` [${s.absBase.toFixed(1)}KB -> ${s.absCand.toFixed(1)}KB]`
: ''
return (
` ${name.padEnd(6)} ${candName} vs ${baseName}: ${pct(s.mean)} ${ci}${meta}${abs} ` +
`(boots=${s.boots}${s.boots < 3 ? ' — TOO FEW FOR CLAIMS' : ''}, p=${s.p.toFixed(4)})` +
` perBoot ${s.bootMeans.map((m) => pct(m)).join(' ')}` +
` [pairs=${s.pairs} within-run p=${s.withinP.toFixed(4)} — diagnostic only]`
)
}
// E2e rows: {vm, arm, block, run, route, phase, <metrics...>}. Pairs are
// (vm, block, run); the boot is the vm. Returns nothing; prints.
export function analyzeE2eRows(rows, baseName, candName, metrics) {
const fps = {}
for (const r of rows)
(fps[r.arm] ||= new Set()).add(r.ver ? `${r.fp}/${r.ver}` : `${r.fp}`)
console.log(
`\nfingerprints: ${baseName}=${[...(fps[baseName] ?? [])].join(',')} ` +
`${candName}=${[...(fps[candName] ?? [])].join(',')}`
)
if ((fps[baseName]?.size ?? 0) !== 1 || (fps[candName]?.size ?? 0) !== 1) {
// A VM measured the wrong build; numbers would look official and be
// meaningless. Refuse instead of printing stats with a warning.
console.log(
'!! inconsistent fingerprints within an arm — RESULTS INVALID, no stats'
)
process.exitCode = 1
return false
}
const baseFp = [...fps[baseName]][0]?.split('/')[0]
const candFp = [...fps[candName]][0]?.split('/')[0]
if (baseFp !== undefined && candFp !== undefined) {
console.log(
baseFp === candFp
? 'fingerprint files byte-identical between arms (A/A for those files; ' +
'arms may still differ elsewhere — check version strings)'
: 'arms differ (A/B mode)'
)
}
// "Absent" must be distinguishable from "identical": metrics the run
// never captured are named at the end instead of silently missing.
const captured = new Set()
for (const phase of [
...new Set(rows.map((r) => `${r.route ?? ''} ${r.phase}`)),
].sort()) {
console.log(`\n${phase}`)
const inPhase = (r) => `${r.route ?? ''} ${r.phase}` === phase
for (const metric of metrics) {
const perBoot = []
const baseVals = []
const candVals = []
for (const vm of [...new Set(rows.map((r) => r.vm))]) {
const deltas = []
for (const r of rows.filter(
(x) => x.vm === vm && inPhase(x) && x.arm === candName
)) {
const b = rows.find(
(x) =>
x.vm === vm &&
inPhase(x) &&
x.arm === baseName &&
x.block === r.block &&
x.run === r.run
)
if (b && b[metric] > 0 && r[metric] > 0) {
deltas.push((r[metric] - b[metric]) / b[metric])
baseVals.push(b[metric])
candVals.push(r[metric])
}
}
perBoot.push(deltas)
}
const s = bootLevelStats(perBoot)
if (s !== null && s.pairs > 0) {
captured.add(metric)
s.absBase = baseVals.reduce((a, b) => a + b, 0) / baseVals.length
s.absCand = candVals.reduce((a, b) => a + b, 0) / candVals.length
console.log(formatStat(metric, candName, baseName, s))
}
}
}
const absent = metrics.filter((m) => !captured.has(m))
if (absent.length > 0) {
console.log(`\nnot captured on this run: ${absent.join(', ')}`)
}
return true
}
#!/usr/bin/env node
// Usage: node bench-status.mjs [--all]
//
// The only reliable way to know what's in flight. Session restarts silently
// kill background launchers while their detached VMs keep measuring, and a
// dead launcher's log file still ends with a healthy-looking progress line —
// never infer liveness from log tails. This reads each run's status.json,
// checks whether the recorded launcher pid is alive, and prints the recovery
// action per run.
import fs from 'fs'
import path from 'path'
import { loadConfig } from './config.mjs'
const CONFIG = loadConfig({ requireScope: false })
const E2E = path.join(CONFIG.cacheDir, 'e2e')
const all = process.argv.includes('--all')
const dirs = fs.existsSync(E2E)
? fs
.readdirSync(E2E)
.filter((d) => d.startsWith('run-'))
.map((d) => path.join(E2E, d))
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
: []
const DAY = 24 * 3600 * 1000
let shown = 0
for (const dir of dirs) {
const sf = path.join(dir, 'status.json')
if (!fs.existsSync(sf)) continue
let st
try {
st = JSON.parse(fs.readFileSync(sf, 'utf8'))
} catch {
continue
}
const fresh = fs.statSync(sf).mtimeMs > Date.now() - DAY
let alive = false
if (st.pid) {
try {
process.kill(st.pid, 0)
alive = true
} catch {}
}
if (!all && !fresh && !alive) {
continue
}
const ageMin = st.updatedAt
? Math.round((Date.now() - new Date(st.updatedAt).getTime()) / 60000)
: null
const vms = Object.values(st.vms || {})
const rows = vms.reduce((s, v) => s + (v.rows || 0), 0)
let action
if (st.phase === 'done') {
action = 'complete — bench-analyze.mjs re-reads it any time'
} else if (alive) {
action = 'RUNNING — leave it alone'
} else if (
(rows > 0 || st.phase === 'measuring') &&
ageMin !== null &&
ageMin > 290
) {
action =
'DEAD and its VMs have expired — whatever was collected is in the ' +
'run dir/results db; relaunch if more data is needed'
} else if (rows > 0 || st.phase === 'measuring') {
action =
`DEAD but VMs may still hold data — node scripts/bench-collect.mjs ${dir}` +
' (measurement VMs time out ~5h after launch; collect before that)'
} else {
action =
'DEAD before measurement — safe to relaunch (caches make it cheap); ' +
'check for leaked builder VMs with sandbox-sweep.mjs'
}
console.log(
`${path.basename(dir)}\n` +
` phase=${st.phase}` +
(st.error
? ` error=${JSON.stringify(String(st.error).slice(0, 140))}`
: '') +
` pid=${st.pid ?? '?'}(${alive ? 'alive' : 'dead'})` +
(ageMin !== null ? ` updated=${ageMin}m ago` : '') +
` rows=${rows}${st.rowsExpected ? `/${st.rowsExpected}` : ''}\n` +
` -> ${action}`
)
shown++
}
if (!shown) {
console.log('no recent runs (use --all to list everything)')
}
// Configuration for the sandbox-bench scripts.
//
// Everything machine- or team-specific lives in a config file OUTSIDE the
// repo (never commit team/project names into the repo):
// ~/.config/sandbox-bench/config.json
//
// Required fields (no defaults — ask the user once, then save):
// team Vercel team slug the sandboxes bill to
// project Vercel project the sandboxes attach to
// Optional fields:
// cacheDir where clones/artifacts/snapshot-ids live
// (default ~/.cache/sandbox-bench)
// reactRepo existing react checkout to use (default: auto-clone
// into <cacheDir>/react)
// nextRepo existing next.js checkout to use (default: auto-clone
// into <cacheDir>/next)
// reactRepoUrl clone/fetch URL (default https://github.com/react/react.git)
// nextRepoUrl clone/fetch URL (default https://github.com/vercel/next.js.git)
// vercelBin vercel CLI binary (default "vercel")
//
// CLI: node config.mjs show
// node config.mjs set team=<slug> project=<name> [key=value...]
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
const CONFIG_DIR = path.join(os.homedir(), '.config', 'sandbox-bench')
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json')
export function loadConfig({ requireScope = true } = {}) {
let cfg = {}
if (fs.existsSync(CONFIG_FILE)) {
cfg = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'))
}
// Env overrides for CI or one-off use.
cfg.team = process.env.SANDBOX_BENCH_TEAM ?? cfg.team
cfg.project = process.env.SANDBOX_BENCH_PROJECT ?? cfg.project
cfg.cacheDir = expandHome(
process.env.SANDBOX_BENCH_CACHE ?? cfg.cacheDir ?? '~/.cache/sandbox-bench'
)
cfg.reactRepo = expandHome(
process.env.SANDBOX_BENCH_REACT_REPO ?? cfg.reactRepo ?? ''
)
cfg.nextRepo = expandHome(
process.env.SANDBOX_BENCH_NEXT_REPO ?? cfg.nextRepo ?? ''
)
cfg.reactRepoUrl = cfg.reactRepoUrl ?? 'https://github.com/react/react.git'
cfg.nextRepoUrl = cfg.nextRepoUrl ?? 'https://github.com/vercel/next.js.git'
cfg.vercelBin = cfg.vercelBin ?? 'vercel'
if (requireScope && (!cfg.team || !cfg.project)) {
throw new Error(
'sandbox-bench is not configured: team and project are required.\n' +
'Ask the user which Vercel team + project the sandbox VMs should ' +
'run under, then save them with:\n' +
` node ${path.relative(process.cwd(), new URL(import.meta.url).pathname)} ` +
'set team=<team-slug> project=<project-name>\n' +
'(Stored in ~/.config/sandbox-bench/config.json, not in the repo.)'
)
}
return cfg
}
export function saveConfig(patch) {
fs.mkdirSync(CONFIG_DIR, { recursive: true })
const existing = fs.existsSync(CONFIG_FILE)
? JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'))
: {}
const merged = { ...existing, ...patch }
fs.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2) + '\n')
return merged
}
function expandHome(p) {
if (!p) return p
return p.startsWith('~/') ? path.join(os.homedir(), p.slice(2)) : p
}
// Scope flags appended to every `vercel sandbox` call. Never widen scope
// beyond the configured team/project: the project may be shared.
export function sandboxScope(cfg) {
return ['--team', cfg.team, '--project', cfg.project]
}
// Repos: use the configured checkout, else clone lazily into the cache.
function ensureRepo(cfg, checkout, url, name) {
if (checkout && fs.existsSync(path.join(checkout, '.git'))) return checkout
const dest = path.join(cfg.cacheDir, name)
if (fs.existsSync(path.join(dest, '.git'))) return dest
fs.mkdirSync(cfg.cacheDir, { recursive: true })
console.error(`cloning ${url} into ${dest} (one-time)...`)
execFileSync('git', ['clone', '--filter=blob:none', url, dest], {
stdio: 'inherit',
})
return dest
}
export function ensureReactRepo(cfg) {
return ensureRepo(cfg, cfg.reactRepo, cfg.reactRepoUrl, 'react')
}
export function ensureNextRepo(cfg) {
return ensureRepo(cfg, cfg.nextRepo, cfg.nextRepoUrl, 'next')
}
// ------------------------------------------------------------------ CLI
// realpath both sides: /tmp vs /private/tmp (macOS) or any symlinked
// invocation path must not silently skip the CLI (a no-op "config set"
// would leave stale team/project in effect with exit 0).
function isMain() {
if (!process.argv[1]) return false
try {
return (
fs.realpathSync(process.argv[1]) ===
fs.realpathSync(new URL(import.meta.url).pathname)
)
} catch {
return false
}
}
if (isMain()) {
const [cmd, ...rest] = process.argv.slice(2)
if (cmd === 'show') {
let cfg
try {
cfg = loadConfig({ requireScope: false })
} catch (e) {
console.error(e.message)
process.exit(1)
}
console.log(JSON.stringify(cfg, null, 2))
if (!cfg.team || !cfg.project) {
console.error('\nNOT CONFIGURED: team/project missing (see file header).')
process.exit(2)
}
} else if (cmd === 'set') {
const patch = {}
for (const kv of rest) {
const i = kv.indexOf('=')
if (i < 0) {
console.error(`bad argument "${kv}", want key=value`)
process.exit(1)
}
patch[kv.slice(0, i)] = kv.slice(i + 1)
}
const merged = saveConfig(patch)
console.log(`saved: ${JSON.stringify(merged, null, 2)}`)
} else {
console.error('usage: node config.mjs show | set key=value [key=value...]')
process.exit(1)
}
}
This diff is collapsed.
This diff is collapsed.
// List/remove leaked bench sandboxes. Every VM the skill's scripts
// create is named sbench-* and tagged purpose=sandbox-bench; the
// harnesses remove their VMs in finally blocks, but a killed local
// process leaks them until their timeout.
//
// The project may be shared, so removal is deliberately conservative:
// a VM is only listed when its name matches, its tag matches, AND it is
// older than --min-age-hours (default 3 — longer than any healthy run),
// and removal is per exact listed name.
//
// node sandbox-sweep.mjs # list what would be removed
// node sandbox-sweep.mjs --yes # remove
// node sandbox-sweep.mjs --min-age-hours 0 # include fresh VMs (danger:
// # only when nothing is active)
import { execFile } from 'child_process'
import { promisify } from 'util'
import { loadConfig, sandboxScope } from './config.mjs'
const execFileP = promisify(execFile)
const CONFIG = loadConfig()
const SCOPE = sandboxScope(CONFIG)
const argv = process.argv.slice(2)
const minAgeHours = argv.includes('--min-age-hours')
? Number(argv[argv.indexOf('--min-age-hours') + 1])
: 3
// Age from the CLI's "CREATED" column ("32 minutes ago", "2 hours ago").
function ageHours(words) {
const i = words.findIndex((w) => w === 'ago')
if (i < 2) return Infinity
const n = Number(words[i - 2])
const unit = words[i - 1]
if (!Number.isFinite(n)) return Infinity
if (unit.startsWith('second')) return n / 3600
if (unit.startsWith('minute')) return n / 60
if (unit.startsWith('hour')) return n
return n * 24
}
// Paginate: the CLI prints a cursor hint line when more pages exist.
const found = []
let cursor
for (let page = 0; page < 50; page++) {
const args = ['sandbox', 'list', '--limit', '100', ...SCOPE]
if (cursor) args.push('--cursor', cursor)
const { stdout, stderr } = await execFileP(CONFIG.vercelBin, args, {
maxBuffer: 1 << 24,
})
for (const line of stdout.split('\n')) {
const words = line.trim().split(/\s+/)
const name = words[0]
if (!/^sbench-/.test(name)) continue
if (!line.includes('purpose:sandbox-bench')) continue
const age = ageHours(words)
if (age < minAgeHours) {
console.log(
`skipping ${name} (${age.toFixed(1)}h old < --min-age-hours ${minAgeHours})`
)
continue
}
found.push(name)
}
cursor = `${stdout}\n${stderr}`.match(/--cursor\s+(\S+)/)?.[1]
if (!cursor) break
}
if (!found.length) {
console.log('no leaked bench sandboxes found')
process.exit(0)
}
const doIt = argv.includes('--yes')
let failures = 0
for (const name of found) {
if (doIt) {
try {
await execFileP(CONFIG.vercelBin, ['sandbox', 'rm', name, ...SCOPE])
console.log(`removed ${name}`)
} catch (e) {
failures++
console.error(`could not remove ${name}: ${e.message.split('\n')[0]}`)
}
} else {
console.log(`would remove ${name} (pass --yes)`)
}
}
process.exit(failures ? 1 : 0)
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