Unverified Commit 925e24e5 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

devlow: add run sampling snapshots and comparison reports (#93833)

A lot of this was written with Claude. We lean a lot on published
libraries for the statistics, so I've got confidence in them.

This adds top-level commands to devlow, `run`, and `compare`, though
we're still backwards compatible with `run` being the default if no
command is specified.

- `--n=<N>` runs each variant N times, `--warmup=<N>` discards the first
N runs (don't use on cold-start metrics). Default behavior is unchanged
at n=1.
- Every run now writes a snapshot CSV to
`.devlow-bench/snapshots/<ts>.csv` (long format, one row per sample, so
mixed-unit metrics share a file). Override with `--snapshot=<path>`.
- `--compare` prints a side-by-side table at the end of a run against
the newest snapshot. `--baseline=<path>` points at a specific file or
directory.
- `devlow-bench compare <baseline.csv> <current.csv>` is a separate
subcommand for diffing two existing snapshots without rerunning
anything.

For every scenario/variant/metric combination, it shows baseline vs
current `mean / p50 / p90 (n)`, the absolute and percent delta, and two
p-values.
parent 079df0f6
......@@ -2004,6 +2004,9 @@ importers:
inquirer:
specifier: ^9.2.7
version: 9.2.23
jstat:
specifier: ^1.9.6
version: 1.9.6
minimist:
specifier: ^1.2.8
version: 1.2.8
......@@ -12360,6 +12363,9 @@ packages:
resolution: {integrity: sha512-4Dj8Rf+fQ+/Pn7C5qeEX02op1WfOss3PKTE9Nsop3Dx+6UPxlm1dr/og7o2cRa5hNN07CACr4NFzRLtj/rjWog==}
engines: {'0': node >=0.6.0}
jstat@1.9.6:
resolution: {integrity: sha512-rPBkJbK2TnA8pzs93QcDDPlKcrtZWuuCo2dVR0TFLOJSxhqfWOVCSp8aV3/oSbn+4uY4yw1URtLpHQedtmXfug==}
jsx-ast-utils@3.3.5:
resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}
engines: {node: '>=4.0'}
......@@ -16519,6 +16525,7 @@ packages:
sliced@1.0.1:
resolution: {integrity: sha512-VZBmZP8WU3sMOZm1bdgTadsQbcscK0UM8oKxKVBs4XAhUo2Xxzm/OFMGBkPusxw9xL3Uy8LrzEqGqJhclsr0yA==}
deprecated: Unsupported
slide@1.1.6:
resolution: {integrity: sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==}
......@@ -17963,11 +17970,11 @@ packages:
uuid@2.0.3:
resolution: {integrity: sha512-FULf7fayPdpASncVy4DLh3xydlXEJJpvIELjYjNeQWYUZ9pclcpvCZSr2gkmN2FrrGcI7G/cJsIEwk5/8vfXpg==}
deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
uuid@3.3.3:
resolution: {integrity: sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ==}
deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
hasBin: true
uuid@8.3.2:
......@@ -23774,7 +23781,7 @@ snapshots:
dependencies:
'@typescript-eslint/tsconfig-utils': 8.46.0(typescript@6.0.2)
'@typescript-eslint/types': 8.46.0
debug: 4.4.0
debug: 4.4.3
typescript: 6.0.2
transitivePeerDependencies:
- supports-color
......@@ -23798,7 +23805,7 @@ snapshots:
'@typescript-eslint/types': 8.46.0
'@typescript-eslint/typescript-estree': 8.46.0(typescript@6.0.2)
'@typescript-eslint/utils': 8.46.0(eslint@9.37.0(jiti@2.6.1))(typescript@6.0.2)
debug: 4.4.0
debug: 4.4.3
eslint: 9.37.0(jiti@2.6.1)
ts-api-utils: 2.1.0(typescript@6.0.2)
typescript: 6.0.2
......@@ -27337,7 +27344,7 @@ snapshots:
esbuild-register@3.6.0(esbuild@0.25.9):
dependencies:
debug: 4.4.0
debug: 4.4.3
esbuild: 0.25.9
transitivePeerDependencies:
- supports-color
......@@ -30863,6 +30870,8 @@ snapshots:
json-schema: 0.2.3
verror: 1.10.0
jstat@1.9.6: {}
jsx-ast-utils@3.3.5:
dependencies:
array-includes: 3.1.8
......@@ -45,6 +45,7 @@
"dependencies": {
"@datadog/datadog-api-client": "^1.13.0",
"inquirer": "^9.2.7",
"jstat": "^1.9.6",
"minimist": "^1.2.8",
"picocolors": "1.0.1",
"pidusage-tree": "^2.0.5",
......
......@@ -3,8 +3,60 @@ import { setCurrentScenarios } from './describe.js'
import { join } from 'path'
import { Scenario, ScenarioVariant, runScenarios } from './index.js'
import compose from './interfaces/compose.js'
import { groupRows, printComparison } from './compare.js'
import { readSnapshot, resolveCompareTarget } from './snapshot.js'
import { pathToFileURL } from 'url'
const SUBCOMMANDS = new Set(['run', 'compare'])
;(async () => {
// Subcommand dispatch. `devlow-bench run [opts] scenario.mjs` and
// `devlow-bench compare <a.csv> <b.csv>` are the explicit forms. A bare
// `devlow-bench <script>` falls through to legacy run-mode for back-compat.
const argv = process.argv.slice(2)
const first = argv[0]
const sub = first && SUBCOMMANDS.has(first) ? first : 'run'
const rest = first && SUBCOMMANDS.has(first) ? argv.slice(1) : argv
if (sub === 'compare') {
await runCompareSubcommand(rest)
return
}
await runRunSubcommand(rest)
})().catch((e) => {
console.error(e.stack)
process.exit(1)
})
async function runCompareSubcommand(argv: string[]): Promise<void> {
const args = minimist(argv, {
alias: { '?': 'help', h: 'help' },
})
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.`)
if (args.help) return
}
if (args._.length !== 2) {
console.error(
`devlow-bench compare: expected 2 positional CSV paths, got ${args._.length}.`
)
console.error('Usage: devlow-bench compare <baseline.csv> <current.csv>')
process.exit(1)
}
const [baselinePath, currentPath] = args._
const [baseRows, curRows] = await Promise.all([
readSnapshot(baselinePath),
readSnapshot(currentPath),
])
printComparison(groupRows(baseRows), groupRows(curRows), {
baselineLabel: baselinePath,
currentLabel: currentPath,
})
}
async function runRunSubcommand(argv: string[]): Promise<void> {
const knownArgs = new Set([
'scenario',
's',
......@@ -15,12 +67,17 @@ import { pathToFileURL } from 'url'
'snowflake',
'interactive',
'i',
'n',
'warmup',
'snapshot',
'compare',
'baseline',
'help',
'h',
'?',
'_',
])
const args = minimist(process.argv.slice(2), {
const args = minimist(argv, {
alias: {
s: 'scenario',
j: 'json',
......@@ -28,41 +85,40 @@ import { pathToFileURL } from 'url'
'?': 'help',
h: 'help',
},
// `compare` is strictly a boolean toggle now (use --baseline=<path> for
// the value form). Declaring it here prevents `--compare scenario.mjs`
// from consuming the scenario as the flag value.
boolean: ['compare'],
})
if (args.help || (Object.keys(args).length === 1 && args._.length === 0)) {
console.log('Usage: devlow-bench [options] <scenario files>')
console.log('## Selecting scenarios')
console.log(
' --scenario=<filter>, -s=<filter> Only run the scenario with the given name'
)
console.log(
' --interactive, -i Select scenarios and variants interactively'
)
console.log(
' --<prop>=<value> Filter by any variant property defined in scenarios'
)
console.log('## Output')
console.log(
' --json=<path>, -j=<path> Write the results to the given path as JSON'
)
console.log(
' --console Print the results to the console'
)
console.log(
' --datadog[=<hostname>] Upload the results to Datadog'
)
console.log(
' (requires DATADOG_API_KEY environment variables)'
)
console.log(
' --snowflake[=<batch-uri>] Upload the results to Snowflake'
)
console.log(
' (requires SNOWFLAKE_TOPIC_NAME and SNOWFLAKE_SCHEMA_ID and environment variables)'
)
console.log('## Help')
console.log(' --help, -h, -? Show this help')
console.log(`Usage: devlow-bench [run] [options] <scenario files>
devlow-bench compare <baseline.csv> <current.csv>
## Selecting scenarios
--scenario=<filter>, -s=<filter> Only run the scenario with the given name
--interactive, -i Select scenarios and variants interactively
--<prop>=<value> Filter by any variant property defined in scenarios
## Repeated sampling
--n=<number> Run each variant N times. Reports mean/p50/p90 per metric.
Default: 1.
--warmup=<number> Discard the first N runs of each variant before sampling.
Default: 0. Do NOT enable when measuring cold-start metrics.
## Snapshots & comparison
--snapshot=<path> Override the snapshot CSV path.
Default: ./.devlow-bench/snapshots/<ts>.csv. Snapshots are always written.
--compare Print a comparison table at end of run. Baseline = newest snapshot,
unless --baseline overrides.
--baseline=<path> Explicit baseline (file or directory). Implies --compare.
## Output
--json=<path>, -j=<path> Write the results to the given path as JSON
--console Print the results to the console
--datadog[=<hostname>] Upload the results to Datadog
(requires DATADOG_API_KEY environment variables)
--snowflake[=<batch-uri>] Upload the results to Snowflake
(requires SNOWFLAKE_TOPIC_NAME and SNOWFLAKE_SCHEMA_ID and environment variables)
## Help
--help, -h, -? Show this help`)
if (args.help) return
}
const scenarios: Scenario[] = []
......@@ -103,10 +159,46 @@ import { pathToFileURL } from 'url'
return variants
},
}
// Validation (clamp to non-negative integers, default n=1/warmup=0) is
// delegated to runScenarios — see runner.ts.
const n = typeof args.n === 'number' ? args.n : 1
const warmup = typeof args.warmup === 'number' ? args.warmup : 0
// Snapshot is always on. `--snapshot=<path>` overrides the default path.
const snapshotPath =
typeof args.snapshot === 'string' ? args.snapshot : undefined
const snapshotIface = (await import('./interfaces/snapshot.js')).default({
path: snapshotPath,
})
// Comparison: enabled by either --compare (boolean) or --baseline=<path>.
// The baseline is the value of --baseline if given, else "auto" (newest
// snapshot in the default snapshot dir).
const compareEnabled =
args.compare === true || typeof args.baseline === 'string'
let compareIface: any = null
if (compareEnabled) {
const baselineArg = typeof args.baseline === 'string' ? args.baseline : true
const baselinePath = await resolveCompareTarget(
baselineArg,
snapshotIface.resolvedPath
)
if (baselinePath == null) {
console.error(
'No baseline snapshot found. Run devlow-bench at least once, or pass --baseline=<path>.'
)
process.exit(1)
}
compareIface = await (
await import('./interfaces/compare.js')
).default({ baselinePath })
}
let ifaces = [
cliIface,
args.interactive && (await import('./interfaces/interactive.js')).default(),
args.json && (await import('./interfaces/json.js')).default(args.json),
args.json &&
(await import('./interfaces/json.js')).default(args.json, { n }),
args.datadog &&
(await import('./interfaces/datadog.js')).default(
typeof args.datadog === 'string' ? { host: args.datadog } : undefined
......@@ -118,10 +210,9 @@ import { pathToFileURL } from 'url'
: undefined
),
args.console !== false &&
(await import('./interfaces/console.js')).default(),
(await import('./interfaces/console.js')).default({ n }),
compareIface,
snapshotIface,
].filter((x) => x)
await runScenarios(scenarios, compose(...ifaces))
})().catch((e) => {
console.error(e.stack)
process.exit(1)
})
await runScenarios(scenarios, compose(...ifaces), { n, warmup })
}
import picocolors from 'picocolors'
import { SnapshotRow } from './snapshot.js'
import { mannWhitneyU, summary, welchsTTest } from './statistics.js'
import { formatUnit } from './units.js'
const { bold, dim, green, red, underline } = picocolors
const SIGNIFICANCE_THRESHOLD = 0.05
type RowVerdict = 'improved' | 'regressed' | undefined
interface FormattedRow {
cells: string[]
verdict: RowVerdict
}
export interface SampleGroup {
scenario: string
variant: string
metric: string
unit: string
samples: number[]
}
// Groups SnapshotRows into per-(scenario, variant, metric) sample arrays.
// Skips rows whose value is non-finite (e.g. failed CSV parse).
export function groupRows(rows: SnapshotRow[]): Map<string, SampleGroup> {
const out = new Map<string, SampleGroup>()
for (const r of rows) {
if (!Number.isFinite(r.value)) continue
const key = makeKey(r.scenario, r.variant, r.metric)
let group = out.get(key)
if (!group) {
group = {
scenario: r.scenario,
variant: r.variant,
metric: r.metric,
unit: r.unit,
samples: [],
}
out.set(key, group)
}
group.samples.push(r.value)
}
return out
}
export function makeKey(
scenario: string,
variant: string,
metric: string
): string {
return `${scenario}\x00${variant}\x00${metric}`
}
// Prints the comparison table comparing baseline (A) to current (B).
// Reports series only in one side and unit mismatches separately.
export function printComparison(
baseline: Map<string, SampleGroup>,
current: Map<string, SampleGroup>,
options: { baselineLabel: string; currentLabel?: string } = {
baselineLabel: 'baseline',
}
): void {
const { baselineLabel, currentLabel } = options
console.log()
if (currentLabel) {
console.log(
bold(underline(`Comparison: ${baselineLabel} → ${currentLabel}`))
)
} else {
console.log(bold(underline(`Comparison vs baseline: ${baselineLabel}`)))
}
const rows: FormattedRow[] = []
const onlyInCurrent: string[] = []
const onlyInBaseline: string[] = []
const skippedMismatch: string[] = []
for (const [key, cur] of current) {
const base = baseline.get(key)
if (!base) {
onlyInCurrent.push(`${cur.scenario} · ${cur.variant} · ${cur.metric}`)
continue
}
if (base.unit !== cur.unit) {
skippedMismatch.push(
`${cur.scenario} · ${cur.variant} · ${cur.metric} (baseline=${base.unit}, current=${cur.unit})`
)
continue
}
rows.push(formatRow(base, cur))
}
for (const [key, base] of baseline) {
if (!current.has(key)) {
onlyInBaseline.push(`${base.scenario} · ${base.variant} · ${base.metric}`)
}
}
if (rows.length > 0) {
const header = [
'Scenario · Variant',
'Metric',
'Baseline μ / p50 / p90 (n)',
'Current μ / p50 / p90 (n)',
'Δ mean',
'Δ%',
"Welch's p",
'MWU p',
]
printTable(header, rows)
} else {
console.log(
dim(
'No matching (scenario, variant, metric) tuples between current and baseline.'
)
)
}
logList('Only in current', onlyInCurrent)
logList('Only in baseline', onlyInBaseline)
logList('Skipped due to unit mismatch', skippedMismatch, Infinity)
}
function logList(label: string, items: string[], max: number = 5): void {
if (items.length === 0) return
const shown = items.slice(0, max).join(', ')
const suffix = items.length > max ? '…' : ''
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)
const mwu = mannWhitneyU(base.samples, cur.samples)
// Color verdict uses Welch's p as the primary signal.
let verdict: RowVerdict
if (
Number.isFinite(welchs.p) &&
welchs.p < SIGNIFICANCE_THRESHOLD &&
delta !== 0
) {
verdict = delta < 0 ? 'improved' : 'regressed'
}
return {
cells: [
`${base.scenario} · ${base.variant}`,
base.metric,
formatGroupCell(base, bs),
formatGroupCell(cur, cs),
formatDelta(delta, base.unit),
Number.isFinite(deltaPct) ? `${deltaPct.toFixed(1)}%` : 'n/a',
formatP(welchs.p),
formatP(mwu.p),
],
verdict,
}
}
function formatGroupCell(
group: SampleGroup,
s: { mean: number; p50: number; p90: number }
): string {
const parts = [s.mean, s.p50, s.p90].map((v) =>
splitFormattedUnit(v, group.unit)
)
const n = 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[0].suffix} / ${parts[1].num}${parts[1].suffix} / ${parts[2].num}${parts[2].suffix} (${n})`
}
function splitFormattedUnit(
value: number,
unit: string
): { num: string; suffix: string } {
const formatted = formatUnit(value, unit)
const m = /^(-?\d+(?:\.\d+)?)(.*)$/.exec(formatted)
if (!m) return { num: formatted, suffix: '' }
return { num: m[1], suffix: m[2] }
}
function formatDelta(d: number, unit: string): string {
if (!Number.isFinite(d)) return 'n/a'
const sign = d > 0 ? '+' : ''
return `${sign}${formatUnit(d, unit)}`
}
function formatP(p: number): string {
if (!Number.isFinite(p)) return String(p)
if (p === 0) return '0'
if (p < 1e-3) return p.toExponential(2)
return p.toFixed(3)
}
function printTable(header: string[], rows: FormattedRow[]) {
const widths = header.map((h) => h.length)
for (const r of rows) {
for (let i = 0; i < r.cells.length; i++) {
if (r.cells[i].length > widths[i]) widths[i] = r.cells[i].length
}
}
const pad = (s: string, w: number) => s + ' '.repeat(w - s.length)
const line = (cells: string[], paint: (s: string) => string = (s) => s) =>
'| ' + cells.map((c, i) => paint(pad(c, widths[i]))).join(' | ') + ' |'
const sep = '|' + widths.map((w) => '-'.repeat(w + 2)).join('|') + '|'
console.log(line(header))
console.log(sep)
for (const r of rows) {
const paint =
r.verdict === 'improved'
? green
: r.verdict === 'regressed'
? red
: undefined
console.log(line(r.cells, paint))
}
}
......@@ -35,6 +35,15 @@ export interface CurrentScenario {
export type Interface = Partial<FullInterface>
export interface VariantStatistic {
samples: number[]
unit: string
relativeTo?: string
mean: number
p50: number
p90: number
}
export interface FullInterface {
filterScenarios(scenarios: Scenario[]): Promise<Scenario[]>
filterScenarioVariants(
......@@ -43,7 +52,8 @@ export interface FullInterface {
start(
scenario: string,
props: Record<string, string | number | boolean | null>
props: Record<string, string | number | boolean | null>,
runInfo?: { run: number; total: number; warmup: boolean }
): Promise<void>
measurement(
scenario: string,
......@@ -63,6 +73,13 @@ export interface FullInterface {
error: unknown
): Promise<void>
// Called once per variant after all n runs complete, with per-metric stats.
variantStatistics(
scenario: string,
props: Record<string, string | number | boolean | null>,
stats: Record<string, VariantStatistic>
): Promise<void>
finish(): Promise<void>
}
......@@ -76,6 +93,7 @@ export function intoFullInterface(iface: Interface): FullInterface {
measurement: iface.measurement ?? (async () => {}),
end: iface.end ?? (async () => {}),
error: iface.error ?? (async () => {}),
variantStatistics: iface.variantStatistics ?? (async () => {}),
finish: iface.finish ?? (async () => {}),
}
}
......
import { Interface } from '../index.js'
import { SampleGroup, groupRows, makeKey, printComparison } from '../compare.js'
import { readSnapshot } from '../snapshot.js'
import { formatVariantProps } from '../utils.js'
export default async function createInterface(options: {
baselinePath: string
}): Promise<Interface> {
const baselinePath = options.baselinePath
const baselineRows = await readSnapshot(baselinePath)
const baseline = groupRows(baselineRows)
const current = new Map<string, SampleGroup>()
return {
variantStatistics: async (scenario, props, stats) => {
const variant = formatVariantProps(props)
for (const [metric, s] of Object.entries(stats)) {
const key = makeKey(scenario, variant, metric)
current.set(key, {
scenario,
variant,
metric,
unit: s.unit,
samples: s.samples.slice(),
})
}
},
finish: async () => {
printComparison(baseline, current, { baselineLabel: baselinePath })
},
}
}
......@@ -3,14 +3,23 @@ import { Interface } from '../index.js'
import { formatUnit } from '../units.js'
import { formatVariant } from '../utils.js'
const { bgCyan, bold, magenta, red, underline } = picocolors
const { bgCyan, bold, cyan, dim, magenta, red, underline } = picocolors
export default function createInterface(): Interface {
export default function createInterface(
options: { n?: number } = {}
): Interface {
const n = options.n ?? 1
const showSummary = n > 1
const iface: Interface = {
start: async (scenario, props) => {
console.log(
bold(underline(`Running ${formatVariant(scenario, props)}...`))
)
start: async (scenario, props, runInfo) => {
const label = formatVariant(scenario, props)
let progress = ''
if (runInfo) {
progress = runInfo.warmup
? ` [warmup ${runInfo.run}/${runInfo.total}]`
: ` [${runInfo.run}/${runInfo.total}]`
}
console.log(bold(underline(`Running ${label}...${progress}`)))
},
measurement: async (scenario, props, name, value, unit, relativeTo) => {
console.log(
......@@ -26,6 +35,20 @@ export default function createInterface(): Interface {
)
)
},
variantStatistics: async (scenario, props, stats) => {
if (!showSummary) return
const header = `${formatVariant(scenario, props)} (n=${n})`
console.log(bold(cyan(header)))
for (const [name, s] of Object.entries(stats)) {
const meanText = formatUnit(s.mean, s.unit)
const p50Text = formatUnit(s.p50, s.unit)
const p90Text = formatUnit(s.p90, s.unit)
const relText = s.relativeTo ? dim(` (from ${s.relativeTo})`) : ''
console.log(
` ${name}: mean=${meanText} p50=${p50Text} p90=${p90Text}${relText}`
)
}
},
error: async (scenario, props, error) => {
console.log(
bold(
......
import { Interface } from '../index.js'
import { quantile, mean as statsMean } from '../statistics.js'
import { formatUnit } from '../units.js'
import { writeFile } from 'fs/promises'
......@@ -21,15 +22,17 @@ export default function createInterface(
throw new Error('env var JSON_OUTPUT_FILE is not set')
}
return file
})()
})(),
options: { n?: number } = {}
): Interface {
const n = options.n ?? 1
// Per-(scenario, props, name) sample accumulator.
const metrics = new Map<
string,
{
key: Record<string, string | number>
value: number
samples: number[]
unit: string
count: number
relativeTo?: string
}
>()
......@@ -43,36 +46,47 @@ export default function createInterface(
const key = JSON.stringify(keyObject)
const current = metrics.get(key)
if (current) {
current.value += value
current.count++
current.samples.push(value)
} else {
metrics.set(key, {
key: keyObject,
value,
unit: unit,
count: 1,
samples: [value],
unit,
relativeTo,
})
}
},
finish: async () => {
await writeFile(
file,
JSON.stringify(
[...metrics.values()].map(
({ key, value, unit, count, relativeTo }) => {
return {
key,
value: value / count,
unit,
text: formatUnit(value / count, unit),
datapoints: count,
relativeTo,
}
const results = [...metrics.values()].map(
({ key, samples, unit, relativeTo }) => {
if (samples.length === 1) {
// Preserve the original single-run shape exactly for back-compat.
return {
key,
value: samples[0],
unit,
text: formatUnit(samples[0], unit),
datapoints: 1,
relativeTo,
}
)
)
}
const m = statsMean(samples)
return {
key,
value: m,
unit,
text: formatUnit(m, unit),
datapoints: samples.length,
mean: m,
p50: quantile(samples, 0.5),
p90: quantile(samples, 0.9),
samples,
relativeTo,
}
}
)
const payload = n > 1 ? { results } : (results as unknown)
await writeFile(file, JSON.stringify(payload))
},
}
......
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import picocolors from 'picocolors'
import { Interface } from '../index.js'
import { SnapshotRow, defaultSnapshotPath, writeSnapshot } from '../snapshot.js'
import { formatVariantProps } from '../utils.js'
const execFileAsync = promisify(execFile)
async function readGitInfo(): Promise<{ sha: string; branch: string }> {
const sha = process.env.GITHUB_SHA || (await tryGit(['rev-parse', 'HEAD']))
const branch =
process.env.GITHUB_REF_NAME ||
(await tryGit(['rev-parse', '--abbrev-ref', 'HEAD']))
return { sha, branch }
}
async function tryGit(args: string[]): Promise<string> {
try {
const { stdout } = await execFileAsync('git', args)
return stdout.trim()
} catch {
return ''
}
}
export default function createInterface(
options: { path?: string } = {}
): Interface & { resolvedPath: string } {
const path = options.path ?? defaultSnapshotPath()
const rows: SnapshotRow[] = []
const timestamp = new Date().toISOString()
const iface: Interface & { resolvedPath: string } = {
resolvedPath: path,
variantStatistics: async (scenario, props, stats) => {
const variant = formatVariantProps(props)
for (const [metric, s] of Object.entries(stats)) {
for (let i = 0; i < s.samples.length; i++) {
rows.push({
timestamp,
scenario,
variant,
metric,
sample_idx: i + 1,
value: s.samples[i],
unit: s.unit,
relative_to: s.relativeTo ?? '',
git_sha: '',
git_branch: '',
})
}
}
},
finish: async () => {
if (rows.length === 0) return
const { sha, branch } = await readGitInfo()
for (const r of rows) {
r.git_sha = sha
r.git_branch = branch
}
await writeSnapshot(path, rows)
console.log(picocolors.dim(`Wrote ${rows.length} rows to ${path}`))
},
}
return iface
}
// Minimal ambient declarations for `jstat` (no TypeScript types shipped).
// Only the distribution CDFs used by src/statistics.ts are declared.
declare module 'jstat' {
const jstat: {
studentt: { cdf(x: number, dof: number): number }
normal: { cdf(x: number, mean: number, sd: number): number }
}
export default jstat
}
import { withCurrent } from './describe.js'
import { Interface, Scenario, intoFullInterface } from './index.js'
import {
FullInterface,
Interface,
Scenario,
VariantStatistic,
intoFullInterface,
} from './index.js'
import { summary } from './statistics.js'
interface SampleSet {
samples: number[]
unit: string
relativeTo?: string
}
export async function runScenarios(
scenarios: Scenario[],
iface: Interface
iface: Interface,
options: { n?: number; warmup?: number } = {}
): Promise<void> {
const n = Math.max(1, Math.floor(options.n ?? 1))
const warmup = Math.max(0, Math.floor(options.warmup ?? 0))
const fullIface = intoFullInterface(iface)
if (scenarios.some((scenario) => scenario.only)) {
scenarios = scenarios.filter((scenario) => scenario.only)
......@@ -37,27 +53,96 @@ export async function runScenarios(
variants = await fullIface.filterScenarioVariants(variants)
for (const variant of variants) {
try {
const measurements = new Map()
await withCurrent(
{
iface: fullIface,
measurements,
scenario: variant,
},
async () => {
await fullIface.start(variant.scenario.name, variant.props)
measurements.set('start', {
value: Date.now(),
unit: 'ms',
})
await variant.scenario.fn(variant.props)
await fullIface.end(variant.scenario.name, variant.props)
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.
let collecting = false
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,
})
}
}
await fullIface.measurement(
scenario,
props,
name,
value,
unit,
relativeTo
)
},
}
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
try {
const measurements = new Map()
await withCurrent(
{
iface: wrappedIface,
measurements,
scenario: variant,
},
async () => {
await wrappedIface.start(
variant.scenario.name,
variant.props,
runInfo
)
measurements.set('start', {
value: Date.now(),
unit: 'ms',
})
await variant.scenario.fn(variant.props)
await wrappedIface.end(variant.scenario.name, variant.props)
}
)
} catch (e) {
await wrappedIface.error(variant.scenario.name, variant.props, e)
process.exitCode = 1
aborted = true
break
}
}
if (!aborted && samplesByMetric.size > 0) {
const stats: Record<string, VariantStatistic> = {}
for (const [name, set] of samplesByMetric) {
stats[name] = {
samples: set.samples,
unit: set.unit,
relativeTo: set.relativeTo,
...summary(set.samples),
}
}
await fullIface.variantStatistics(
variant.scenario.name,
variant.props,
stats
)
} catch (e) {
await fullIface.error(variant.scenario.name, variant.props, e)
process.exitCode = 1
}
}
......
import { readFile, readdir, mkdir, writeFile, stat } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
export const DEFAULT_SNAPSHOT_DIR = '.devlow-bench/snapshots'
// One row per (scenario, variant, metric, sample). Long-format so the same
// file can store mixed-unit metrics (ms, MB, requests, ...) without sparse
// columns. Consumers can filter by `unit` and pivot downstream.
export interface SnapshotRow {
timestamp: string
scenario: string
variant: string
metric: string
sample_idx: number
value: number
unit: string
relative_to: string
git_sha: string
git_branch: string
}
const COLUMNS: (keyof SnapshotRow)[] = [
'timestamp',
'scenario',
'variant',
'metric',
'sample_idx',
'value',
'unit',
'relative_to',
'git_sha',
'git_branch',
]
export function defaultSnapshotPath(
dir: string = DEFAULT_SNAPSHOT_DIR,
now: Date = new Date()
): string {
// ISO-ish, filesystem-safe, lexicographic-sortable.
const stamp = now.toISOString().replace(/[:.]/g, '-').replace(/Z$/, 'Z')
return resolve(join(dir, `${stamp}.csv`))
}
export async function writeSnapshot(
path: string,
rows: SnapshotRow[]
): Promise<void> {
await mkdir(dirname(path), { recursive: true })
const lines: string[] = [COLUMNS.join(',')]
for (const row of rows) {
lines.push(COLUMNS.map((c) => csvCell(row[c])).join(','))
}
await writeFile(path, lines.join('\n') + '\n')
}
export async function readSnapshot(path: string): Promise<SnapshotRow[]> {
const text = await readFile(path, 'utf-8')
const lines = text.split(/\r?\n/).filter((l) => l.length > 0)
if (lines.length === 0) return []
const header = parseCsvLine(lines[0])
const idx: Partial<Record<keyof SnapshotRow, number>> = {}
for (let i = 0; i < header.length; i++) {
if ((COLUMNS as string[]).includes(header[i])) {
idx[header[i] as keyof SnapshotRow] = i
}
}
const rows: SnapshotRow[] = []
for (let i = 1; i < lines.length; i++) {
const cells = parseCsvLine(lines[i])
const get = (k: keyof SnapshotRow): string => {
const j = idx[k]
return j == null ? '' : (cells[j] ?? '')
}
rows.push({
timestamp: get('timestamp'),
scenario: get('scenario'),
variant: get('variant'),
metric: get('metric'),
sample_idx: Number(get('sample_idx')),
value: Number(get('value')),
unit: get('unit'),
relative_to: get('relative_to'),
git_sha: get('git_sha'),
git_branch: get('git_branch'),
})
}
return rows
}
// Returns the newest .csv in the directory, excluding the optional exclude
// path. Returns null if the directory doesn't exist or has no matching files.
export async function findMostRecentSnapshot(
dir: string = DEFAULT_SNAPSHOT_DIR,
excludePath?: string
): Promise<string | null> {
let entries: string[]
try {
entries = await readdir(dir)
} catch (e: any) {
if (e.code === 'ENOENT') return null
throw e
}
const candidates = entries.filter((f) => f.endsWith('.csv'))
const excludeResolved = excludePath ? resolve(excludePath) : null
let best: { path: string; mtime: number } | null = null
for (const f of candidates) {
const full = resolve(join(dir, f))
if (excludeResolved && full === excludeResolved) continue
const s = await stat(full)
if (!best || s.mtimeMs > best.mtime) {
best = { path: full, mtime: s.mtimeMs }
}
}
return best?.path ?? null
}
// Resolve --compare: if given a directory, pick the newest .csv inside;
// if given a file, use it; if null/undefined, fall back to DEFAULT_SNAPSHOT_DIR.
export async function resolveCompareTarget(
target: string | true | undefined,
excludePath?: string
): Promise<string | null> {
if (target == null) return null
let candidatePath: string | null = null
if (target === true) {
candidatePath = await findMostRecentSnapshot(
DEFAULT_SNAPSHOT_DIR,
excludePath
)
} else {
let isDir = false
try {
isDir = (await stat(target)).isDirectory()
} catch {
// Path doesn't exist; let caller error out.
}
if (isDir) {
candidatePath = await findMostRecentSnapshot(target, excludePath)
} else {
candidatePath = resolve(target)
}
}
return candidatePath
}
function csvCell(v: string | number): string {
const s = String(v)
if (/[,"\n\r]/.test(s)) {
return `"${s.replace(/"/g, '""')}"`
}
return s
}
function parseCsvLine(line: string): string[] {
const cells: string[] = []
let i = 0
while (i < line.length) {
if (line[i] === '"') {
let s = ''
i++ // skip opening quote
while (i < line.length) {
if (line[i] === '"') {
if (line[i + 1] === '"') {
s += '"'
i += 2
} else {
i++ // closing quote
break
}
} else {
s += line[i]
i++
}
}
cells.push(s)
if (line[i] === ',') i++
} else {
const next = line.indexOf(',', i)
if (next === -1) {
cells.push(line.slice(i))
i = line.length
} else {
cells.push(line.slice(i, next))
i = next + 1
}
}
}
return cells
}
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { mean, quantile, welchsTTest, mannWhitneyU } from './statistics.js'
function near(actual: number, expected: number, tol = 1e-6, label = '') {
assert.ok(
Math.abs(actual - expected) < tol,
`${label}: expected ${expected}, got ${actual} (tol ${tol})`
)
}
test('mean', () => {
near(mean([1, 2, 3, 4, 5]), 3)
near(mean([10]), 10)
})
test('quantile (linear interpolation, numpy/R type 7)', () => {
// [1,2,3,4,5] with q=0.5 → 3, q=0.9 → 4.6
near(quantile([1, 2, 3, 4, 5], 0.5), 3)
near(quantile([1, 2, 3, 4, 5], 0.9), 4.6)
// sorts internally
near(quantile([5, 3, 1, 2, 4], 0.5), 3)
// single sample
near(quantile([42], 0.9), 42)
})
test("Welch's t-test: small samples", () => {
// Hand-verified: means 2 and 3, both sample variances = 1.
// sea = seb = 1/3, denom = 2/3
// t = -1 / sqrt(2/3) = -1.2247448713915892
// df = (2/3)^2 / (2 * (1/3)^2 / 2) = (4/9) / (1/9) = 4
// p ≈ 0.288 (two-sided, df=4)
const r = welchsTTest([1, 2, 3], [2, 3, 4])
near(r.t, -1.2247448713915892, 1e-12, 't')
near(r.df, 4, 1e-12, 'df')
near(r.p, 0.288, 1e-3, 'p')
})
test("Welch's t-test: large clearly-different samples", () => {
// mean_a=12, mean_b=22, var_a=var_b=2.5 → t=-10 exactly, df=8 exactly.
const a = [10, 11, 12, 13, 14]
const b = [20, 21, 22, 23, 24]
const r = welchsTTest(a, b)
near(r.t, -10, 1e-12, 't')
near(r.df, 8, 1e-12, 'df')
// P(|T|>10 | df=8) is on the order of 8e-6.
assert.ok(r.p > 1e-6 && r.p < 1e-5, `expected p in (1e-6, 1e-5), got ${r.p}`)
})
test("Welch's t-test: identical samples → t=0, p=1", () => {
const r = welchsTTest([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
near(r.t, 0)
near(r.p, 1)
})
test('Welch handles unequal variance (small group variance)', () => {
// [1..5] vs [10, 10.1, 10.2, 10.3, 10.4]
// var_a = 2.5, var_b = 0.025 → very unequal.
// sea = 0.5, seb = 0.005, denom = 0.505
// t = -7.2 / sqrt(0.505) ≈ -10.1318
// df = 0.505^2 / (0.0625 + 6.25e-6) ≈ 4.080
const r = welchsTTest([1, 2, 3, 4, 5], [10, 10.1, 10.2, 10.3, 10.4])
near(r.t, -10.131804644116203, 1e-9, 't')
near(r.df, 4.08, 1e-2, 'df')
// df is small (~4) so heavier tails than the df=8 case: p should be larger.
assert.ok(r.p < 1e-3, `expected p<1e-3, got ${r.p}`)
})
test('t-distribution CDF: known critical value', () => {
// df=10, |t|=2.228 → two-sided p ≈ 0.05 (standard table).
// We verify by constructing a sample with exactly that t-stat.
// Easier: use the fact that for df=∞ (large df), Welch's reduces to z-test.
// df=1000, t≈1.96 should give p≈0.05.
// Construct a=[0]*n, b shifted: we can't get exact df without specific values,
// so we just confirm the formula gives sane values across df range.
// Pair 1: df ≈ 10, t ≈ 2.228 — synthesize with two known groups.
// Simpler check: at very large df, p should match the normal-tail p for the same z.
const huge = Array.from({ length: 500 }, (_, i) => i)
const huger = Array.from({ length: 500 }, (_, i) => i + 0.2) // tiny shift
const r = welchsTTest(huge, huger)
// With this setup df is enormous (~1000) and t is small but well-defined.
// p should be between 0 and 1; finite.
assert.ok(Number.isFinite(r.p))
assert.ok(r.p >= 0 && r.p <= 1)
})
test('Mann–Whitney U: n=5 vs n=5, max separation', () => {
// [1..5] vs [6..10]: U=0. Exact two-sided p = 2/252 ≈ 0.00794;
// asymptotic with continuity correction ≈ 0.012. Both indicate a strong
// separation; we just verify U=0 and p is below 0.05.
const r = mannWhitneyU([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
assert.equal(r.u, 0)
assert.ok(r.p < 0.05, `expected p<0.05, got ${r.p}`)
assert.ok(r.p > 0.005, `expected p>0.005, got ${r.p}`)
})
test('Mann–Whitney U: fully overlapping → no rejection', () => {
const r = mannWhitneyU([1, 2, 3], [1, 2, 3])
assert.ok(r.p > 0.5, `expected p>0.5, got ${r.p}`)
})
test('Mann–Whitney U: 3 vs 3 distinct, no ties', () => {
// U=0 for group A. Exact two-sided p = 0.1; asymptotic ≈ 0.081.
const r = mannWhitneyU([1, 2, 3], [4, 5, 6])
assert.equal(r.u, 0)
assert.ok(r.p > 0.05 && r.p < 0.15, `expected p in (0.05, 0.15), got ${r.p}`)
})
test('Mann–Whitney U: medium samples use normal approximation', () => {
// Two clearly separated groups of 12.
// scipy two-sided p with continuity correction is in the ~1e-5 range.
const a = Array.from({ length: 12 }, (_, i) => i + 1)
const b = Array.from({ length: 12 }, (_, i) => i + 100)
const r = mannWhitneyU(a, b)
assert.equal(r.u, 0)
assert.ok(r.p < 1e-4, `expected p<1e-4, got ${r.p}`)
})
// Statistics helpers for repeated-sampling benchmarks.
//
// We use `jstat` for the underlying distribution CDFs (Student's t and
// standard normal). The rest — Welch's t-statistic, average-rank ranking,
// and the Mann–Whitney U statistic + asymptotic-tail p-value — is
// implemented here directly.
//
// For Mann–Whitney we use the normal approximation with continuity
// correction. For very small samples this approximation is less accurate
// (n=5 vs n=5 has a minimum exact two-sided p ≈ 0.008 vs the
// approximation's ≈ 0.012). Document this at the call site, not here.
import jstat from 'jstat'
export interface Summary {
mean: number
p50: number
p90: number
}
export function mean(xs: number[]): number {
if (xs.length === 0) return NaN
let s = 0
for (const x of xs) s += x
return s / xs.length
}
// Linear-interpolation quantile (numpy/R "type 7" default).
export function quantile(xs: number[], q: number): number {
if (xs.length === 0) return NaN
if (xs.length === 1) return xs[0]
const sorted = [...xs].sort((a, b) => a - b)
const pos = q * (sorted.length - 1)
const lo = Math.floor(pos)
const hi = Math.ceil(pos)
if (lo === hi) return sorted[lo]
return sorted[lo] + (pos - lo) * (sorted[hi] - sorted[lo])
}
export function summary(samples: number[]): Summary {
return {
mean: mean(samples),
p50: quantile(samples, 0.5),
p90: quantile(samples, 0.9),
}
}
export interface WelchsTResult {
t: number
df: number
p: number
}
// Two-sample Welch's t-test (unequal variances, two-sided).
export function welchsTTest(a: number[], b: number[]): WelchsTResult {
if (a.length < 2 || b.length < 2) return { t: NaN, df: NaN, p: NaN }
if (allEqual(a) && allEqual(b)) {
const ma = a[0]
const mb = b[0]
return {
t: ma === mb ? 0 : ma > mb ? Infinity : -Infinity,
df: NaN,
p: ma === mb ? 1 : 0,
}
}
const ma = mean(a)
const mb = mean(b)
const va = sampleVariance(a, ma)
const vb = sampleVariance(b, mb)
const na = a.length
const nb = b.length
const sea = va / na
const seb = vb / nb
const t = (ma - mb) / Math.sqrt(sea + seb)
// Welch–Satterthwaite degrees of freedom.
const df =
(sea + seb) ** 2 / ((sea * sea) / (na - 1) + (seb * seb) / (nb - 1))
const p = 2 * (1 - jstat.studentt.cdf(Math.abs(t), df))
return { t, df, p }
}
export interface MannWhitneyResult {
u: number
p: number
}
// Two-sided Mann–Whitney U test, asymptotic with continuity correction.
export function mannWhitneyU(a: number[], b: number[]): MannWhitneyResult {
const na = a.length
const nb = b.length
if (na === 0 || nb === 0) return { u: NaN, p: NaN }
const combined = [...a, ...b]
const r = averageRanks(combined)
let rankSumA = 0
for (let i = 0; i < na; i++) rankSumA += r[i]
const uA = rankSumA - (na * (na + 1)) / 2
const uB = na * nb - uA
const u = Math.min(uA, uB)
const meanU = (na * nb) / 2
const sd = Math.sqrt((na * nb * (na + nb + 1)) / 12)
if (sd === 0) return { u, p: 1 }
const z = Math.max(0, (Math.abs(uA - meanU) - 0.5) / sd)
const p = 2 * (1 - jstat.normal.cdf(z, 0, 1))
return { u, p: Math.min(1, Math.max(0, p)) }
}
// Average-rank ranking (R/scipy default tie correction): tied values share
// the mean of the ranks they would have received.
function averageRanks(xs: number[]): number[] {
const n = xs.length
const idx: [number, number][] = xs.map((v, i) => [v, i])
idx.sort((p, q) => p[0] - q[0])
const r = new Array<number>(n)
let i = 0
while (i < n) {
let j = i
while (j + 1 < n && idx[j + 1][0] === idx[i][0]) j++
const avg = (i + j) / 2 + 1
for (let k = i; k <= j; k++) r[idx[k][1]] = avg
i = j + 1
}
return r
}
function sampleVariance(xs: number[], m: number): number {
let s = 0
for (const x of xs) {
const d = x - m
s += d * d
}
return s / (xs.length - 1)
}
function allEqual(xs: number[]): boolean {
for (let i = 1; i < xs.length; i++) if (xs[i] !== xs[0]) return false
return true
}
......@@ -2,11 +2,16 @@ export function formatVariant(
scenario: string,
props: Record<string, string | number | boolean | null>
): string {
const keys = Object.keys(props)
const propsStr = formatVariantProps(props)
return propsStr ? `${scenario} ${propsStr}` : scenario
}
// Just the props part (no scenario prefix). Stable key for snapshots/compare.
export function formatVariantProps(
props: Record<string, string | number | boolean | null>
): string {
return Object.keys(props)
.filter((key) => props[key] !== false && props[key] !== null)
.map((key) => (props[key] === true ? key : `${key}=${props[key]}`))
if (keys.length === 0) {
return scenario
}
return `${scenario} ${keys.join(' ')}`
.join(' ')
}
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