Unverified Commit 56825e5d authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

devlow-bench: percentile-based comparison and run retries (#93950)

A few changes to devlow-bench so the comparison output is easier to read
and so a couple of flaky page-load runs don't quietly poison the stats.

**compare**
- Show p50 / p90 / p99 instead of mean / p50 / p90, with Δ p50 and a
single Mann–Whitney p-value (Welch's t-test and Δ mean are gone — the
mean was dragging on bad runs).
- Hoist the modal sample count into an `n = 7 per metric` banner so only
the outlier rows carry `(n)`.

**runner**
- Each attempt's measurements are buffered locally and only merged on
success. Failed runs are retried (capped at 2× warmup+n) until we have a
clean n samples.
- Per-variant retry line plus an end-of-run summary noting which
variants recovered and which fell short.

**browser**
- `hardNavigation` / `reload` now throw when the navigation response is
missing or non-2xx. Previously a `200`-committed-but-broken page was
being recorded as a real sample.

The trigger was a run where 2 of 7 cold-build attempts hit an error
page, dragging the mean response size from 45 MB to 33 MB while the p50
was unchanged.

<!-- NEXT_JS_LLM_PR -->
parent 108e9652
......@@ -259,9 +259,17 @@ class BrowserSessionImpl implements BrowserSession {
await withRequestMetrics(metricName, page, async () => {
await measureTime(`${metricName}/start`)
const idle = networkIdle(page, 3000)
await page.goto(url, {
const response = await page.goto(url, {
waitUntil: 'commit',
})
if (!response) {
throw new Error(`Navigation to ${url} produced no response`)
}
if (!response.ok()) {
throw new Error(
`Navigation to ${url} returned HTTP ${response.status()}`
)
}
await measureTime(`${metricName}/html`, {
relativeTo: `${metricName}/start`,
})
......@@ -318,9 +326,15 @@ class BrowserSessionImpl implements BrowserSession {
await withRequestMetrics(metricName, page, async () => {
await measureTime(`${metricName}/start`)
const idle = networkIdle(page, 3000)
await page.reload({
const response = await page.reload({
waitUntil: 'commit',
})
if (!response) {
throw new Error('Reload produced no response')
}
if (!response.ok()) {
throw new Error(`Reload returned HTTP ${response.status()}`)
}
await measureTime(`${metricName}/html`, {
relativeTo: `${metricName}/start`,
})
......
......@@ -35,7 +35,7 @@ async function runCompareSubcommand(argv: string[]): Promise<void> {
if (args.help || args._.length === 0) {
console.log(`Usage: devlow-bench compare <baseline.csv> <current.csv>
Reads both snapshot CSVs and prints a side-by-side comparison table
with mean/p50/p90 plus Welch’s t and Mann–Whitney U p-values per metric.`)
with p50/p90/p99 plus a Mann–Whitney U p-value per metric.`)
if (args.help) return
}
if (args._.length !== 2) {
......
import picocolors from 'picocolors'
import { SnapshotRow } from './snapshot.js'
import { mannWhitneyU, summary, welchsTTest } from './statistics.js'
import { mannWhitneyU, quantile } from './statistics.js'
import { formatUnit } from './units.js'
const { bold, dim, green, red, underline } = picocolors
......@@ -72,7 +72,7 @@ export function printComparison(
console.log(bold(underline(`Comparison vs baseline: ${baselineLabel}`)))
}
const rows: FormattedRow[] = []
const pairs: { base: SampleGroup; cur: SampleGroup }[] = []
const onlyInCurrent: string[] = []
const onlyInBaseline: string[] = []
const skippedMismatch: string[] = []
......@@ -89,7 +89,7 @@ export function printComparison(
)
continue
}
rows.push(formatRow(base, cur))
pairs.push({ base, cur })
}
for (const [key, base] of baseline) {
if (!current.has(key)) {
......@@ -97,17 +97,32 @@ export function printComparison(
}
}
if (rows.length > 0) {
// Hoist the most common sample count for each side into a banner above the
// table; per-row `(n)` is then shown only for rows that deviate from it,
// so the eye-catching exceptions aren't drowned in repeated `(7)`s.
const baseMode = modeN(pairs.map((p) => p.base.samples.length))
const curMode = modeN(pairs.map((p) => p.cur.samples.length))
if (pairs.length > 0) {
if (baseMode != null && curMode != null) {
const banner =
baseMode === curMode
? `n = ${baseMode} per metric`
: `baseline n = ${baseMode}, current n = ${curMode}`
console.log(bold(banner))
}
const header = [
'Scenario · Variant',
'Metric',
'Baseline μ / p50 / p90 (n)',
'Current μ / p50 / p90 (n)',
'Δ mean',
'Baseline p50 / p90 / p99',
'Current p50 / p90 / p99',
'Δ p50',
'Δ%',
"Welch's p",
'MWU p',
'p',
]
const rows = pairs.map(({ base, cur }) =>
formatRow(base, cur, baseMode, curMode)
)
printTable(header, rows)
} else {
console.log(
......@@ -129,54 +144,85 @@ function logList(label: string, items: string[], max: number = 5): void {
console.log(dim(`${label} (${items.length}): ${shown}${suffix}`))
}
function formatRow(base: SampleGroup, cur: SampleGroup): FormattedRow {
const bs = summary(base.samples)
const cs = summary(cur.samples)
const delta = cs.mean - bs.mean
const deltaPct = bs.mean === 0 ? NaN : (delta / bs.mean) * 100
const welchs = welchsTTest(base.samples, cur.samples)
// Picks the most common n in the list. Ties are broken in favor of the
// larger n (treat "the typical fully-collected sample count" as the default).
// Returns null for an empty list.
function modeN(ns: number[]): number | null {
if (ns.length === 0) return null
const counts = new Map<number, number>()
for (const n of ns) counts.set(n, (counts.get(n) ?? 0) + 1)
let bestN = ns[0]
let bestCount = 0
for (const [n, c] of counts) {
if (c > bestCount || (c === bestCount && n > bestN)) {
bestN = n
bestCount = c
}
}
return bestN
}
function formatRow(
base: SampleGroup,
cur: SampleGroup,
baseMode: number | null,
curMode: number | null
): FormattedRow {
const bs = percentiles(base.samples)
const cs = percentiles(cur.samples)
const delta = cs.p50 - bs.p50
const deltaPct = bs.p50 === 0 ? NaN : (delta / bs.p50) * 100
const mwu = mannWhitneyU(base.samples, cur.samples)
// Color verdict uses Welch's p as the primary signal.
// Color verdict uses Mann–Whitney U's p as the significance signal, with
// the sign of the p50 shift determining improvement vs regression.
let verdict: RowVerdict
if (
Number.isFinite(welchs.p) &&
welchs.p < SIGNIFICANCE_THRESHOLD &&
delta !== 0
) {
if (Number.isFinite(mwu.p) && mwu.p < SIGNIFICANCE_THRESHOLD && delta !== 0) {
verdict = delta < 0 ? 'improved' : 'regressed'
}
return {
cells: [
`${base.scenario} · ${base.variant}`,
base.metric,
formatGroupCell(base, bs),
formatGroupCell(cur, cs),
formatGroupCell(base, bs, base.samples.length !== baseMode),
formatGroupCell(cur, cs, cur.samples.length !== curMode),
formatDelta(delta, base.unit),
Number.isFinite(deltaPct) ? `${deltaPct.toFixed(1)}%` : 'n/a',
formatP(welchs.p),
formatP(mwu.p),
],
verdict,
}
}
function percentiles(samples: number[]): {
p50: number
p90: number
p99: number
} {
return {
p50: quantile(samples, 0.5),
p90: quantile(samples, 0.9),
p99: quantile(samples, 0.99),
}
}
function formatGroupCell(
group: SampleGroup,
s: { mean: number; p50: number; p90: number }
s: { p50: number; p90: number; p99: number },
showN: boolean
): string {
const parts = [s.mean, s.p50, s.p90].map((v) =>
const parts = [s.p50, s.p90, s.p99].map((v) =>
splitFormattedUnit(v, group.unit)
)
const n = group.samples.length
const nSuffix = showN ? ` (${group.samples.length})` : ''
// If all three values render with the same unit suffix (e.g. all "requests"),
// only print the suffix on the last value to avoid "7 req / 7 req / 7 req".
if (
parts[0].suffix === parts[1].suffix &&
parts[1].suffix === parts[2].suffix
) {
return `${parts[0].num} / ${parts[1].num} / ${parts[2].num}${parts[2].suffix} (${n})`
return `${parts[0].num} / ${parts[1].num} / ${parts[2].num}${parts[2].suffix}${nSuffix}`
}
return `${parts[0].num}${parts[0].suffix} / ${parts[1].num}${parts[1].suffix} / ${parts[2].num}${parts[2].suffix} (${n})`
return `${parts[0].num}${parts[0].suffix} / ${parts[1].num}${parts[1].suffix} / ${parts[2].num}${parts[2].suffix}${nSuffix}`
}
function splitFormattedUnit(
......
......@@ -7,6 +7,7 @@ import {
intoFullInterface,
} from './index.js'
import { summary } from './statistics.js'
import { formatVariant } from './utils.js'
interface SampleSet {
samples: number[]
......@@ -14,6 +15,17 @@ interface SampleSet {
relativeTo?: string
}
interface BufferedSample {
value: number
unit: string
relativeTo?: string
}
// Total attempts per variant are capped at this multiple of the requested
// `warmup + n`. Allows retrying flaky runs without burning unbounded time when
// every attempt fails.
const MAX_ATTEMPT_MULTIPLIER = 2
export async function runScenarios(
scenarios: Scenario[],
iface: Interface,
......@@ -26,6 +38,9 @@ export async function runScenarios(
scenarios = scenarios.filter((scenario) => scenario.only)
}
scenarios = await fullIface.filterScenarios(scenarios)
let totalFailedAttempts = 0
let variantsWithRetries = 0
let variantsShortOfTarget = 0
let variants = []
for (const scenario of scenarios) {
let props = [{}]
......@@ -55,25 +70,23 @@ export async function runScenarios(
for (const variant of variants) {
const samplesByMetric = new Map<string, SampleSet>()
// Wrap the interface for this variant so that per-sample `measurement`
// calls (a) flow through to all underlying reporters (preserving Datadog /
// Snowflake / etc. behavior) and (b) get collected into samplesByMetric
// for aggregation. Only counted on non-warmup runs.
// Each attempt buffers its measurements here. On success we merge into
// `samplesByMetric`; on failure we discard, so a partial run can't
// pollute the aggregated stats. Downstream per-sample reporters (Datadog,
// console, …) still receive every measurement inline — only the
// aggregated per-variant samples are gated on success.
let collecting = false
let perRun = new Map<string, BufferedSample[]>()
const wrappedIface: FullInterface = {
...fullIface,
measurement: async (scenario, props, name, value, unit, relativeTo) => {
if (collecting) {
const existing = samplesByMetric.get(name)
if (existing) {
existing.samples.push(value)
} else {
samplesByMetric.set(name, {
samples: [value],
unit,
relativeTo,
})
let list = perRun.get(name)
if (!list) {
list = []
perRun.set(name, list)
}
list.push({ value, unit, relativeTo })
}
await fullIface.measurement(
scenario,
......@@ -86,18 +99,25 @@ export async function runScenarios(
},
}
const totalRuns = warmup + n
let aborted = false
for (let run = 0; run < totalRuns; run++) {
collecting = run >= warmup
// Only report run progress when the user is actually doing multiple
// runs. Single-sample runs don't need a "[1/1]" tag.
const runInfo =
totalRuns > 1
? run < warmup
? { run: run + 1, total: warmup, warmup: true }
: { run: run - warmup + 1, total: n, warmup: false }
: undefined
const maxAttempts = (warmup + n) * MAX_ATTEMPT_MULTIPLIER
const showRunInfo = warmup + n > 1
let warmupDone = 0
let collectedRuns = 0
let totalAttempts = 0
while (
(warmupDone < warmup || collectedRuns < n) &&
totalAttempts < maxAttempts
) {
totalAttempts++
const isWarmup = warmupDone < warmup
collecting = !isWarmup
perRun = new Map()
const runInfo = showRunInfo
? isWarmup
? { run: warmupDone + 1, total: warmup, warmup: true }
: { run: collectedRuns + 1, total: n, warmup: false }
: undefined
try {
const measurements = new Map()
await withCurrent(
......@@ -120,15 +140,49 @@ export async function runScenarios(
await wrappedIface.end(variant.scenario.name, variant.props)
}
)
if (collecting) {
// Commit the buffered samples for this run into the aggregate.
for (const [name, entries] of perRun) {
let set = samplesByMetric.get(name)
if (!set) {
const first = entries[0]
set = {
samples: [],
unit: first.unit,
relativeTo: first.relativeTo,
}
samplesByMetric.set(name, set)
}
for (const e of entries) {
set.samples.push(e.value)
}
}
collectedRuns++
} else {
warmupDone++
}
} catch (e) {
await wrappedIface.error(variant.scenario.name, variant.props, e)
process.exitCode = 1
aborted = true
break
// Loop continues; the buffered samples for this attempt are dropped
// when `perRun` is replaced on the next iteration.
}
}
if (!aborted && samplesByMetric.size > 0) {
const failedAttempts = totalAttempts - warmupDone - collectedRuns
if (failedAttempts > 0) {
const label = formatVariant(variant.scenario.name, variant.props)
console.log(
`${label}: collected ${collectedRuns}/${n} samples after ${totalAttempts} attempts (${failedAttempts} failed)`
)
totalFailedAttempts += failedAttempts
variantsWithRetries++
}
if (collectedRuns < n) {
process.exitCode = 1
variantsShortOfTarget++
}
if (samplesByMetric.size > 0) {
const stats: Record<string, VariantStatistic> = {}
for (const [name, set] of samplesByMetric) {
stats[name] = {
......@@ -146,5 +200,23 @@ export async function runScenarios(
}
}
if (totalFailedAttempts > 0) {
const recovered = variantsWithRetries - variantsShortOfTarget
const parts: string[] = []
if (recovered > 0) {
parts.push(
`${recovered} variant${recovered === 1 ? '' : 's'} hit n=${n} after retries`
)
}
if (variantsShortOfTarget > 0) {
parts.push(
`${variantsShortOfTarget} variant${variantsShortOfTarget === 1 ? '' : 's'} fell short of n=${n}`
)
}
console.log(
`\n${totalFailedAttempts} failed attempt${totalFailedAttempts === 1 ? '' : 's'} across ${variantsWithRetries} variant${variantsWithRetries === 1 ? '' : 's'}: ${parts.join('; ')}.`
)
}
await fullIface.finish()
}
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