Files
unkernel/test/work-bench.mjs

323 lines
19 KiB
JavaScript
Executable File

#!/usr/bin/env node
// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Workload timings of one or more bundles on the work disk (Perl, Python, a
// C build, shell and dpkg, Node, Bun and Claude Code; .agents/a64/
// performance.md, Measuring), built like test/app-bench.mjs: one boot per
// bundle and round (the order rotates per round), each row RUNS times in a
// row, timed in the guest by test/work-bench.sh; it prints per row the
// median first run and the median later run in ms, with the difference to
// the first bundle, and writes every sample to a JSON file.
//
// node test/work-bench.mjs [--rounds N] [--runs N] [--cpus N] [--stats] [--rows A,B]
// [--disk FILE] [--out FILE] [--raw] [--detail] [--list] [--from FILE.json] [NAME=]BUNDLE.wasm[,VAR=VALUE...] ...
//
// VAR=VALUE after a bundle sets test/work-bench.sh's variables for that
// variant (ASLR=2, PERL_N=2, ...), so one bundle can be listed twice. --rows
// takes row names or groups (perl, py, cc, sh, node; --list prints them).
// --cpus 2 boots the SMP kernel of each bundle. The disk (default the work
// disk, WORK_DISK in the environment or jit2-scratch/disks/debian-work.img;
// see test/work-bench-setup.sh) is opened as a snapshot, with no network,
// so runs share it and fetch nothing. --stats (a stats bundle, one CPU)
// also takes kwemu's counters around every run (vm.stats().kwemu) and
// prints them per row (--detail: also interpreted instructions by reason,
// exits, frees); --raw keeps every counter word in the JSON. --from FILE
// prints the tables of an earlier run's JSON file again.
// Each boot runs in a child process (this script with --child) that drives
// the kernel through the SDK. Wall-time runs on a shared host take the
// bench lock: flock jit2-scratch/bench.lock node test/work-bench.mjs ...
import { spawn, execFileSync } from "node:child_process";
import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
const root = path.resolve(import.meta.dirname, "..");
// Rows in boot order, with their group. The desktop group runs on its own
// disk (another boot) and only when --rows names it.
const ROWS = [
...[1, 2, 3, 4, 5, 6].map((k) => ["perl", `perl-k${k}`]),
["perl", "perl-start"],
["py", "py-start"], ["py", "py-compile"], ["py", "py-cpu"],
["cc", "cc-build"],
["sh", "sh-procs"], ["sh", "dpkg"],
["node", "claude-help"], ["node", "npm-version"], ["node", "bun-cpu"], ["node", "node-cpu"], ["node", "node-e0"],
["node", "claude-version"], ["node", "bun-build"],
["desktop", "ff-page"],
];
// Disks other than the work disk, with the memory their boots get.
const DISKS = {
desktop: { env: "FF_DISK", file: "../jit2-scratch/disks/debian-firefox-work.img", mem: 2048 },
};
async function main() {
const argv = process.argv.slice(2);
const opt = (f, d) => (argv.includes(f) ? argv.splice(argv.indexOf(f), 2)[1] : d);
const flag = (f) => argv.includes(f) && !!argv.splice(argv.indexOf(f), 1);
const rounds = Number(opt("--rounds", 3)), runs = Number(opt("--runs", 3)), cpus = Number(opt("--cpus", 1));
const stats = flag("--stats"), raw = flag("--raw"), detail = flag("--detail");
const from = opt("--from");
if (from) return report(JSON.parse(readFileSync(from, "utf8")), detail);
const disk = path.resolve(opt("--disk", process.env.WORK_DISK ?? path.join(root, "../jit2-scratch/disks/debian-work.img")));
const want = opt("--rows", "").split(",").filter(Boolean);
if (flag("--list")) {
for (const [g, r] of ROWS) console.log(`${g}\t${r}`);
return;
}
const rows = ROWS.filter(([g, r]) => (!want.length && !DISKS[g]) || want.includes(g) || want.includes(r)).map(([, r]) => r);
// One boot per disk: the work disk's rows, then each other disk's.
const groupOf = (row) => ROWS.find(([, r]) => r === row)[0];
const parts = [{ disk, mem: 1024, rows: rows.filter((r) => !DISKS[groupOf(r)]) }];
for (const [g, d] of Object.entries(DISKS)) {
parts.push({ disk: path.resolve(process.env[d.env] ?? path.join(root, d.file)), mem: d.mem, rows: rows.filter((r) => groupOf(r) === g) });
}
for (const w of want) if (!ROWS.some(([g, r]) => g === w || r === w)) throw new Error(`unknown row or group ${w} (--list)`);
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
const out = path.resolve(opt("--out", `work-bench-${stamp}.json`));
const bundles = (argv.length ? argv : ["vendor/build/bundle/unkernel.wasm"]).map((a) => {
const [spec, ...env] = a.split(",");
const i = spec.indexOf("=");
const file = path.resolve(i < 0 ? spec : spec.slice(i + 1));
if (env.some((e) => !/^[A-Z_]+=[\w.-]+$/.test(e))) throw new Error(`bad variable in ${a}`);
return { name: i < 0 ? [path.basename(file, ".wasm"), ...env].join(",") : spec.slice(0, i), file, env };
});
for (const f of [...parts.filter((p) => p.rows.length).map((p) => p.disk), ...bundles.map((b) => b.file)]) {
if (!existsSync(f)) {
console.error(`missing ${f}`);
process.exit(1);
}
}
// The generated inputs, made once on the host and mounted at /w.
const gen = mkdtempSync(path.join(tmpdir(), "work-bench-"));
for (const js of ["guest/work/gen-c.js", "guest/app/gen-ts.js"]) copyFileSync(path.join(root, "test", js), path.join(gen, path.basename(js, ".js") + ".cjs"));
execFileSync(process.execPath, [path.join(gen, "gen-c.cjs"), path.join(gen, "cproj"), process.env.C_UNITS ?? "3", process.env.C_FUNCS ?? "1"]);
execFileSync(process.execPath, [path.join(gen, "gen-ts.cjs"), path.join(gen, "big.ts")]);
const median = (a) => {
const s = [...a].sort((x, y) => x - y);
return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
};
const result = { date: new Date().toISOString(), host: process.env.HOSTNAME, cpus, rounds, runs, stats, disk, rows,
bundles: bundles.map((b) => ({ name: b.name, file: b.file, env: b.env })), boots: [] };
const save = () => writeFileSync(out, JSON.stringify(result, null, raw ? 0 : 1) + "\n");
for (let r = 0; r < rounds; r++) {
for (let k = 0; k < bundles.length; k++) {
const i = (k + r) % bundles.length, b = bundles[i];
for (const part of parts.filter((p) => p.rows.length)) {
const t0 = performance.now();
const res = await boot({ bundle: b.file, env: b.env, disk: part.disk, mem: part.mem, rows: part.rows, runs, cpus, stats, raw, gen, root });
result.boots.push({ bundle: i, round: r + 1, disk: part.disk, bootMs: res.bootMs, prep: res.prep, runs: res.runs });
save();
console.error(`round ${r + 1}/${rounds} ${b.name}${part.disk === disk ? "" : ` (${path.basename(part.disk)})`}: ${((performance.now() - t0) / 1000).toFixed(0)} s`);
}
}
}
rmSync(gen, { recursive: true, force: true });
report(result, detail);
console.log(`\nsamples: ${path.relative(process.cwd(), out)}`);
}
/** Prints the tables of a result (as written to the JSON file). */
function report(result, detail) {
const median = (a) => {
const s = [...a].sort((x, y) => x - y);
return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
};
// samples[bundle][row] = per boot: ms; "row first" is run 1, "row later" the median of the others.
const { bundles, rows, cpus, rounds, runs, stats } = result;
const samples = bundles.map(() => new Map());
const counters = bundles.map(() => new Map());
const tableRows = [];
for (const boot of result.boots) {
for (const row of rows) {
const of = boot.runs.filter((x) => x.row === row);
if (!of.length) continue;
const add = (name, ms, c) => {
if (!tableRows.includes(name)) tableRows.push(name);
const m = samples[boot.bundle];
m.set(name, [...(m.get(name) ?? []), ms]);
if (c) counters[boot.bundle].set(name, [...(counters[boot.bundle].get(name) ?? []), c]);
};
add(`${row} first`, of[0].ms, of[0].c);
if (of.length > 1) add(`${row} later`, median(of.slice(1).map((x) => x.ms)), of.at(-1).c);
}
}
console.log(`${result.date.slice(0, 10)}, ${cpus} CPU${cpus > 1 ? "s" : ""}, ${rounds} boots per bundle, ${runs} runs per row; guest ms, medians (min-max)`);
console.log(`| row | ${bundles.map((b) => b.name).join(" | ")} |`);
console.log(`| --- | ${bundles.map(() => "---:").join(" | ")} |`);
for (const row of tableRows) {
const base = median(samples[0].get(row) ?? [NaN]);
const cells = bundles.map((b, i) => {
const a = samples[i].get(row);
if (!a) return "-";
const m = median(a);
const d = i ? ` ${m >= base ? "+" : ""}${(((m - base) / base) * 100).toFixed(1)}%` : "";
return `${m.toFixed(0)} (${Math.min(...a)}-${Math.max(...a)})${d}`;
});
console.log(`| ${row} | ${cells.join(" | ")} |`);
}
if (stats) {
// Counters of the first run and of the last later run, medians over boots.
const keys = ["Minsns", "compiled%", "ent/1k", "decodes", "redec", "compiles", "modKiB", "compMs", "hb", "cntdown%", "frees"];
console.log(`\nCounters per run (medians over boots): Minsns, compiled share, entries into compiled code per 1000 instructions,` +
` decodes, re-decodes (dec_gone + dec_changed + dec_host), compiles, module KiB, compile ms, hand-backs,` +
` instructions counting down (share), modules freed`);
console.log(`| row | bundle | ${keys.join(" | ")} |`);
console.log(`| --- | --- | ${keys.map(() => "---:").join(" | ")} |`);
for (const row of tableRows) {
bundles.forEach((b, i) => {
const cs = counters[i].get(row);
if (!cs) return;
const m = (f) => median(cs.map(f));
const v = [m((c) => c.insns / 1e6).toFixed(1), m((c) => c.compiledPct).toFixed(1), m((c) => c.entPer1k).toFixed(1),
m((c) => c.decodes), m((c) => c.redecodes), m((c) => c.compiles), m((c) => c.jitBytes / 1024).toFixed(0),
m((c) => c.compileMs).toFixed(0), m((c) => c.handbacks), m((c) => (c.interp.countdown * 100) / Math.max(c.insns, 1)).toFixed(1),
m((c) => c.free.grow + c.free.exit_grow + c.free.clock + c.free.ring + c.free.other)];
console.log(`| ${row} | ${b.name} | ${v.join(" | ")} |`);
});
}
if (!detail) return;
// Where the instructions and the entries go: interpreted instructions by reason (share of all),
// exits from compiled code by kind (per entry), modules freed by reason, nursery resets.
const dk = ["never%", "cntdown%", "tail%", "hb-tail%", "hb", "exit side", "direct", "jalr", "stop", "hops/ent", "free grow", "exit_grow", "clock", "ring", "other", "resets", "revalid", "walks r/w/x"];
console.log(`\nDetail (medians over boots): interpreted instructions by reason (Ax: never compiled, counting down, tail after a` +
` static/dynamic stop, tail after a hand-back) as shares of all instructions; hand-backs; exits per kind; region hops per entry;` +
` modules freed by reason (jc.Why); nursery resets; revalidations; page walks`);
console.log(`| row | bundle | ${dk.join(" | ")} |`);
console.log(`| --- | --- | ${dk.map(() => "---:").join(" | ")} |`);
for (const row of tableRows) {
bundles.forEach((b, i) => {
const cs = counters[i].get(row);
if (!cs) return;
const m = (f) => median(cs.map(f));
const pc = (f) => m((c) => (f(c) * 100) / Math.max(c.insns, 1)).toFixed(1);
const v = [pc((c) => c.interp.never), pc((c) => c.interp.countdown), pc((c) => c.interp.tail_static + c.interp.tail_dyn),
pc((c) => c.interp.hb_static + c.interp.hb_dyn), m((c) => c.handbacks), m((c) => c.exits.side), m((c) => c.exits.direct),
m((c) => c.exits.jalr), m((c) => c.exits.stop), m((c) => c.region.hops / Math.max(c.entries, 1)).toFixed(2),
m((c) => c.free.grow), m((c) => c.free.exit_grow), m((c) => c.free.clock), m((c) => c.free.ring), m((c) => c.free.other),
m((c) => c.nurseryResets), m((c) => c.revalidated), `${m((c) => c.walks[0])}/${m((c) => c.walks[1])}/${m((c) => c.walks[2])}`];
console.log(`| ${row} | ${b.name} | ${v.join(" | ")} |`);
});
}
// The block cache: decodes by what the table way held, countdown lost, code-page marks.
const ck = ["dec evict", "dec gone", "lost drop M", "by compiled", "its lost M", "both compiled", "halved lost M",
"code stores", "hits", "mark evictions", "retired", "full sets/marked pages per reset", "compiled per reset"];
console.log(`\nBlock cache (medians over boots): decodes into a way that held another block / the same block's discarded ops;` +
` countdown progress lost to table replacement (M instructions), of it when the other way was compiled, both ways compiled,` +
` progress the survivor's halving took; stores that took the code-page path, of them hits on a marked chunk, marks evicted from a full set,` +
` exec-TLB entries retired by both; full mark sets, marked pages and compiled blocks per nursery reset`);
console.log(`| row | bundle | ${ck.join(" | ")} |`);
console.log(`| --- | --- | ${ck.map(() => "---:").join(" | ")} |`);
for (const row of tableRows) {
bundles.forEach((b, i) => {
const cs = counters[i].get(row)?.filter((c) => c.cache);
if (!cs?.length) return;
const m = (f) => median(cs.map(f));
const per = (f) => m((c) => f(c) / Math.max(c.nurseryResets, 1)).toFixed(0);
const v = [m((c) => c.dec.evict), m((c) => c.dec.gone), (m((c) => c.lost.drop) / 1e6).toFixed(1), m((c) => c.cache.vByCompiled),
(m((c) => c.cache.vByCompiledLost) / 1e6).toFixed(1), m((c) => c.cache.vBothCompiled), (m((c) => c.cache.vHalvedLost) / 1e6).toFixed(1),
m((c) => c.cache.csCalls), m((c) => c.cache.csHits), m((c) => c.cache.markEvictions), m((c) => c.cache.csRetired),
`${per((c) => c.cache.fullAtReset)}/${per((c) => c.cache.markedAtReset)}`, per((c) => c.cache.compiledAtReset)];
console.log(`| ${row} | ${b.name} | ${v.join(" | ")} |`);
});
}
}
}
/** One boot in a child process: { bootMs, prep, runs: [{ row, run, ms, hostMs, rc, c? }] }. */
function boot(cfg) {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [import.meta.filename, "--child", JSON.stringify(cfg)], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
let out = "", err = "";
child.stdout.on("data", (d) => (out += d));
child.stderr.on("data", (d) => (err += d));
child.on("error", reject);
child.on("close", (code) => {
const m = out.match(/^WB-RESULT (.*)$/m);
if (code || !m) return reject(new Error(`${path.basename(cfg.bundle)}: the boot did not finish (exit ${code}):\n${(out + err).slice(-3000)}`));
const res = JSON.parse(m[1]);
for (const r of res.runs) if (r.rc) console.error(`warning: ${r.row} run ${r.run} exited ${r.rc}: ${r.err ?? ""}`);
resolve(res);
});
});
}
// Layout of KwemuStats.words (src/emu/kwemu.zig Stats; js/cli.ts printKwemuStats).
const NK = 192, OH = 11, JI = OH + NK, HB = JI + 1, HG = HB + 1 + NK, JX = HG + 40, AR = OH + 150;
/** The counters of one window (b - a) that explain a row's time. */
function counters(a, b, ja, jb, raw) {
const d = b.words.map((x, i) => x - (a.words[i] ?? 0));
const w = (i) => d[i] ?? 0, jx = (i) => w(JX + i), ax = (i) => w(HG + i), ar = (i) => w(AR + i), gx = (i) => w(HB + 1 + 100 + i);
const insns = b.icount - a.icount;
const c = {
insns, jitInsns: w(JI), compiledPct: (w(JI) * 100) / Math.max(insns, 1), handbacks: w(HB),
interp: { never: ax(0), countdown: ax(1), tail_static: ax(2), tail_dyn: ax(3), hb_static: ax(4), hb_dyn: ax(5) },
lost: { drop: ax(6), reset: ax(7) },
decodes: w(2), redecodes: ar(6) + ar(7) + ar(8),
dec: { gone: ar(6), changed: ar(7), host: ar(8), evict: ar(9), empty: ar(10) },
resets: w(3), nurseryResets: ar(0), tenEvicted: ar(14), tenEvictedCompiled: ar(15),
lookupsSlow: w(0), revalidated: w(1), walks: [w(7), w(8), w(9)], generic: w(10),
core: { compiles: ax(10), skips: ax(11), fails: ax(12), shortened: ax(13), evictions: ax(14), frees: ax(15), grows: ax(16), members: ax(17) },
compiles: ax(10),
entries: jx(0), entPer1k: (jx(0) * 1000) / Math.max(insns, 1),
exits: { handback: jx(1), side: jx(2), side_region: jx(25), direct: jx(3), jalr: jx(4), stop: jx(24) },
region: { hops: jx(15), stale: jx(16), stop: jx(17), out: jx(18), cross: jx(23) },
free: { grow: jx(59), exit_grow: jx(60), clock: jx(61), ring: jx(62), other: jx(63) },
jitCompiled: jb.compiled - ja.compiled, jitBytes: jb.bytes - ja.bytes, compileMs: jb.compileMs - ja.compileMs,
// Block-cache counters (kwemu.zig Gx, in JitStats.hb from 100) and arena snapshots at nursery resets (Ar).
cache: {
csCalls: gx(0), csHits: gx(1), markEvictions: gx(2), csRetired: gx(3), fullAtReset: gx(4), markedAtReset: gx(5),
vByCompiled: gx(6), vByCompiledLost: gx(7), vBothCompiled: gx(8), vHalved: gx(9), vHalvedLost: gx(10),
retireAll: gx(11), icInval: gx(12), cross15: gx(13), cross16: gx(14), cdHist: Array.from({ length: 20 }, (_, i) => gx(15 + i)), liveAtReset: ar(1), tenAtReset: ar(3), compiledAtReset: ar(13),
},
};
if (raw) c.words = d;
return c;
}
async function child(cfg) {
const { createKernel, openDisk, nodeFs } = await import(path.join(cfg.root, "js/node.ts"));
const { smpKernelFromBundle } = await import(path.join(cfg.root, "js/core/kpatch.ts"));
const t0 = performance.now();
let bytes = readFileSync(cfg.bundle);
if (cfg.cpus > 1) bytes = (await smpKernelFromBundle(bytes)) ?? bytes;
const kernel = await WebAssembly.compile(bytes);
const worker = cfg.cpus > 1;
const vm = await createKernel({
kernel, memoryMiB: cfg.mem ?? 1024, cpus: cfg.cpus, worker, jit: true, vsock: true, log: () => {},
distro: path.join(cfg.root, "vendor/build/distro/debian.erofs"),
disks: [worker ? { kind: "file", path: cfg.disk, snapshot: true } : await openDisk(cfg.disk, { snapshot: true })],
mounts: { "/t": { fs: nodeFs(path.join(cfg.root, "test")), readOnly: true }, "/w": { fs: nodeFs(cfg.gen), readOnly: true } },
});
const env = cfg.env.join(" ");
const sh = async (args, timeout = 900000) => vm.exec("sh", ["-c", `${env} sh /t/work-bench.sh ${args}`], { timeout });
const prep = await sh("prep");
const bootMs = performance.now() - t0;
if (!/PREP-DONE/.test(prep.stdout)) throw new Error(`prep failed: ${prep.stdout}${prep.stderr}`);
const snap = () => (cfg.stats ? { k: vm.stats().kwemu, j: { ...vm.stats().jit } } : undefined);
const runs = [];
for (const row of cfg.rows) {
for (let run = 1; run <= cfg.runs; run++) {
const a = snap(), h0 = performance.now();
const r = await sh(`run ${row}`);
const hostMs = performance.now() - h0, b = snap();
const m = r.stdout.match(/^RES (\S+) (\d+) rc=(\d+)/m);
if (!m) throw new Error(`${row}: no result: ${r.stdout}${r.stderr}`);
const x = { row, run, ms: +m[2], hostMs: Math.round(hostMs), rc: +m[3] };
if (x.rc) x.err = r.stderr.trim().slice(-300);
const info = r.stdout.match(/^INFO (.*)$/m);
if (info) x.info = info[1];
if (a?.k && b?.k) x.c = counters(a.k, b.k, a.j, b.j, cfg.raw);
runs.push(x);
}
}
await vm.stop();
process.stdout.write(`WB-RESULT ${JSON.stringify({ bootMs: Math.round(bootMs), prep: prep.stdout.trim(), runs })}\n`);
process.exit(0);
}
if (process.argv[2] === "--child") await child(JSON.parse(process.argv[3]));
else await main();