From f3f3ffea98167e21e23bd5c4f6b7750dac055642 Mon Sep 17 00:00:00 2001 From: Tim Smart Date: Fri, 27 Nov 2026 20:30:10 +0000 Subject: [PATCH 1/2] Add hostperf, a cross-runtime benchmark suite for Node.js, Bun, Chromium and WebKit --- package.json | 1 + packages/effect/benchmark/hostperf/README.md | 121 +++++++ packages/effect/benchmark/hostperf/cases.ts | 233 +++++++++++++ packages/effect/benchmark/hostperf/entry.ts | 25 ++ packages/effect/benchmark/hostperf/harness.ts | 97 ++++++ packages/effect/benchmark/hostperf/run.ts | 311 ++++++++++++++++++ packages/effect/benchmark/hostperf/stats.ts | 58 ++++ 7 files changed, 846 insertions(+) create mode 100644 packages/effect/benchmark/hostperf/README.md create mode 100644 packages/effect/benchmark/hostperf/cases.ts create mode 100644 packages/effect/benchmark/hostperf/entry.ts create mode 100644 packages/effect/benchmark/hostperf/harness.ts create mode 100644 packages/effect/benchmark/hostperf/run.ts create mode 100644 packages/effect/benchmark/hostperf/stats.ts diff --git a/package.json b/package.json index a7ede8cd76e..ccfdf672a0f 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "typeperf-compare": "pnpm --dir packages/effect exec node typeperf/compare.mjs", "runtimeperf": "pnpm --dir packages/effect exec node runtimeperf/run.mts", "runtimeperf-compare": "pnpm --dir packages/effect exec node runtimeperf/compare.mts", + "hostperf": "node packages/effect/benchmark/hostperf/run.ts", "check-recursive": "pnpm --recursive --filter \"./packages/**/*\" exec tsc -b tsconfig.json", "check-dist-types": "node scripts/check-dist-types.mjs", "jsdocs": "effect-jsdocs", diff --git a/packages/effect/benchmark/hostperf/README.md b/packages/effect/benchmark/hostperf/README.md new file mode 100644 index 00000000000..7d6a17258dd --- /dev/null +++ b/packages/effect/benchmark/hostperf/README.md @@ -0,0 +1,121 @@ +# hostperf + +Runs a small set of Effect runtime benchmarks in Node.js, Bun, Chromium and +WebKit, writes a JSON report and optionally compares it with an earlier report. +A full run takes under a minute; a filtered run on one host takes a few seconds. + +## Cases + +| Case | One operation | +| ------------------------------------------- | -------------------------------------------------------------- | +| `Effect/yield` | `Effect.yieldNow` | +| `Effect/forkJoin` | fork a child fiber and join it | +| `Queue/queueTake` | offer and take one item through a bounded queue of 16 | +| `Pool/get and release (fixed pool)` | `Effect.scoped(Pool.get(pool))` on an idle pool of 4 | +| `Pool/poolUseContended` | `Pool.use` from one of 8 fibers sharing a pool of 4 | +| `HashMap/set n fresh string keys + get all` | set one new string key, then read it back | +| `Schema/decode struct (valid)` | `Schema.decodeUnknownSync` of a nested struct | +| `app/app-untraced` | one request through two services, a layer and a caught failure | + +Cases are defined in `cases.ts`. Each one validates its result before and +after timing. + +## Usage + +```sh +pnpm hostperf # all cases, all hosts +pnpm hostperf Pool Effect/yield # cases whose name contains a filter +pnpm hostperf --host node,chromium # a subset of hosts +pnpm hostperf --rounds 1 # quicker, less reliable comparisons +pnpm hostperf --list # case names +``` + +To check a change, record a baseline before it and compare after it: + +```sh +git switch main +pnpm hostperf --out tmp/hostperf/main.json +git switch my-branch +pnpm hostperf --baseline tmp/hostperf/main.json +``` + +The comparison prints `median(baseline) / median(current)` per host and case, +so values above 1 mean the current tree is faster. The 95% interval comes from +a bootstrap that resamples rounds and then the samples inside them, so noise +between processes counts as well as noise between samples. A case is marked +`faster` or `slower` only when the whole interval is more than 5% away from 1. +Reports are only comparable when they come from the same machine and settings. + +Browsers come from Playwright. Install them once with +`pnpm exec playwright install chromium-headless-shell webkit`. Bun must be on +`PATH`; the Nix dev shell provides it. + +## Measurement + +`cases.ts`, `harness.ts` and `entry.ts` are bundled once with Vite into +`tmp/hostperf/bundle/hostperf.js`, so every host runs the same code. Each case +then runs in a fresh process (Node.js, Bun) or a fresh browser context, so JIT +state from one case does not leak into the next. Every round runs every case +once, in that fresh setting. + +For each case and round the harness: + +1. runs and validates the case once, then keeps running it until the warmup + time has passed; +2. picks a batch size so one batch takes at least `--sample-ms`; +3. times `--samples` batches, stopping early once the round has used + `--max-case-ms` and has at least 3 samples; +4. validates the last result. + +Pages are served from an intercepted `http://localhost` origin with +cross-origin isolation headers, which gives browsers their finest +`performance.now()` resolution. The report records the resolution each host +actually had. + +| Option | Default | Meaning | +| --------------- | ------- | ------------------------------------ | +| `--rounds` | 3 | fresh processes or pages per case | +| `--samples` | 10 | timed batches per case and round | +| `--sample-ms` | 10 | target duration of one batch | +| `--warmup-ms` | 100 | warmup per case and round | +| `--max-case-ms` | 1000 | time after which a round stops early | + +## Report + +Reports are written to `tmp/hostperf/results/.json` unless `--out` +is given: + +```json +{ + "schemaVersion": 1, + "createdAt": "2026-11-27T20:30:00.000Z", + "git": { "sha": "8245e5a2...", "dirty": true }, + "settings": { "samples": 10, "sampleMs": 10, "warmupMs": 100, "maxCaseMs": 1000, "minSamples": 3, "rounds": 3 }, + "durationMs": 33800, + "hosts": [ + { + "host": "node", + "runtime": "Node.js v26.13.0", + "timerResolutionMs": 0.0002, + "durationMs": 9400, + "cases": [ + { + "name": "Effect/yield", + "operations": 100, + "medianNs": 1331.2, + "minNs": 1302.5, + "maxNs": 1398.0, + "rounds": [ + { "batchSize": 77, "samples": [1331.2, 1329.9], "durationMs": 312 } + ] + } + ], + "errors": [] + } + ] +} +``` + +`samples` are nanoseconds per operation, and the case medians cover the samples +of every round. A host that fails to start, or a case that throws, is listed in +`errors` and makes the command exit with code 1. The other hosts still run. diff --git a/packages/effect/benchmark/hostperf/cases.ts b/packages/effect/benchmark/hostperf/cases.ts new file mode 100644 index 00000000000..50517401d54 --- /dev/null +++ b/packages/effect/benchmark/hostperf/cases.ts @@ -0,0 +1,233 @@ +import { Context, Data, Effect, Exit, Fiber, HashMap, Layer, ManagedRuntime, Pool, Queue, Schema, Scope } from "effect" + +/** + * One measured operation. `run` may return a Promise; sync cases are timed + * without awaiting so the loop adds no microtask cost. + */ +export interface Instance { + readonly run: () => unknown + readonly validate: (result: unknown) => void + readonly dispose?: () => Promise +} + +export interface BenchCase { + readonly name: string + /** Logical operations performed by one `run`; results are reported per operation. */ + readonly operations: number + readonly make: () => Instance | Promise +} + +const expectEqual = (actual: unknown, expected: unknown) => { + if (actual !== expected) { + throw new Error(`Expected ${String(expected)}, received ${String(actual)}`) + } +} + +const yieldCount = 100 +const forkCount = 100 +const queueItems = 1_000 +const poolSize = 4 +const poolGets = 1_000 +const contendedFibers = 8 +const contendedGets = 8 +const hashMapKeys = 1_000 +const appRequests = 100 + +const sumTo = (n: number) => n * (n - 1) / 2 + +const makePool = async () => { + const scope = await Effect.runPromise(Scope.make()) + let next = 0 + const pool = await Effect.runPromise( + Pool.make({ acquire: Effect.sync(() => ++next), size: poolSize }).pipe(Scope.provide(scope)) + ) + return { pool, dispose: () => Effect.runPromise(Scope.close(scope, Exit.void)) } +} + +class NotFound extends Data.TaggedError("NotFound")<{ readonly id: number }> {} + +class Users extends Context.Service Effect.Effect<{ readonly id: number; readonly name: string }, NotFound> +}>()("hostperf/Users") {} + +class Greeter extends Context.Service Effect.Effect +}>()("hostperf/Greeter") {} + +const UsersLive = Layer.sync(Users)(() => { + const users = new Map(Array.from({ length: 90 }, (_, id) => [id, { id, name: `user-${id}` }])) + return Users.of({ + find: (id) => { + const user = users.get(id) + return user === undefined ? Effect.fail(new NotFound({ id })) : Effect.succeed(user) + } + }) +}) + +const GreeterLive = Layer.effect(Greeter)(Effect.gen(function*() { + const prefix = yield* Effect.succeed("hello ") + return Greeter.of({ greet: (name) => Effect.sync(() => prefix + name) }) +})) + +const handleRequest = Effect.fnUntraced(function*(id: number) { + const users = yield* Users + const greeter = yield* Greeter + const user = yield* users.find(id) + return yield* greeter.greet(user.name) +}, Effect.catchTag("NotFound", (error) => Effect.succeed(`missing ${error.id}`))) + +const UserSchema = Schema.Struct({ + id: Schema.Number, + name: Schema.String, + email: Schema.String, + active: Schema.Boolean, + tags: Schema.Array(Schema.String), + address: Schema.Struct({ + street: Schema.String, + city: Schema.String, + zip: Schema.optional(Schema.String) + }) +}) + +export const cases: ReadonlyArray = [ + { + name: "Effect/yield", + operations: yieldCount, + make: () => { + const program = Effect.gen(function*() { + let i = 0 + for (; i < yieldCount; i++) yield* Effect.yieldNow + return i + }) + return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, yieldCount) } + } + }, + { + name: "Effect/forkJoin", + operations: forkCount, + make: () => { + const program = Effect.gen(function*() { + const fibers: Array> = [] + for (let i = 0; i < forkCount; i++) fibers.push(yield* Effect.forkChild(Effect.succeed(i))) + let sum = 0 + for (const fiber of fibers) sum += yield* Fiber.join(fiber) + return sum + }) + return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, sumTo(forkCount)) } + } + }, + { + name: "Queue/queueTake", + operations: queueItems, + make: () => { + const program = Effect.gen(function*() { + const queue = yield* Queue.bounded(16) + yield* Effect.forkChild(Effect.gen(function*() { + for (let i = 0; i < queueItems; i++) yield* Queue.offer(queue, i) + })) + let sum = 0 + for (let i = 0; i < queueItems; i++) sum += yield* Queue.take(queue) + return sum + }) + return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, sumTo(queueItems)) } + } + }, + { + name: "Pool/get and release (fixed pool)", + operations: poolGets, + make: async () => { + const { dispose, pool } = await makePool() + const program = Effect.gen(function*() { + let count = 0 + for (let i = 0; i < poolGets; i++) { + if ((yield* Effect.scoped(Pool.get(pool))) > 0) count++ + } + return count + }) + return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, poolGets), dispose } + } + }, + { + name: "Pool/poolUseContended", + operations: contendedFibers * contendedGets, + make: async () => { + const { dispose, pool } = await makePool() + const worker = Effect.gen(function*() { + let count = 0 + for (let i = 0; i < contendedGets; i++) { + count += yield* Pool.use(pool, () => Effect.as(Effect.yieldNow, 1)) + } + return count + }) + const program = Effect.all(Array.from({ length: contendedFibers }, () => worker), { + concurrency: "unbounded" + }).pipe(Effect.map((counts) => counts.reduce((a, b) => a + b, 0))) + return { + run: () => Effect.runPromise(program), + validate: (result) => expectEqual(result, contendedFibers * contendedGets), + dispose + } + } + }, + { + name: "HashMap/set n fresh string keys + get all", + operations: hashMapKeys, + make: () => { + let round = 0 + return { + run: () => { + const prefix = `k${round++}-` + const keys = new Array(hashMapKeys) + for (let i = 0; i < hashMapKeys; i++) keys[i] = prefix + i + let map = HashMap.empty() + for (let i = 0; i < hashMapKeys; i++) map = HashMap.set(map, keys[i], i) + let sum = 0 + for (let i = 0; i < hashMapKeys; i++) { + const value = HashMap.get(map, keys[i]) + if (value._tag === "Some") sum += value.value + } + return sum + }, + validate: (result) => expectEqual(result, sumTo(hashMapKeys)) + } + } + }, + { + name: "Schema/decode struct (valid)", + operations: 1, + make: () => { + const decode = Schema.decodeUnknownSync(UserSchema) + const input = { + id: 1, + name: "Ada", + email: "ada@example.com", + active: true, + tags: ["admin", "ops", "dev"], + address: { street: "1 Main St", city: "London", zip: "N1" } + } + return { + run: () => decode(input), + validate: (result) => expectEqual((result as typeof input).address.city, "London") + } + } + }, + { + name: "app/app-untraced", + operations: appRequests, + make: async () => { + const runtime = ManagedRuntime.make(Layer.mergeAll(UsersLive, GreeterLive)) + await runtime.runPromise(Effect.void) + const ids = Array.from({ length: appRequests }, (_, i) => i) + const program = Effect.forEach(ids, handleRequest) + return { + run: () => runtime.runPromise(program), + validate: (result) => { + const responses = result as ReadonlyArray + expectEqual(responses[0], "hello user-0") + expectEqual(responses[appRequests - 1], `missing ${appRequests - 1}`) + }, + dispose: () => runtime.dispose() + } + } + } +] diff --git a/packages/effect/benchmark/hostperf/entry.ts b/packages/effect/benchmark/hostperf/entry.ts new file mode 100644 index 00000000000..d92338a4389 --- /dev/null +++ b/packages/effect/benchmark/hostperf/entry.ts @@ -0,0 +1,25 @@ +/** + * Bundle entry shared by every host. It only uses APIs available in browsers, + * Node.js and Bun, and exposes the runner on `globalThis.__hostperf`. + */ +import { cases } from "./cases.ts" +import { measure, type Settings, timerResolutionMs } from "./harness.ts" + +const runtime = (): string => { + const g = globalThis as any + if (g.Bun !== undefined) return `Bun ${g.Bun.version}` + if (g.process?.versions?.node !== undefined) return `Node.js ${g.process.version}` + return g.navigator?.userAgent ?? "unknown" +} + +const run = async (options: { readonly case: string; readonly settings: Settings }) => { + const benchCase = cases.find((c) => c.name === options.case) + if (benchCase === undefined) throw new Error(`Unknown case ${options.case}`) + return { + operations: benchCase.operations, + runtime: runtime(), + timerResolutionMs: timerResolutionMs(), + result: await measure(benchCase, options.settings) + } +} +;(globalThis as any).__hostperf = { cases: cases.map((c) => c.name), run } diff --git a/packages/effect/benchmark/hostperf/harness.ts b/packages/effect/benchmark/hostperf/harness.ts new file mode 100644 index 00000000000..c41d0135954 --- /dev/null +++ b/packages/effect/benchmark/hostperf/harness.ts @@ -0,0 +1,97 @@ +import type { BenchCase, Instance } from "./cases.ts" + +export interface Settings { + /** Time spent running the case before calibration. */ + readonly warmupMs: number + /** Target duration of one timed sample; the batch size is calibrated to reach it. */ + readonly sampleMs: number + readonly samples: number + /** Stop sampling once a case has run this long and has at least `minSamples`. */ + readonly maxCaseMs: number + readonly minSamples: number +} + +/** One fresh process or page running one case. */ +export interface RoundResult { + readonly batchSize: number + /** Nanoseconds per operation, one entry per timed batch. */ + readonly samples: ReadonlyArray + readonly durationMs: number +} + +const isPromiseLike = (value: unknown): value is PromiseLike => + value !== null && (typeof value === "object" || typeof value === "function") && + typeof (value as PromiseLike).then === "function" + +const makeBatch = (instance: Instance, async: boolean) => + async + ? async (size: number) => { + let result: unknown + for (let i = 0; i < size; i++) result = await instance.run() + return result + } + : (size: number) => { + let result: unknown + for (let i = 0; i < size; i++) result = instance.run() + return result + } + +const time = async (batch: (size: number) => unknown, size: number) => { + const start = performance.now() + const result = await batch(size) + return { elapsedMs: performance.now() - start, result } +} + +export const measure = async (benchCase: BenchCase, settings: Settings): Promise => { + const started = performance.now() + const instance = await benchCase.make() + try { + // The validated first run counts towards the warmup. + const warmupEnd = performance.now() + settings.warmupMs + const first = instance.run() + const async = isPromiseLike(first) + instance.validate(await first) + const batch = makeBatch(instance, async) + while (performance.now() < warmupEnd) await batch(1) + + const toNsPerOp = (elapsedMs: number) => elapsedMs * 1e6 / (batchSize * benchCase.operations) + let batchSize = 1 + let calibrated = await time(batch, batchSize) + while (calibrated.elapsedMs < settings.sampleMs) { + // Jump close to the target instead of doubling from 1 for fast cases. + batchSize = Math.max( + batchSize * 2, + Math.ceil(batchSize * settings.sampleMs / Math.max(calibrated.elapsedMs, 0.01) * 0.9) + ) + calibrated = await time(batch, batchSize) + } + + // The final calibration batch has the measured batch size, so it is the first sample. + const samples = [toNsPerOp(calibrated.elapsedMs)] + let result = calibrated.result + while ( + samples.length < settings.samples && + (samples.length < settings.minSamples || performance.now() - started < settings.maxCaseMs) + ) { + const sample = await time(batch, batchSize) + result = sample.result + samples.push(toNsPerOp(sample.elapsedMs)) + } + instance.validate(result) + return { batchSize, samples, durationMs: performance.now() - started } + } finally { + await instance.dispose?.() + } +} + +/** Smallest observable `performance.now()` step, which differs widely between hosts. */ +export const timerResolutionMs = (): number => { + let smallest = Infinity + for (let i = 0; i < 20; i++) { + const start = performance.now() + let next = performance.now() + while (next === start) next = performance.now() + smallest = Math.min(smallest, next - start) + } + return smallest +} diff --git a/packages/effect/benchmark/hostperf/run.ts b/packages/effect/benchmark/hostperf/run.ts new file mode 100644 index 00000000000..693e0a0472d --- /dev/null +++ b/packages/effect/benchmark/hostperf/run.ts @@ -0,0 +1,311 @@ +/** + * Runs the hostperf cases in Node.js, Bun, Chromium and WebKit and writes one + * JSON report. See README.md. + */ +import { spawn, spawnSync } from "node:child_process" +import { mkdirSync, readFileSync, writeFileSync } from "node:fs" +import { dirname, join, relative, resolve } from "node:path" +import { fileURLToPath } from "node:url" +import { parseArgs } from "node:util" +import type { Browser } from "playwright" +import { chromium, webkit } from "playwright" +import { build } from "vite" +import type { RoundResult, Settings } from "./harness.ts" +import { median, speedup } from "./stats.ts" + +const hostperfDir = dirname(fileURLToPath(import.meta.url)) +const repoRoot = resolve(hostperfDir, "../../../..") +const tmpDir = join(repoRoot, "tmp", "hostperf") +const bundleDir = join(tmpDir, "bundle") + +const allHosts = ["node", "bun", "chromium", "webkit"] as const +type Host = typeof allHosts[number] + +interface Measurement { + readonly operations: number + readonly runtime: string + readonly timerResolutionMs: number + readonly result: RoundResult +} + +interface CaseReport { + readonly name: string + readonly operations: number + /** Over the samples of every round, in nanoseconds per operation. */ + medianNs: number + minNs: number + maxNs: number + readonly rounds: Array +} + +interface HostReport { + readonly host: Host + runtime?: string + timerResolutionMs?: number + durationMs: number + readonly cases: Array + readonly errors: Array +} + +interface Report { + readonly schemaVersion: 1 + readonly createdAt: string + readonly git: { readonly sha: string; readonly dirty: boolean } + readonly settings: Settings & { readonly rounds: number } + durationMs: number + readonly hosts: Array +} + +const usage = `Usage: pnpm hostperf [case-filter...] [options] + +Options: + --host Comma-separated hosts (default: ${allHosts.join(",")}) + --baseline Compare against an earlier report + --out Report path (default: tmp/hostperf/results/.json) + --rounds Fresh processes or pages per case (default: 3) + --samples Timed samples per case and round (default: 10) + --sample-ms Target duration of one sample (default: 10) + --warmup-ms Warmup per case and round (default: 100) + --max-case-ms Stop sampling a slow round after this long, keeping at least 3 samples (default: 1000) + --list Print the case names +` + +const { positionals, values } = parseArgs({ + allowPositionals: true, + options: { + host: { type: "string", default: allHosts.join(",") }, + baseline: { type: "string" }, + out: { type: "string" }, + rounds: { type: "string", default: "3" }, + samples: { type: "string", default: "10" }, + "sample-ms": { type: "string", default: "10" }, + "warmup-ms": { type: "string", default: "100" }, + "max-case-ms": { type: "string", default: "1000" }, + list: { type: "boolean", default: false }, + help: { type: "boolean", default: false } + } +}) + +const positive = (name: string, raw: string) => { + const value = Number(raw) + if (!Number.isFinite(value) || value <= 0) throw new Error(`--${name} must be a positive number`) + return value +} + +const git = (...args: Array) => spawnSync("git", args, { cwd: repoRoot, encoding: "utf8" }).stdout.trim() + +const bundle = async () => { + await build({ + configFile: false, + logLevel: "warn", + resolve: { + alias: [{ find: /^effect$/, replacement: resolve(hostperfDir, "../../src/index.ts") }] + }, + build: { + outDir: bundleDir, + emptyOutDir: true, + minify: false, + target: "es2022", + lib: { entry: join(hostperfDir, "entry.ts"), formats: ["es"], fileName: () => "hostperf.js" } + } + }) + const runner = join(bundleDir, "runner.mjs") + writeFileSync( + runner, + `await import("./hostperf.js") +const output = await globalThis.__hostperf.run(JSON.parse(process.argv[2])) +process.stdout.write(JSON.stringify(output), () => process.exit(0)) +` + ) + return { script: join(bundleDir, "hostperf.js"), runner } +} + +const runProcess = (command: string, args: Array) => + new Promise((resolvePromise, reject) => { + const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] }) + let stdout = "" + let stderr = "" + child.stdout.on("data", (chunk) => stdout += chunk) + child.stderr.on("data", (chunk) => stderr += chunk) + child.on("error", reject) + child.on("close", (code) => { + if (code === 0) resolvePromise(JSON.parse(stdout)) + else reject(new Error(`${command} exited with ${code}: ${stderr.trim()}`)) + }) + }) + +const origin = "http://localhost" + +const runPage = async (browser: Browser, script: string, input: unknown): Promise => { + const context = await browser.newContext() + try { + // Cross-origin isolation gives the page its finest performance.now() resolution. + const headers = { + "cross-origin-opener-policy": "same-origin", + "cross-origin-embedder-policy": "require-corp" + } + await context.route(`${origin}/**`, (route) => { + const url = new URL(route.request().url()) + return url.pathname === "/hostperf.js" + ? route.fulfill({ headers, contentType: "text/javascript", body: script }) + : route.fulfill({ + headers, + contentType: "text/html", + body: "" + }) + }) + const page = await context.newPage() + await page.goto(`${origin}/`) + await page.waitForFunction(() => (globalThis as any).__hostperf !== undefined) + return await page.evaluate((input) => (globalThis as any).__hostperf.run(input), input) + } finally { + await context.close() + } +} + +/** Changes inside this band are reported as `same`, even when the interval excludes 1. */ +const noiseBand = 0.05 + +const formatNs = (ns: number) => + ns >= 1e6 ? `${(ns / 1e6).toFixed(2)} ms` : ns >= 1e3 ? `${(ns / 1e3).toFixed(2)} µs` : `${ns.toFixed(1)} ns` + +const formatX = (value: number) => `${value >= 10 ? value.toFixed(1) : value.toFixed(2)}x` + +const printTable = (rows: ReadonlyArray>) => { + const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length))) + for (const row of rows) console.log(row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd()) +} + +const printReport = (report: Report, baseline: Report | undefined) => { + const samples = (c: CaseReport) => c.rounds.map((round) => round.samples) + const rows: Array<{ readonly cells: Array; readonly sort: number }> = [] + for (const host of report.hosts) { + for (const result of host.cases) { + const cells = [host.host, result.name, formatNs(result.medianNs), String(samples(result).flat().length)] + const base = baseline?.hosts.find((h) => h.host === host.host)?.cases.find((c) => c.name === result.name) + if (baseline === undefined) { + rows.push({ cells, sort: 0 }) + } else if (base === undefined) { + rows.push({ cells: [...cells, "-", "-", "-"], sort: -Infinity }) + } else { + const s = speedup(samples(base), samples(result)) + const verdict = s.low > 1 + noiseBand ? "faster" : s.high < 1 / (1 + noiseBand) ? "slower" : "same" + cells.push(formatX(s.speedup), `${formatX(s.low)}-${formatX(s.high)}`, verdict) + rows.push({ cells, sort: s.speedup }) + } + } + } + if (baseline !== undefined) rows.sort((a, b) => b.sort - a.sort) + const header = ["host", "case", "median/op", "n"] + if (baseline !== undefined) header.push("speedup", "95% CI", "") + printTable([header, ...rows.map((row) => row.cells)]) + for (const host of report.hosts) { + for (const error of host.errors) console.error(`${host.host}: ${error}`) + } +} + +const main = async () => { + if (values.help) { + console.log(usage) + return + } + const hosts = values.host.split(",").map((host) => host.trim()) as Array + for (const host of hosts) { + if (!allHosts.includes(host)) throw new Error(`Unknown host ${host}; expected one of ${allHosts.join(", ")}`) + } + const settings: Settings = { + samples: positive("samples", values.samples), + sampleMs: positive("sample-ms", values["sample-ms"]), + warmupMs: positive("warmup-ms", values["warmup-ms"]), + maxCaseMs: positive("max-case-ms", values["max-case-ms"]), + minSamples: 3 + } + const rounds = positive("rounds", values.rounds) + const baseline: Report | undefined = values.baseline === undefined + ? undefined + : JSON.parse(readFileSync(values.baseline, "utf8")) + + const started = performance.now() + const { runner, script } = await bundle() + await import(script) + const allCases: ReadonlyArray = (globalThis as any).__hostperf.cases + if (values.list) { + for (const name of allCases) console.log(name) + return + } + const filters = positionals.map((filter) => filter.toLowerCase()) + const selected = allCases.filter((name) => + filters.length === 0 || filters.some((filter) => name.toLowerCase().includes(filter)) + ) + if (selected.length === 0) throw new Error(`No cases match ${positionals.join(", ")}`) + + const report: Report = { + schemaVersion: 1, + createdAt: new Date().toISOString(), + git: { sha: git("rev-parse", "HEAD"), dirty: git("status", "--porcelain") !== "" }, + settings: { ...settings, rounds }, + durationMs: 0, + hosts: [] + } + const scriptSource = readFileSync(script, "utf8") + + for (const host of hosts) { + const hostStarted = performance.now() + const hostReport: HostReport = { host, durationMs: 0, cases: [], errors: [] } + report.hosts.push(hostReport) + let browser: Browser | undefined + try { + if (host === "chromium" || host === "webkit") { + browser = await (host === "chromium" ? chromium : webkit).launch() + } else if (host === "bun" && spawnSync("bun", ["--version"]).error !== undefined) { + throw new Error("bun is not on PATH") + } + // Every round runs every case in a fresh process or page, so JIT state + // does not leak between cases and noise between processes is measured. + const byName = new Map() + for (let round = 1; round <= rounds; round++) { + for (const name of selected) { + const input = { case: name, settings } + try { + const measurement = browser === undefined + ? await runProcess(host === "node" ? process.execPath : "bun", [runner, JSON.stringify(input)]) + : await runPage(browser, scriptSource, input) + hostReport.runtime = measurement.runtime + hostReport.timerResolutionMs = measurement.timerResolutionMs + const caseReport = byName.get(name) ?? + { name, operations: measurement.operations, medianNs: 0, minNs: 0, maxNs: 0, rounds: [] } + caseReport.rounds.push(measurement.result) + byName.set(name, caseReport) + console.error(`${host} ${name} #${round}: ${formatNs(median(measurement.result.samples))}/op`) + } catch (error) { + hostReport.errors.push(`${name} #${round}: ${error instanceof Error ? error.message : String(error)}`) + } + } + } + for (const caseReport of byName.values()) { + const all = caseReport.rounds.flatMap((round) => round.samples) + caseReport.medianNs = median(all) + caseReport.minNs = Math.min(...all) + caseReport.maxNs = Math.max(...all) + hostReport.cases.push(caseReport) + } + } catch (error) { + hostReport.errors.push(error instanceof Error ? error.message : String(error)) + } finally { + await browser?.close() + hostReport.durationMs = performance.now() - hostStarted + } + } + report.durationMs = performance.now() - started + + const out = resolve(values.out ?? join(tmpDir, "results", `${report.createdAt.replace(/[:.]/g, "-")}.json`)) + mkdirSync(dirname(out), { recursive: true }) + writeFileSync(out, `${JSON.stringify(report, null, 2)}\n`) + printReport(report, baseline) + const seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s` + const perHost = report.hosts.map((host) => `${host.host} ${seconds(host.durationMs)}`).join(", ") + console.log(`\nWrote ${relative(process.cwd(), out)} in ${seconds(report.durationMs)} (${perHost})`) + if (report.hosts.some((host) => host.errors.length > 0)) process.exitCode = 1 +} + +await main() diff --git a/packages/effect/benchmark/hostperf/stats.ts b/packages/effect/benchmark/hostperf/stats.ts new file mode 100644 index 00000000000..597058b9112 --- /dev/null +++ b/packages/effect/benchmark/hostperf/stats.ts @@ -0,0 +1,58 @@ +export const median = (values: ReadonlyArray): number => { + const sorted = values.slice().sort((a, b) => a - b) + const middle = Math.floor(sorted.length / 2) + return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle] +} + +const percentile = (sorted: ReadonlyArray, probability: number): number => { + const index = (sorted.length - 1) * probability + const lower = Math.floor(index) + const upper = Math.ceil(index) + return sorted[lower] + (sorted[upper] - sorted[lower]) * (index - lower) +} + +// mulberry32, so repeated comparisons of the same files print the same intervals +const makeRandom = (seed: number) => { + let state = seed >>> 0 + return () => { + state += 0x6d2b79f5 + let value = state + value = Math.imul(value ^ value >>> 15, value | 1) + value ^= value + Math.imul(value ^ value >>> 7, value | 61) + return ((value ^ value >>> 14) >>> 0) / 4294967296 + } +} + +export interface Speedup { + /** `median(base) / median(head)`: above 1 means head is faster. */ + readonly speedup: number + readonly low: number + readonly high: number +} + +/** + * Speedup of `head` over `base`. Each side is a list of rounds (fresh + * processes) holding samples. The percentile bootstrap resamples rounds, then + * samples within each chosen round, so noise between processes widens the + * interval as well as noise between samples. + */ +export const speedup = ( + base: ReadonlyArray>, + head: ReadonlyArray>, + { confidence = 0.95, iterations = 2_000, seed = 0x5eed1234 } = {} +): Speedup => { + const random = makeRandom(seed) + const pick = (values: ReadonlyArray) => values[Math.floor(random() * values.length)] + const resample = (rounds: ReadonlyArray>) => + median(rounds.flatMap(() => { + const round = pick(rounds) + return round.map(() => pick(round)) + })) + const ratios = Array.from({ length: iterations }, () => resample(base) / resample(head)).sort((a, b) => a - b) + const tail = (1 - confidence) / 2 + return { + speedup: median(base.flat()) / median(head.flat()), + low: percentile(ratios, tail), + high: percentile(ratios, 1 - tail) + } +} From 346403ea1129ea4341c6f598f0a2417db166bf62 Mon Sep 17 00:00:00 2001 From: Tim Smart Date: Fri, 27 Nov 2026 20:33:54 +0000 Subject: [PATCH 2/2] hostperf: per-round deadline, robust output parsing, integer counts, inconclusive verdict --- packages/effect/benchmark/hostperf/README.md | 8 +- packages/effect/benchmark/hostperf/run.ts | 105 +++++++++++++------ 2 files changed, 80 insertions(+), 33 deletions(-) diff --git a/packages/effect/benchmark/hostperf/README.md b/packages/effect/benchmark/hostperf/README.md index 7d6a17258dd..0b6a465f8db 100644 --- a/packages/effect/benchmark/hostperf/README.md +++ b/packages/effect/benchmark/hostperf/README.md @@ -43,7 +43,9 @@ The comparison prints `median(baseline) / median(current)` per host and case, so values above 1 mean the current tree is faster. The 95% interval comes from a bootstrap that resamples rounds and then the samples inside them, so noise between processes counts as well as noise between samples. A case is marked -`faster` or `slower` only when the whole interval is more than 5% away from 1. +`faster` or `slower` when the whole interval is more than 5% away from 1, and +`same` when the whole interval is within 5% of 1. Anything else is +`inconclusive`; more `--rounds` may settle it. Reports are only comparable when they come from the same machine and settings. Browsers come from Playwright. Install them once with @@ -79,6 +81,7 @@ actually had. | `--sample-ms` | 10 | target duration of one batch | | `--warmup-ms` | 100 | warmup per case and round | | `--max-case-ms` | 1000 | time after which a round stops early | +| `--timeout-ms` | 60000 | time after which a round is killed | ## Report @@ -117,5 +120,6 @@ is given: ``` `samples` are nanoseconds per operation, and the case medians cover the samples -of every round. A host that fails to start, or a case that throws, is listed in +of every round. A host that fails to start, or a case that throws, times out or prints +something other than its measurement, is listed in `errors` and makes the command exit with code 1. The other hosts still run. diff --git a/packages/effect/benchmark/hostperf/run.ts b/packages/effect/benchmark/hostperf/run.ts index 693e0a0472d..b1012b90085 100644 --- a/packages/effect/benchmark/hostperf/run.ts +++ b/packages/effect/benchmark/hostperf/run.ts @@ -7,7 +7,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs" import { dirname, join, relative, resolve } from "node:path" import { fileURLToPath } from "node:url" import { parseArgs } from "node:util" -import type { Browser } from "playwright" +import type { Browser, BrowserContext } from "playwright" import { chromium, webkit } from "playwright" import { build } from "vite" import type { RoundResult, Settings } from "./harness.ts" @@ -67,6 +67,7 @@ Options: --sample-ms Target duration of one sample (default: 10) --warmup-ms Warmup per case and round (default: 100) --max-case-ms Stop sampling a slow round after this long, keeping at least 3 samples (default: 1000) + --timeout-ms Kill a round that has not finished after this long (default: 60000) --list Print the case names ` @@ -81,6 +82,7 @@ const { positionals, values } = parseArgs({ "sample-ms": { type: "string", default: "10" }, "warmup-ms": { type: "string", default: "100" }, "max-case-ms": { type: "string", default: "1000" }, + "timeout-ms": { type: "string", default: "60000" }, list: { type: "boolean", default: false }, help: { type: "boolean", default: false } } @@ -92,6 +94,12 @@ const positive = (name: string, raw: string) => { return value } +const positiveInteger = (name: string, raw: string) => { + const value = Number(raw) + if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`--${name} must be a positive integer`) + return value +} + const git = (...args: Array) => spawnSync("git", args, { cwd: repoRoot, encoding: "utf8" }).stdout.trim() const bundle = async () => { @@ -120,52 +128,87 @@ process.stdout.write(JSON.stringify(output), () => process.exit(0)) return { script: join(bundleDir, "hostperf.js"), runner } } -const runProcess = (command: string, args: Array) => +const timeoutError = (timeoutMs: number) => new Error(`Timed out after ${timeoutMs} ms`) + +const runProcess = (command: string, args: Array, timeoutMs: number) => new Promise((resolvePromise, reject) => { const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] }) let stdout = "" let stderr = "" + let timedOut = false + const timer = setTimeout(() => { + timedOut = true + child.kill("SIGKILL") + }, timeoutMs) child.stdout.on("data", (chunk) => stdout += chunk) child.stderr.on("data", (chunk) => stderr += chunk) child.on("error", reject) child.on("close", (code) => { - if (code === 0) resolvePromise(JSON.parse(stdout)) - else reject(new Error(`${command} exited with ${code}: ${stderr.trim()}`)) + clearTimeout(timer) + if (timedOut) return reject(timeoutError(timeoutMs)) + if (code !== 0) return reject(new Error(`${command} exited with ${code}: ${stderr.trim()}`)) + try { + resolvePromise(JSON.parse(stdout)) + } catch { + reject(new Error(`${command} wrote output that is not a measurement: ${stdout.slice(0, 200)}`)) + } }) }) const origin = "http://localhost" -const runPage = async (browser: Browser, script: string, input: unknown): Promise => { +const runPage = async (browser: Browser, script: string, input: unknown, timeoutMs: number): Promise => { const context = await browser.newContext() + let timer: ReturnType | undefined + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(timeoutError(timeoutMs)), timeoutMs) + }) try { - // Cross-origin isolation gives the page its finest performance.now() resolution. - const headers = { - "cross-origin-opener-policy": "same-origin", - "cross-origin-embedder-policy": "require-corp" - } - await context.route(`${origin}/**`, (route) => { - const url = new URL(route.request().url()) - return url.pathname === "/hostperf.js" - ? route.fulfill({ headers, contentType: "text/javascript", body: script }) - : route.fulfill({ - headers, - contentType: "text/html", - body: "" - }) - }) - const page = await context.newPage() - await page.goto(`${origin}/`) - await page.waitForFunction(() => (globalThis as any).__hostperf !== undefined) - return await page.evaluate((input) => (globalThis as any).__hostperf.run(input), input) + return await Promise.race([measurePage(context, script, input), deadline]) } finally { + clearTimeout(timer) + // Closing the context also abandons a page that is still measuring. await context.close() } } -/** Changes inside this band are reported as `same`, even when the interval excludes 1. */ +const measurePage = async (context: BrowserContext, script: string, input: unknown): Promise => { + // Cross-origin isolation gives the page its finest performance.now() resolution. + const headers = { + "cross-origin-opener-policy": "same-origin", + "cross-origin-embedder-policy": "require-corp" + } + await context.route(`${origin}/**`, (route) => { + const url = new URL(route.request().url()) + return url.pathname === "/hostperf.js" + ? route.fulfill({ headers, contentType: "text/javascript", body: script }) + : route.fulfill({ + headers, + contentType: "text/html", + body: "" + }) + }) + const page = await context.newPage() + await page.goto(`${origin}/`) + await page.waitForFunction(() => (globalThis as any).__hostperf !== undefined) + return await page.evaluate((input) => (globalThis as any).__hostperf.run(input), input) +} + +/** + * A case is `faster` or `slower` when its whole interval is outside this band, + * `same` when the whole interval is inside it, and `inconclusive` otherwise. + */ const noiseBand = 0.05 +const verdict = ({ high, low }: { readonly low: number; readonly high: number }) => + low > 1 + noiseBand + ? "faster" + : high < 1 / (1 + noiseBand) + ? "slower" + : low >= 1 / (1 + noiseBand) && high <= 1 + noiseBand + ? "same" + : "inconclusive" + const formatNs = (ns: number) => ns >= 1e6 ? `${(ns / 1e6).toFixed(2)} ms` : ns >= 1e3 ? `${(ns / 1e3).toFixed(2)} µs` : `${ns.toFixed(1)} ns` @@ -189,8 +232,7 @@ const printReport = (report: Report, baseline: Report | undefined) => { rows.push({ cells: [...cells, "-", "-", "-"], sort: -Infinity }) } else { const s = speedup(samples(base), samples(result)) - const verdict = s.low > 1 + noiseBand ? "faster" : s.high < 1 / (1 + noiseBand) ? "slower" : "same" - cells.push(formatX(s.speedup), `${formatX(s.low)}-${formatX(s.high)}`, verdict) + cells.push(formatX(s.speedup), `${formatX(s.low)}-${formatX(s.high)}`, verdict(s)) rows.push({ cells, sort: s.speedup }) } } @@ -214,13 +256,14 @@ const main = async () => { if (!allHosts.includes(host)) throw new Error(`Unknown host ${host}; expected one of ${allHosts.join(", ")}`) } const settings: Settings = { - samples: positive("samples", values.samples), + samples: positiveInteger("samples", values.samples), sampleMs: positive("sample-ms", values["sample-ms"]), warmupMs: positive("warmup-ms", values["warmup-ms"]), maxCaseMs: positive("max-case-ms", values["max-case-ms"]), minSamples: 3 } - const rounds = positive("rounds", values.rounds) + const rounds = positiveInteger("rounds", values.rounds) + const timeoutMs = positive("timeout-ms", values["timeout-ms"]) const baseline: Report | undefined = values.baseline === undefined ? undefined : JSON.parse(readFileSync(values.baseline, "utf8")) @@ -268,8 +311,8 @@ const main = async () => { const input = { case: name, settings } try { const measurement = browser === undefined - ? await runProcess(host === "node" ? process.execPath : "bun", [runner, JSON.stringify(input)]) - : await runPage(browser, scriptSource, input) + ? await runProcess(host === "node" ? process.execPath : "bun", [runner, JSON.stringify(input)], timeoutMs) + : await runPage(browser, scriptSource, input, timeoutMs) hostReport.runtime = measurement.runtime hostReport.timerResolutionMs = measurement.timerResolutionMs const caseReport = byName.get(name) ??