From b2c820ebe04407900a2637468ac60bb419da711a Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 23:52:38 -0500 Subject: [PATCH 1/4] feat(bench): decide the cutover rule over two schema-2 artifacts --- .changeset/bench-gate.md | 4 + .knip.json | 1 + package.json | 1 + src/scripts/bench-gate.ts | 365 ++++++++++++++++++ test/unit/scripts/bench-gate.spec.ts | 531 +++++++++++++++++++++++++++ 5 files changed, 902 insertions(+) create mode 100644 .changeset/bench-gate.md create mode 100644 src/scripts/bench-gate.ts create mode 100644 test/unit/scripts/bench-gate.spec.ts diff --git a/.changeset/bench-gate.md b/.changeset/bench-gate.md new file mode 100644 index 000000000..7803e3fb2 --- /dev/null +++ b/.changeset/bench-gate.md @@ -0,0 +1,4 @@ +--- +--- + +bench-gate: decide #868's cutover rule over two schema-2 artifacts (`src/scripts/bench-gate.ts`) diff --git a/.knip.json b/.knip.json index d84dc2d3d..44eb3d15d 100644 --- a/.knip.json +++ b/.knip.json @@ -7,6 +7,7 @@ "src/import-events.ts!", "src/cli/index.ts!", "src/scripts/benchmark-queries.ts!", + "src/scripts/bench-gate.ts!", "knexfile.js!" ], "project": [ diff --git a/package.json b/package.json index 754f439be..8e9761456 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ "db:migrate": "knex migrate:latest", "db:migrate:rollback": "knex migrate:rollback", "db:seed": "knex seed:run", + "bench:gate": "node -r ts-node/register src/scripts/bench-gate.ts", "db:benchmark": "node --env-file-if-exists=.env -r ts-node/register src/scripts/benchmark-queries.ts", "db:verify-index-impact": "node --env-file-if-exists=.env -r ts-node/register scripts/verify-index-impact.ts", "pretest:unit": "pnpm run build && node -e \"require('fs').mkdirSync('.test-reports/unit', {recursive: true})\"", diff --git a/src/scripts/bench-gate.ts b/src/scripts/bench-gate.ts new file mode 100644 index 000000000..3d78bdc07 --- /dev/null +++ b/src/scripts/bench-gate.ts @@ -0,0 +1,365 @@ +import fs from 'node:fs' + +/** + * The cutover gate for #868: two schema-2 benchmark artifacts in, one verdict out. + * + * REQ: each of `by_id`, `author_kind`, `kind_since`, `tag` must have its p95 band within 1.5x of + * the Postgres band's, and the band is tested twice — at its median and at its failing edge + * (`p90`) — each against that same bound. Ingest: `create`'s `per_second` band must be at or + * above 1x the Postgres band's, tested at its median and at its failing edge (`p10`). An item + * whose median is inside the bound but whose failing edge is outside it is a straddle, and a + * straddle fails: the worst repeat is not evidence that the shape sits inside the margin. + */ + +/** The artifact layout version this gate reads (`ARTIFACT_SCHEMA`, bench.rs:87). */ +const ARTIFACT_SCHEMA = 2 + +/** #868's two corpora: the only corpus sizes the rule covers. */ +const COVERED_CORPORA = [1_000_000, 10_000_000] + +/** The REQ read shapes: the four that reach `find_by_filters` (bench.rs:1073). */ +const REQ_SHAPES = ['by_id', 'author_kind', 'kind_since', 'tag'] + +/** The ingest shape: the corpus's last thousand events, one `create` each (bench.rs:1044-1055). */ +const INGEST_SHAPE = 'create' + +/** REQ p95 bound: `lmdb <= 1.5 x postgres`, as integer cross-multiplication. */ +const REQ_MARGIN_DEN = 2 +const REQ_MARGIN_NUM = 3 + +/** Ingest floor: `lmdb >= 1 x postgres`, as integer cross-multiplication. */ +const INGEST_FLOOR = 1 + +/** A gated LMDB band needs three repeats: one or two is a point or a pair, never a straddle. */ +const MIN_LMDB_REPEATS = 3 + +/** The rig's seven shapes, in its fixed order (`SHAPES`, bench.rs:108-116). */ +const SHAPES = ['create_many', 'create', 'by_id', 'author_kind', 'kind_since', 'tag', 'count'] + +/** The three fields of a band, in the order the artifact writes them. */ +const BAND_FIELDS = ['median', 'p10', 'p90'] + +/** The `machine` fields the gate requires; only `profile` is compared. */ +const MACHINE_FIELDS = ['cpu_model', 'os', 'arch', 'profile'] + +type Band = { median: number; p10: number; p90: number } + +type Artifact = { path: string; document: Record } + +type Difference = { path: string; left: unknown; right: unknown } + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value) + +/** A refusal is a thrown message; the entry point turns it into one stderr line and exit 2. */ +const refuse = (detail: string): never => { + throw new Error(detail) +} + +const renderJson = (value: unknown): string => (value === undefined ? 'absent' : JSON.stringify(value)) + +/** + * Exactly two positional arguments, each taken as a path whatever it starts with. Neither order + * nor any flag assigns a role: each artifact's `backend` field does. + */ +export const parseGateArgs = (argv: string[]): string[] => { + if (argv.length !== 2) { + refuse(`expected exactly two artifact paths, got ${argv.length}`) + } + return argv +} + +const readArtifact = (artifactPath: string): Artifact => { + let text: string + try { + text = fs.readFileSync(artifactPath, 'utf8') + } catch { + return refuse(`cannot read ${artifactPath}`) + } + + let document: unknown + try { + document = JSON.parse(text) + } catch { + return refuse(`cannot parse ${artifactPath} as JSON`) + } + + if (!isRecord(document)) { + return refuse(`${artifactPath} is not a JSON object`) + } + + return { path: artifactPath, document } +} + +const assertSchema = (artifact: Artifact): void => { + if (artifact.document.schema !== ARTIFACT_SCHEMA) { + refuse(`${artifact.path}: schema ${renderJson(artifact.document.schema)} is not supported (this gate reads schema 2)`) + } +} + +const deepEqual = (left: unknown, right: unknown): boolean => { + if (left === right) { + return true + } + + if (Array.isArray(left) || Array.isArray(right)) { + if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) { + return false + } + + return left.every((value, index) => deepEqual(value, right[index])) + } + + if (isRecord(left) && isRecord(right)) { + const keys = new Set([...Object.keys(left), ...Object.keys(right)]) + if (keys.size !== Object.keys(left).length || keys.size !== Object.keys(right).length) { + return false + } + + return [...keys].every((key) => deepEqual(left[key], right[key])) + } + + return false +} + +/** + * The first difference between two `workload` echoes, in lexicographic key order, by dotted path. + * Arrays compare element-wise and in order; `workload.repeats` is excluded at the top level, + * because how many times each backend was measured is not what was measured. + */ +const findDifference = (left: unknown, right: unknown, path: string, topLevel = false): Difference | undefined => { + if (isRecord(left) && isRecord(right)) { + const keys = [...new Set([...Object.keys(left), ...Object.keys(right)])] + .filter((key) => !(topLevel && key === 'repeats')) + .sort() + + for (const key of keys) { + const found = findDifference(left[key], right[key], `${path}.${key}`) + if (found !== undefined) { + return found + } + } + + return undefined + } + + return deepEqual(left, right) ? undefined : { path, left, right } +} + +const workloadOf = (artifact: Artifact): Record => { + if (!isRecord(artifact.document.workload)) { + return refuse(`${artifact.path}: workload is not a JSON object`) + } + + return artifact.document.workload +} + +const machineOf = (artifact: Artifact): Record => { + const { volatile } = artifact.document + if (!isRecord(volatile) || !isRecord(volatile.machine)) { + return refuse(`${artifact.path}: volatile.machine is missing`) + } + + return volatile.machine +} + +const shapeNamesOf = (artifact: Artifact): string[] => { + const rows = artifact.document.shapes + if (!Array.isArray(rows)) { + return refuse(`${artifact.path}: shapes is not a JSON array`) + } + + return rows.map((row) => { + if (!isRecord(row) || typeof row.shape !== 'string') { + return refuse(`${artifact.path}: shapes carries a row without a shape name`) + } + + return row.shape + }) +} + +/** One band, refused unless it is three non-negative safe integers ordered `p10 <= median <= p90`. */ +const bandOf = (artifact: Artifact, shape: string, metric: string): Band => { + const repeats = artifact.document.volatile?.repeats + const metrics = isRecord(repeats) ? repeats[shape] : undefined + const band = isRecord(metrics) ? metrics[metric] : undefined + if (!isRecord(band)) { + return refuse(`${artifact.path}: volatile.repeats.${shape}.${metric} is missing`) + } + + for (const field of BAND_FIELDS) { + if (!Number.isSafeInteger(band[field]) || band[field] < 0) { + return refuse(`${artifact.path}: volatile.repeats.${shape}.${metric}.${field} is not a non-negative integer`) + } + } + + if (!(band.p10 <= band.median && band.median <= band.p90)) { + return refuse(`${artifact.path}: volatile.repeats.${shape}.${metric} is not ordered p10 <= median <= p90`) + } + + return { median: band.median, p10: band.p10, p90: band.p90 } +} + +const reqVerdict = (lmdb: Band, postgres: Band): string => { + const medianWithin = lmdb.median * REQ_MARGIN_DEN <= postgres.median * REQ_MARGIN_NUM + const edgeWithin = lmdb.p90 * REQ_MARGIN_DEN <= postgres.p90 * REQ_MARGIN_NUM + + if (medianWithin && edgeWithin) { + return 'within 1.5x' + } + + return medianWithin ? 'straddle 1.5x' : 'outside 1.5x' +} + +const ingestVerdict = (lmdb: Band, postgres: Band): string => { + const medianAtOrAbove = lmdb.median * INGEST_FLOOR >= postgres.median * INGEST_FLOOR + const edgeAtOrAbove = lmdb.p10 * INGEST_FLOOR >= postgres.p10 * INGEST_FLOOR + + if (medianAtOrAbove && edgeAtOrAbove) { + return 'at or above 1.0x' + } + + return medianAtOrAbove ? 'straddle 1.0x' : 'below 1.0x' +} + +const describeMachine = (artifact: Artifact): string => { + const machine = machineOf(artifact) + return `${machine.cpu_model} (${machine.os} ${machine.arch}, profile ${machine.profile})` +} + +export const runBenchGate = async (argv: string[] = process.argv.slice(2)): Promise => { + try { + const [firstPath, secondPath] = parseGateArgs(argv) + const first = readArtifact(firstPath) + const second = readArtifact(secondPath) + const artifacts = [first, second] + + for (const artifact of artifacts) { + assertSchema(artifact) + } + + for (const artifact of artifacts) { + const events = artifact.document.events + if (!COVERED_CORPORA.includes(events)) { + refuse(`${artifact.path}: events ${renderJson(events)} is not a corpus the rule covers (covered: 1000000, 10000000)`) + } + } + + if (first.document.events !== second.document.events) { + refuse(`artifacts name different corpora: ${first.document.events} and ${second.document.events}`) + } + + for (const artifact of artifacts) { + if (!Number.isSafeInteger(artifact.document.seed)) { + refuse(`${artifact.path}: seed is not an integer`) + } + } + + if (first.document.seed !== second.document.seed) { + refuse(`artifacts name different seeds: ${first.document.seed} and ${second.document.seed}`) + } + + const backends = artifacts.map((artifact) => artifact.document.backend) + const lmdbArtifacts = artifacts.filter((artifact) => artifact.document.backend === 'lmdb') + const postgresArtifacts = artifacts.filter((artifact) => artifact.document.backend === 'postgres') + if (lmdbArtifacts.length !== 1 || postgresArtifacts.length !== 1) { + refuse(`expected one lmdb and one postgres artifact, got ${backends[0]} and ${backends[1]}`) + } + + const [lmdbArtifact] = lmdbArtifacts + const [postgresArtifact] = postgresArtifacts + + const lmdbWorkload = workloadOf(lmdbArtifact) + const repeats = lmdbWorkload.repeats + if (!Number.isSafeInteger(repeats)) { + refuse(`${lmdbArtifact.path}: workload.repeats is not a non-negative integer`) + } + + if (repeats < MIN_LMDB_REPEATS) { + refuse(`${lmdbArtifact.path}: workload.repeats ${repeats} is below the minimum of 3`) + } + + const difference = findDifference(workloadOf(first), workloadOf(second), 'workload', true) + if (difference !== undefined) { + refuse(`${difference.path} differs: ${renderJson(difference.left)} and ${renderJson(difference.right)}`) + } + + for (const artifact of artifacts) { + const machine = machineOf(artifact) + for (const field of MACHINE_FIELDS) { + if (!(field in machine)) { + refuse(`${artifact.path}: volatile.machine.${field} is missing`) + } + + if (typeof machine[field] !== 'string') { + refuse(`${artifact.path}: volatile.machine.${field} is not a string`) + } + } + } + + if (machineOf(first).profile !== machineOf(second).profile) { + refuse(`volatile.machine.profile differs: ${renderJson(machineOf(first).profile)} and ${renderJson(machineOf(second).profile)}`) + } + + for (const artifact of artifacts) { + const names = shapeNamesOf(artifact) + for (const name of SHAPES) { + if (!names.includes(name)) { + refuse(`${artifact.path}: shape ${name} is missing`) + } + } + + for (const name of names) { + if (!SHAPES.includes(name)) { + refuse(`${artifact.path}: shape ${name} is not a schema-2 shape`) + } + } + } + + const reqBands = REQ_SHAPES.map((shape) => ({ + shape, + lmdb: bandOf(lmdbArtifact, shape, 'p95_us'), + postgres: bandOf(postgresArtifact, shape, 'p95_us'), + })) + const ingestBands = { + lmdb: bandOf(lmdbArtifact, INGEST_SHAPE, 'per_second'), + postgres: bandOf(postgresArtifact, INGEST_SHAPE, 'per_second'), + } + + const lines = [ + `hosts: lmdb ${describeMachine(lmdbArtifact)}; postgres ${describeMachine(postgresArtifact)}`, + ] + let passed = true + + for (const item of reqBands) { + const verdict = reqVerdict(item.lmdb, item.postgres) + passed = passed && verdict === 'within 1.5x' + lines.push( + `req ${item.shape}: lmdb p95 median ${item.lmdb.median} us (band ${item.lmdb.p10}..${item.lmdb.p90}); postgres p95 median ${item.postgres.median} us (band ${item.postgres.p10}..${item.postgres.p90}); ${verdict}`, + ) + } + + const ingest = ingestVerdict(ingestBands.lmdb, ingestBands.postgres) + passed = passed && ingest === 'at or above 1.0x' + lines.push( + `ingest create: lmdb ${ingestBands.lmdb.median} ops/s (band ${ingestBands.lmdb.p10}..${ingestBands.lmdb.p90}); postgres ${ingestBands.postgres.median} ops/s (band ${ingestBands.postgres.p10}..${ingestBands.postgres.p90}); ${ingest}`, + ) + lines.push(`bench-gate: ${passed ? 'PASS' : 'FAIL'}`) + + for (const line of lines) { + console.error(line) + } + + return passed ? 0 : 1 + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + console.error(`bench-gate: refused: ${detail.replace(/\s*\n\s*/g, ' ')}`) + return 2 + } +} + +if (require.main === module) { + runBenchGate().then((code) => { + process.exitCode = code + }) +} diff --git a/test/unit/scripts/bench-gate.spec.ts b/test/unit/scripts/bench-gate.spec.ts new file mode 100644 index 000000000..5860f1ffe --- /dev/null +++ b/test/unit/scripts/bench-gate.spec.ts @@ -0,0 +1,531 @@ +import { expect } from 'chai' +import { spawnSync } from 'child_process' +import fs from 'fs' +import os from 'os' +import path from 'path' + +const projectRoot = path.resolve(__dirname, '../../..') +const gatePath = path.join(projectRoot, 'src/scripts/bench-gate.ts') +const committedArtifact = 'docs/rewrite/benchmarks/lmdb-50k-seed7.json' + +type Artifact = Record +type Band = { median: number; p10: number; p90: number } +type Mutation = (artifact: Artifact) => void + +const SHAPE_NAMES = ['create_many', 'create', 'by_id', 'author_kind', 'kind_since', 'tag', 'count'] + +/** The committed artifact's `workload`, minus `repeats`, which differs by backend. */ +const WORKLOAD = { + concurrency: 1, + corpus: { + authors: 200, + content_len: 256, + created_at_anchor_unix: 1_700_000_000, + created_at_window_secs: 2_592_000, + kind_cycle: [1, 1, 1, 1, 1, 1, 1, 1, 7, 7], + tag_value_count: 20, + }, + reads: { + by_id_offset: 13, + by_id_stride: 7919, + counts: 50, + iterations: 200, + limits: { author_kind: 100, by_id: 1, kind_since: 500, tag: 100 }, + }, + writes: { create_many_batch: 500, ingest_events: 1000 }, +} + +const point = (value: number): Band => ({ median: value, p10: value, p90: value }) + +const metricBands = (p95Us: number, perSecond: number): Record => ({ + p50_us: point(p95Us), + p95_us: point(p95Us), + p99_us: point(p95Us), + per_second: point(perSecond), + rows_per_second: point(perSecond), +}) + +/** + * One base schema-2 artifact. LMDB's numbers are the pass fixture's: it is inside the 1.5x + * margin on all four REQ shapes (`tag`'s 150 against 100 is the inclusive boundary) and at 1.2x + * on ingest, while `count` and `create_many` sit far outside it to prove they are not gated. + */ +const baseArtifact = (backend: 'lmdb' | 'postgres'): Artifact => { + const lmdb = backend === 'lmdb' + + return { + schema: 2, + backend, + seed: 7, + events: 1_000_000, + event_count_read_back: 1_000_000, + workload: { ...JSON.parse(JSON.stringify(WORKLOAD)), repeats: lmdb ? 3 : 1 }, + shapes: SHAPE_NAMES.map((shape) => ({ shape, count: 1, rows: 1 })), + volatile: { + machine: { cpu_model: 'bench-host', os: 'linux', arch: 'x86_64', profile: 'release' }, + repeats: { + create_many: metricBands(lmdb ? 30_000 : 1_000, lmdb ? 1 : 1_000), + create: metricBands(lmdb ? 4_655 : 100, lmdb ? 120 : 100), + by_id: metricBands(lmdb ? 60 : 100, 37_615), + author_kind: metricBands(lmdb ? 120 : 100, 37_615), + kind_since: metricBands(lmdb ? 140 : 100, 37_615), + tag: metricBands(lmdb ? 150 : 100, 37_615), + count: metricBands(lmdb ? 10_000 : 100, 1), + read_back: metricBands(lmdb ? 20_434 : 100, 1), + }, + store: lmdb ? { data_bytes: 1, bytes_per_event: 1 } : { data_bytes: null, bytes_per_event: null }, + timings: {}, + }, + } +} + +const at = (artifact: Artifact, dotted: string): Artifact => + dotted.split('.').reduce((node, key) => node[key], artifact) + +const set = (artifact: Artifact, dotted: string, value: unknown): void => { + const keys = dotted.split('.') + const leaf = keys.pop() as string + const parent = keys.length === 0 ? artifact : at(artifact, keys.join('.')) + parent[leaf] = value +} + +const remove = (artifact: Artifact, dotted: string): void => { + const keys = dotted.split('.') + const leaf = keys.pop() as string + const parent = keys.length === 0 ? artifact : at(artifact, keys.join('.')) + delete parent[leaf] +} + +const write = (directory: string, name: string, content: Artifact | string): string => { + const file = path.join(directory, name) + fs.writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content, null, 2)) + return file +} + +const writePair = ( + directory: string, + name: string, + mutateLmdb: Mutation = () => {}, + mutatePostgres: Mutation = () => {}, +): { lmdb: string; postgres: string } => { + const lmdb = baseArtifact('lmdb') + const postgres = baseArtifact('postgres') + mutateLmdb(lmdb) + mutatePostgres(postgres) + + return { + lmdb: write(directory, `${name}-lmdb.json`, lmdb), + postgres: write(directory, `${name}-postgres.json`, postgres), + } +} + +type GateRun = { status: number | null; stdout: string; stderr: string } + +/** Spawn the gate the way a caller would; the exit code and the printed lines are the contract. */ +const runGate = (...args: string[]): GateRun => { + const result = spawnSync(process.execPath, ['-r', 'ts-node/register', gatePath, ...args], { + cwd: projectRoot, + encoding: 'utf-8', + timeout: 30_000, + }) + + return { status: result.status, stdout: result.stdout ?? '', stderr: result.stderr ?? '' } +} + +const expectRefusal = (run: GateRun, detail: string): void => { + expect(run.stdout).to.equal('') + expect(run.status, run.stderr).to.equal(2) + expect(run.stderr).to.equal(`bench-gate: refused: ${detail}\n`) +} + +const expectVerdict = (run: GateRun, status: number, lines: string[]): void => { + expect(run.stdout).to.equal('') + expect(run.status, run.stderr).to.equal(status) + expect(run.stderr).to.equal(`${lines.join('\n')}\n`) +} + +const replaceLine = (lines: string[], prefix: string, replacement: string): string[] => + lines.map((line) => (line.startsWith(prefix) ? replacement : line)) + +const PASS_LINES = [ + 'hosts: lmdb bench-host (linux x86_64, profile release); postgres bench-host (linux x86_64, profile release)', + 'req by_id: lmdb p95 median 60 us (band 60..60); postgres p95 median 100 us (band 100..100); within 1.5x', + 'req author_kind: lmdb p95 median 120 us (band 120..120); postgres p95 median 100 us (band 100..100); within 1.5x', + 'req kind_since: lmdb p95 median 140 us (band 140..140); postgres p95 median 100 us (band 100..100); within 1.5x', + 'req tag: lmdb p95 median 150 us (band 150..150); postgres p95 median 100 us (band 100..100); within 1.5x', + 'ingest create: lmdb 120 ops/s (band 120..120); postgres 100 ops/s (band 100..100); at or above 1.0x', + 'bench-gate: PASS', +] + +describe('bench-gate (src/scripts/bench-gate.ts)', function () { + this.timeout(30_000) + + let directory: string + + before(function () { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'bench-gate-')) + }) + + after(function () { + fs.rmSync(directory, { recursive: true, force: true }) + }) + + it('refuses zero arguments', () => { + expectRefusal(runGate(), 'expected exactly two artifact paths, got 0') + }) + + it('refuses one argument', () => { + expectRefusal(runGate(path.join(directory, 'args-1.json')), 'expected exactly two artifact paths, got 1') + }) + + it('refuses three arguments', () => { + const first = path.join(directory, 'args-3-a.json') + const second = path.join(directory, 'args-3-b.json') + const third = path.join(directory, 'args-3-c.json') + + expectRefusal(runGate(first, second, third), 'expected exactly two artifact paths, got 3') + }) + + it('refuses a baseline path it cannot read', () => { + const pair = writePair(directory, 'missing-baseline') + const missing = path.join(directory, 'missing-baseline-absent.json') + + expectRefusal(runGate(pair.lmdb, missing), `cannot read ${missing}`) + }) + + it('refuses an artifact that is not JSON', () => { + const pair = writePair(directory, 'unparseable') + const broken = write(directory, 'unparseable-postgres.json', '{') + + expectRefusal(runGate(pair.lmdb, broken), `cannot parse ${broken} as JSON`) + }) + + it('refuses an artifact whose schema is not 2', () => { + const pair = writePair( + directory, + 'schema', + () => {}, + (postgres) => set(postgres, 'schema', 3), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), `${pair.postgres}: schema 3 is not supported (this gate reads schema 2)`) + }) + + it('refuses a missing band', () => { + const pair = writePair( + directory, + 'metric-missing', + () => {}, + (postgres) => remove(postgres, 'volatile.repeats.tag.p95_us'), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), `${pair.postgres}: volatile.repeats.tag.p95_us is missing`) + }) + + it('refuses a band field that is not an integer', () => { + const pair = writePair( + directory, + 'metric-string', + () => {}, + (postgres) => set(postgres, 'volatile.repeats.tag.p95_us.median', '120'), + ) + + expectRefusal( + runGate(pair.lmdb, pair.postgres), + `${pair.postgres}: volatile.repeats.tag.p95_us.median is not a non-negative integer`, + ) + }) + + it('refuses a band not ordered p10 <= median <= p90', () => { + const pair = writePair( + directory, + 'band-inverted', + () => {}, + (postgres) => set(postgres, 'volatile.repeats.tag.p95_us', { median: 120, p10: 130, p90: 140 }), + ) + + expectRefusal( + runGate(pair.lmdb, pair.postgres), + `${pair.postgres}: volatile.repeats.tag.p95_us is not ordered p10 <= median <= p90`, + ) + }) + + it('refuses a corpus the rule does not cover', () => { + const pair = writePair( + directory, + 'corpus-50000', + (lmdb) => set(lmdb, 'events', 50_000), + (postgres) => set(postgres, 'events', 50_000), + ) + + expectRefusal( + runGate(pair.lmdb, pair.postgres), + `${pair.lmdb}: events 50000 is not a corpus the rule covers (covered: 1000000, 10000000)`, + ) + }) + + it('refuses two artifacts at different corpora', () => { + const pair = writePair( + directory, + 'corpus-mismatch', + () => {}, + (postgres) => set(postgres, 'events', 10_000_000), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), 'artifacts name different corpora: 1000000 and 10000000') + }) + + it('refuses two artifacts at different seeds', () => { + const pair = writePair( + directory, + 'seed', + () => {}, + (postgres) => set(postgres, 'seed', 8), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), 'artifacts name different seeds: 7 and 8') + }) + + it('refuses two artifacts of one backend', () => { + const pair = writePair( + directory, + 'backend-same', + () => {}, + (postgres) => set(postgres, 'backend', 'lmdb'), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), 'expected one lmdb and one postgres artifact, got lmdb and lmdb') + }) + + it('refuses an unknown backend', () => { + const pair = writePair( + directory, + 'backend-unknown', + () => {}, + (postgres) => set(postgres, 'backend', 'sqlite'), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), 'expected one lmdb and one postgres artifact, got lmdb and sqlite') + }) + + it('refuses a workload that differs', () => { + const pair = writePair( + directory, + 'workload', + () => {}, + (postgres) => set(postgres, 'workload.reads.limits.tag', 50), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), 'workload.reads.limits.tag differs: 100 and 50') + }) + + it('refuses a profile difference', () => { + const pair = writePair( + directory, + 'profile', + () => {}, + (postgres) => set(postgres, 'volatile.machine.profile', 'debug'), + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), 'volatile.machine.profile differs: "release" and "debug"') + }) + + it('refuses a shape present in one artifact only', () => { + const pair = writePair( + directory, + 'shape-missing', + () => {}, + (postgres) => { + postgres.shapes = (postgres.shapes as Artifact[]).filter((row) => row.shape !== 'count') + }, + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), `${pair.postgres}: shape count is missing`) + }) + + it('passes a comparable pair, reading the roles from backend', () => { + const pair = writePair(directory, 'pass') + + expectVerdict(runGate(pair.postgres, pair.lmdb), 0, PASS_LINES) + }) + + it('passes when a non-gated band differs wildly', () => { + const pair = writePair( + directory, + 'pass-ignores-count', + (lmdb) => set(lmdb, 'volatile.repeats.read_back.p95_us', { median: 500_000, p10: 1, p90: 999_999 }), + (postgres) => set(postgres, 'volatile.repeats.read_back.p95_us', point(1)), + ) + + const run = runGate(pair.lmdb, pair.postgres) + + expectVerdict(run, 0, PASS_LINES) + expect(run.stderr).to.not.match(/count|create_many|read_back/) + }) + + it('fails a p95 outside the margin on one shape', () => { + const pair = writePair( + directory, + 'p95-fail', + (lmdb) => { + set(lmdb, 'volatile.repeats.tag.p95_us', point(151)) + set(lmdb, 'volatile.repeats.count.p95_us', point(100)) + }, + ) + + const expected = replaceLine( + replaceLine( + PASS_LINES, + 'req tag:', + 'req tag: lmdb p95 median 151 us (band 151..151); postgres p95 median 100 us (band 100..100); outside 1.5x', + ), + 'bench-gate:', + 'bench-gate: FAIL', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 1, expected) + }) + + it('fails a slow ingest even when the bulk load is fast', () => { + const pair = writePair( + directory, + 'ingest-fail', + (lmdb) => { + set(lmdb, 'volatile.repeats.create.per_second', point(99)) + set(lmdb, 'volatile.repeats.create_many.per_second', point(500)) + }, + ) + + const expected = replaceLine( + replaceLine( + PASS_LINES, + 'ingest create:', + 'ingest create: lmdb 99 ops/s (band 99..99); postgres 100 ops/s (band 100..100); below 1.0x', + ), + 'bench-gate:', + 'bench-gate: FAIL', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 1, expected) + }) + + it('passes an ingest exactly at the floor', () => { + const pair = writePair( + directory, + 'ingest-equal', + (lmdb) => set(lmdb, 'volatile.repeats.create.per_second', point(100)), + ) + + const expected = replaceLine( + PASS_LINES, + 'ingest create:', + 'ingest create: lmdb 100 ops/s (band 100..100); postgres 100 ops/s (band 100..100); at or above 1.0x', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 0, expected) + }) + + it('fails a straddle on the REQ edge', () => { + const pair = writePair( + directory, + 'straddle', + (lmdb) => set(lmdb, 'volatile.repeats.by_id.p95_us', { median: 120, p10: 100, p90: 160 }), + ) + + const expected = replaceLine( + replaceLine( + PASS_LINES, + 'req by_id:', + 'req by_id: lmdb p95 median 120 us (band 100..160); postgres p95 median 100 us (band 100..100); straddle 1.5x', + ), + 'bench-gate:', + 'bench-gate: FAIL', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 1, expected) + }) + + it('fails a straddle at ten repeats', () => { + const pair = writePair( + directory, + 'straddle-10', + (lmdb) => { + set(lmdb, 'volatile.repeats.by_id.p95_us', { median: 120, p10: 100, p90: 160 }) + set(lmdb, 'workload.repeats', 10) + }, + (postgres) => set(postgres, 'workload.repeats', 10), + ) + + const expected = replaceLine( + replaceLine( + PASS_LINES, + 'req by_id:', + 'req by_id: lmdb p95 median 120 us (band 100..160); postgres p95 median 100 us (band 100..100); straddle 1.5x', + ), + 'bench-gate:', + 'bench-gate: FAIL', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 1, expected) + }) + + it('fails a straddle on the ingest edge', () => { + const pair = writePair( + directory, + 'ingest-straddle', + (lmdb) => set(lmdb, 'volatile.repeats.create.per_second', { median: 100, p10: 50, p90: 150 }), + ) + + const expected = replaceLine( + replaceLine( + PASS_LINES, + 'ingest create:', + 'ingest create: lmdb 100 ops/s (band 50..150); postgres 100 ops/s (band 100..100); straddle 1.0x', + ), + 'bench-gate:', + 'bench-gate: FAIL', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 1, expected) + }) + + it('passes a wide Postgres band whose median and edge are inside', () => { + const pair = writePair( + directory, + 'pg-band', + (lmdb) => set(lmdb, 'volatile.repeats.by_id.p95_us', point(120)), + (postgres) => { + set(postgres, 'volatile.repeats.by_id.p95_us', { median: 140, p10: 50, p90: 200 }) + set(postgres, 'workload.repeats', 3) + }, + ) + + const expected = replaceLine( + PASS_LINES, + 'req by_id:', + 'req by_id: lmdb p95 median 120 us (band 120..120); postgres p95 median 140 us (band 50..200); within 1.5x', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 0, expected) + }) + + it('refuses an LMDB artifact below the minimum repeat count', () => { + const pair = writePair( + directory, + 'repeat-below-min', + (lmdb) => { + set(lmdb, 'workload.repeats', 1) + set(lmdb, 'volatile.repeats.by_id.p95_us', point(160)) + }, + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), `${pair.lmdb}: workload.repeats 1 is below the minimum of 3`) + }) + + it('reads the committed artifact and refuses its corpus', () => { + expectRefusal( + runGate(committedArtifact, committedArtifact), + `${committedArtifact}: events 50000 is not a corpus the rule covers (covered: 1000000, 10000000)`, + ) + }) +}) From 77d81d88f6d0e81916ae6c2bf450d58635e8b9e1 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 23:52:41 -0500 Subject: [PATCH 2/4] docs(rewrite): publish the cutover gate and the rule it applies --- docs/rewrite/benchmarks.md | 80 +++++++++++++++++++++++++++++++------- 1 file changed, 65 insertions(+), 15 deletions(-) diff --git a/docs/rewrite/benchmarks.md b/docs/rewrite/benchmarks.md index 12467ed84..f34bb160c 100644 --- a/docs/rewrite/benchmarks.md +++ b/docs/rewrite/benchmarks.md @@ -136,9 +136,11 @@ rows and only `create` speaks for ingest. ### D3 The five read shapes, and the access path each reaches -Each shape is one filter through `find_by_filters`, drained to rows with `collect_records`, so -the measurement covers the whole page and not just its first batch. The LMDB planner picks the -path in `crates/nostream-storage/src/lmdb/events.rs`: +Each of the four REQ shapes — `by_id`, `author_kind`, `kind_since` and `tag` — is one filter +through `find_by_filters`, drained to rows with `collect_records`, so the measurement covers the +whole page and not just its first batch. `count` is the fifth read shape and is not one of them: +it goes through `count_by_filters`. The LMDB planner picks the path in +`crates/nostream-storage/src/lmdb/events.rs`: - `by_id` — `ids`, limit 1: the `events` key is the id, so the range runs in id order (`events.rs:1303-1316`). @@ -241,18 +243,66 @@ nor the Postgres it needs can be started here. That column, and the side-by-side gate reads, is filed as #1132 and must be run from a checkout of `origin/main` on a host with a Docker daemon. -### D8 No threshold is asserted - -This document carries evidence, not a pass/fail. The gate is #868: REQ p95 within 1.5× of the -Postgres implementation and ingest ≥ 1×, at the 1M and 10M corpora (#868). That p95 comparison -reads the band, not one run: the artifact carries `p95_us` per shape across repeats so the median -and the width are both available, and a single run's p95 inside a band as wide as `read_back`'s -above cannot decide a margin of one and a half on its own. #868's rule does not say which statistic -of the band the ratio applies to, and a band that straddles the threshold — one repeat inside the -margin, another outside it — is exactly the case that rule has to settle; this document measures -and does not decide it. The board's 50 000 events/s figure is a target tracked in #864, not a -measurement, and nothing here is compared with it. No ratio, floor or comparison against another -backend appears in this document. +### D8 The cutover gate, and the rule it applies + +The gate is `src/scripts/bench-gate.ts`, run as `pnpm run bench:gate +`. It takes two schema-2 artifacts — one `backend: "lmdb"`, one +`backend: "postgres"` — at one of the two corpora the rule covers, 1000000 or 10000000 events, and +decides #868's rule: + +- each of the four REQ read shapes — `by_id`, `author_kind`, `kind_since`, `tag` — must have its + `p95_us` band within 1.5× of the Postgres band's; +- the ingest shape, `create`, must have its `per_second` band at or above 1× the Postgres band's. + +There is no single statistic: each item is decided by two comparisons against the same bound — the median ratio, and the failing band edge (REQ p90 / ingest p10) against the same bound. For REQ +that is `2 × lmdb.median ≤ 3 × pg.median` and `2 × lmdb.p90 ≤ 3 × pg.p90`; for ingest it is +`lmdb.median ≥ pg.median` and `lmdb.p10 ≥ pg.p10`. All arithmetic is integer cross-multiplication, +so a zero Postgres rate is well defined. An item whose median is inside the margin but whose +failing edge is outside it is a straddle, and a straddle fails: the slowest repeat is not evidence +that the shape sits inside the margin. + +The edges are the band's order statistics, not named repeats. At three repeats `p10` is the fastest +repeat and `p90` the slowest; p90 is interior from ten repeats and p10 is interior from eleven, so +from ten repeats on the band is a statement over interior order statistics and the extreme repeat +is not recoverable from the artifact. The Postgres side may carry one repeat — the rig defaults to +one repeat, and CI's Postgres arm runs one — so with a one-repeat Postgres artifact only the LMDB edge is tested, because its three band fields are one value. + +A gated LMDB artifact must carry `workload.repeats >= 3`; a one- or two-repeat LMDB band is one or +two points and cannot decide a 1.5× margin. A pair whose `workload` echoes differ — apart from +`workload.repeats`, which says how often each was measured — is refused, as is a differing `seed`, +`events` or `volatile.machine.profile`. `cpu_model`, `os` and `arch` are printed on the gate's +first line and not compared: both artifacts must be produced on the same host, and the gate does +not refuse a cross-host pair because the gate does not verify it. The gate exits 0 on a pass, 1 on +a failed item and 2 with one `bench-gate: refused: ` line when it cannot decide; stdout +stays empty. The board's 50 000 events/s figure is a target tracked in #864, not a measurement, and +the gate does not compare with it. + +Until a Postgres artifact exists the gate refuses rather than passing: it never fabricates a +baseline and never falls back to the LMDB band. No Postgres artifact is committed — every artifact +in the tree is LMDB — and CI writes `/tmp/bench-postgres.json` at 2000 events with one repeat and +discards it. With one LMDB artifact and no Postgres artifact the gate can only refuse. Run against +the committed 50000-event artifact, the gate stops at the corpus check: + + $ node -r ts-node/register src/scripts/bench-gate.ts docs/rewrite/benchmarks/lmdb-50k-seed7.json docs/rewrite/benchmarks/lmdb-50k-seed7.json + bench-gate: refused: docs/rewrite/benchmarks/lmdb-50k-seed7.json: events 50000 is not a corpus the rule covers (covered: 1000000, 10000000) + +exit code 2, with nothing on stdout. Reaching that line proves the file was read, parsed and +schema-checked; the comparison itself is proved by the fixtures in +`test/unit/scripts/bench-gate.spec.ts`, which spawn the gate on synthetic artifact pairs. + +What the gate does not cover yet. The Postgres column needs #1132's host, and that host must be the +same host that produced the LMDB artifact; the 1000000 and 10000000 corpora need a host with the +disk and a quiet box. The rig refuses a corpus above `MAX_CORPUS_EVENTS = 200_000` unless +`--allow-large-corpus` is passed, and the rig defaults to one repeat, so a gated LMDB arm needs at +least `--repeats 3`, both arms need the same `--seed`, and the command is: + + cargo run --release -p nostream-storage --example bench -- --backend lmdb \ + --events 1000000 --seed 7 --repeats 3 --allow-large-corpus --verify --out /tmp/bench-lmdb-1m.json + +At the recorded 1889.8 bytes per event the 10M corpus projects to 18898000000 bytes of `data.mdb`, +which does not fit this host's available memory, so D4's warm-read premise covers 1000000 and the warm-read premise stops holding at 10M. +The gate's own covered set stays 1000000 and 10000000 regardless of the rig's local ceiling: the +ceiling is a rig guard, not the gate's rule. The artifact's `schema` integer is its layout version: the artifact this document reads — the committed `docs/rewrite/benchmarks/lmdb-50k-seed7.json` — is schema 2, and a field whose meaning From 1aba7910f8e5afbd377d2d6c4f409cc63bff76fc Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Mon, 30 Nov 2026 00:28:55 -0500 Subject: [PATCH 3/4] fix(bench): refuse incomplete runs, tolerate a null cpu_model, and name the rule's authority --- docs/rewrite/benchmarks.md | 37 ++- src/scripts/bench-gate.ts | 149 +++++++++--- test/unit/scripts/bench-gate-units.spec.ts | 268 +++++++++++++++++++++ test/unit/scripts/bench-gate.spec.ts | 71 ++++++ 4 files changed, 479 insertions(+), 46 deletions(-) create mode 100644 test/unit/scripts/bench-gate-units.spec.ts diff --git a/docs/rewrite/benchmarks.md b/docs/rewrite/benchmarks.md index f34bb160c..408a57dbe 100644 --- a/docs/rewrite/benchmarks.md +++ b/docs/rewrite/benchmarks.md @@ -254,6 +254,12 @@ decides #868's rule: `p95_us` band within 1.5× of the Postgres band's; - the ingest shape, `create`, must have its `per_second` band at or above 1× the Postgres band's. +The rule's definition is the named constants at the top of `src/scripts/bench-gate.ts` — +`REQ_MARGIN_NUM`/`REQ_MARGIN_DEN`, `COVERED_CORPORA`, `MIN_LMDB_REPEATS` and +`MIN_POSTGRES_REPEATS` — and this section is their reading, as D9 is the reading of the rig's +workload constants: a number changes in the script first, and in this section with it, so no value +here has a second source. The script's own header says the same from the other side. + There is no single statistic: each item is decided by two comparisons against the same bound — the median ratio, and the failing band edge (REQ p90 / ingest p10) against the same bound. For REQ that is `2 × lmdb.median ≤ 3 × pg.median` and `2 × lmdb.p90 ≤ 3 × pg.p90`; for ingest it is `lmdb.median ≥ pg.median` and `lmdb.p10 ≥ pg.p10`. All arithmetic is integer cross-multiplication, @@ -261,21 +267,30 @@ so a zero Postgres rate is well defined. An item whose median is inside the marg failing edge is outside it is a straddle, and a straddle fails: the slowest repeat is not evidence that the shape sits inside the margin. -The edges are the band's order statistics, not named repeats. At three repeats `p10` is the fastest -repeat and `p90` the slowest; p90 is interior from ten repeats and p10 is interior from eleven, so +The edges are the band's order statistics, not named repeats. `p10` is the band's smallest value and +`p90` its largest, and what that means depends on the metric: for a latency band the smallest value +is the fastest repeat and the largest the slowest, while for a rate band it is the other way round — +`p10` is the slowest rate and `p90` the fastest. The gate therefore tests only the edge that can +fail its bound: `p90` for the four REQ latency bands, where a slower repeat is worse against a +ceiling, and `p10` for the ingest rate band, where a slower repeat is worse against a floor. p90 is interior from ten repeats and p10 is interior from eleven, so from ten repeats on the band is a statement over interior order statistics and the extreme repeat is not recoverable from the artifact. The Postgres side may carry one repeat — the rig defaults to one repeat, and CI's Postgres arm runs one — so with a one-repeat Postgres artifact only the LMDB edge is tested, because its three band fields are one value. -A gated LMDB artifact must carry `workload.repeats >= 3`; a one- or two-repeat LMDB band is one or -two points and cannot decide a 1.5× margin. A pair whose `workload` echoes differ — apart from -`workload.repeats`, which says how often each was measured — is refused, as is a differing `seed`, -`events` or `volatile.machine.profile`. `cpu_model`, `os` and `arch` are printed on the gate's -first line and not compared: both artifacts must be produced on the same host, and the gate does -not refuse a cross-host pair because the gate does not verify it. The gate exits 0 on a pass, 1 on -a failed item and 2 with one `bench-gate: refused: ` line when it cannot decide; stdout -stays empty. The board's 50 000 events/s figure is a target tracked in #864, not a measurement, and -the gate does not compare with it. +A gated LMDB artifact must carry `workload.repeats >= 3`, and the Postgres artifact at least 1; a +one- or two-repeat LMDB band is one or two points and cannot decide a 1.5× margin. A pair whose +`workload` echoes differ — apart from `workload.repeats`, which says how often each was measured — +is refused, as is a differing `seed`, `events` or `volatile.machine.profile`. An artifact that +records less work than its own corpus declares is refused before any band is compared: its +`event_count_read_back` must equal its `events`, and each of the four REQ shapes and `create` must +have read non-zero rows — the rig writes the artifact before `verify()` runs, so a run whose reads +failed still leaves a file on disk. `cpu_model`, `os` and `arch` are printed on the gate's first +line and not compared — a null `cpu_model`, which is what a host with no `/proc` writes, prints as +`unknown` — because both artifacts must be produced on the same host, and the gate does not refuse +a cross-host pair because the gate does not verify it. The gate exits 0 on a pass, 1 on a failed +item and 2 with one `bench-gate: refused: ` line when it cannot decide; stdout stays empty. +The board's 50 000 events/s figure is a target tracked in #864, not a measurement, and the gate +does not compare with it. Until a Postgres artifact exists the gate refuses rather than passing: it never fabricates a baseline and never falls back to the LMDB band. No Postgres artifact is committed — every artifact diff --git a/src/scripts/bench-gate.ts b/src/scripts/bench-gate.ts index 3d78bdc07..bc550f73e 100644 --- a/src/scripts/bench-gate.ts +++ b/src/scripts/bench-gate.ts @@ -9,6 +9,13 @@ import fs from 'node:fs' * above 1x the Postgres band's, tested at its median and at its failing edge (`p10`). An item * whose median is inside the bound but whose failing edge is outside it is a straddle, and a * straddle fails: the worst repeat is not evidence that the shape sits inside the margin. + * + * An artifact that records less work than its own corpus declares — a read-back count short of its + * `events`, or a gated shape with zero rows — is refused before any band is compared: the rig + * writes the artifact before `verify()` runs, so a failed run still leaves a file on disk. + * + * This file's named constants are the rule's definition; `docs/rewrite/benchmarks.md` D8 is its + * reading, and points back here for the numbers. */ /** The artifact layout version this gate reads (`ARTIFACT_SCHEMA`, bench.rs:87). */ @@ -27,26 +34,29 @@ const INGEST_SHAPE = 'create' const REQ_MARGIN_DEN = 2 const REQ_MARGIN_NUM = 3 -/** Ingest floor: `lmdb >= 1 x postgres`, as integer cross-multiplication. */ -const INGEST_FLOOR = 1 - /** A gated LMDB band needs three repeats: one or two is a point or a pair, never a straddle. */ const MIN_LMDB_REPEATS = 3 +/** A Postgres artifact may carry one repeat (CI's run does); zero is not a measurement. */ +const MIN_POSTGRES_REPEATS = 1 + /** The rig's seven shapes, in its fixed order (`SHAPES`, bench.rs:108-116). */ const SHAPES = ['create_many', 'create', 'by_id', 'author_kind', 'kind_since', 'tag', 'count'] /** The three fields of a band, in the order the artifact writes them. */ const BAND_FIELDS = ['median', 'p10', 'p90'] -/** The `machine` fields the gate requires; only `profile` is compared. */ +/** The `machine` fields the gate requires; `cpu_model` may be null, and only `profile` is compared. */ const MACHINE_FIELDS = ['cpu_model', 'os', 'arch', 'profile'] -type Band = { median: number; p10: number; p90: number } +/** The `machine` fields that must be strings: a null `cpu_model` means `/proc` is absent. */ +const MACHINE_STRING_FIELDS = ['os', 'arch', 'profile'] + +export type Band = { median: number; p10: number; p90: number } -type Artifact = { path: string; document: Record } +export type Artifact = { path: string; document: Record } -type Difference = { path: string; left: unknown; right: unknown } +export type Difference = { path: string; left: unknown; right: unknown } const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value) @@ -58,6 +68,9 @@ const refuse = (detail: string): never => { const renderJson = (value: unknown): string => (value === undefined ? 'absent' : JSON.stringify(value)) +/** A value as a refusal names it: a string raw, `absent` when the key is missing. */ +const renderValue = (value: unknown): string => (value === undefined ? 'absent' : String(value)) + /** * Exactly two positional arguments, each taken as a path whatever it starts with. Neither order * nor any flag assigns a role: each artifact's `backend` field does. @@ -97,6 +110,21 @@ const assertSchema = (artifact: Artifact): void => { } } +/** + * Exactly one `lmdb` and one `postgres` artifact. Argument order assigns no role, so the pair is + * returned by backend; any other pair — two of a kind, or a third value — is refused by name. + */ +export const resolveRoles = (first: Artifact, second: Artifact): { lmdb: Artifact; postgres: Artifact } => { + const backends = [first.document.backend, second.document.backend] + const lmdbArtifacts = [first, second].filter((artifact) => artifact.document.backend === 'lmdb') + const postgresArtifacts = [first, second].filter((artifact) => artifact.document.backend === 'postgres') + if (lmdbArtifacts.length !== 1 || postgresArtifacts.length !== 1) { + refuse(`expected one lmdb and one postgres artifact, got ${renderValue(backends[0])} and ${renderValue(backends[1])}`) + } + + return { lmdb: lmdbArtifacts[0], postgres: postgresArtifacts[0] } +} + const deepEqual = (left: unknown, right: unknown): boolean => { if (left === right) { return true @@ -146,6 +174,10 @@ const findDifference = (left: unknown, right: unknown, path: string, topLevel = return deepEqual(left, right) ? undefined : { path, left, right } } +/** The first `workload` difference, with `workload.repeats` excluded: it is a measurement count. */ +export const findWorkloadDifference = (left: unknown, right: unknown): Difference | undefined => + findDifference(left, right, 'workload', true) + const workloadOf = (artifact: Artifact): Record => { if (!isRecord(artifact.document.workload)) { return refuse(`${artifact.path}: workload is not a JSON object`) @@ -154,6 +186,31 @@ const workloadOf = (artifact: Artifact): Record => { return artifact.document.workload } +/** + * The repeat counts the rule can read: at least `MIN_LMDB_REPEATS` on the LMDB side, whose band is + * what decides the margin, and at least `MIN_POSTGRES_REPEATS` on the Postgres side, whose band may + * be the single repeat CI's run takes. + */ +export const assertRepeatCounts = (lmdbArtifact: Artifact, postgresArtifact: Artifact): void => { + const lmdbRepeats = workloadOf(lmdbArtifact).repeats + if (!Number.isSafeInteger(lmdbRepeats)) { + refuse(`${lmdbArtifact.path}: workload.repeats is not a non-negative integer`) + } + + if (lmdbRepeats < MIN_LMDB_REPEATS) { + refuse(`${lmdbArtifact.path}: workload.repeats ${lmdbRepeats} is below the minimum of 3`) + } + + const postgresRepeats = workloadOf(postgresArtifact).repeats + if (!Number.isSafeInteger(postgresRepeats)) { + refuse(`${postgresArtifact.path}: workload.repeats is not a non-negative integer`) + } + + if (postgresRepeats < MIN_POSTGRES_REPEATS) { + refuse(`${postgresArtifact.path}: workload.repeats ${postgresRepeats} is below the minimum of 1`) + } +} + const machineOf = (artifact: Artifact): Record => { const { volatile } = artifact.document if (!isRecord(volatile) || !isRecord(volatile.machine)) { @@ -163,23 +220,49 @@ const machineOf = (artifact: Artifact): Record => { return volatile.machine } -const shapeNamesOf = (artifact: Artifact): string[] => { +const shapeRowsOf = (artifact: Artifact): Record[] => { const rows = artifact.document.shapes if (!Array.isArray(rows)) { return refuse(`${artifact.path}: shapes is not a JSON array`) } - return rows.map((row) => { + return rows +} + +const shapeNamesOf = (artifact: Artifact): string[] => + shapeRowsOf(artifact).map((row) => { if (!isRecord(row) || typeof row.shape !== 'string') { return refuse(`${artifact.path}: shapes carries a row without a shape name`) } return row.shape }) + +/** + * Refuse an artifact that records less work than its own corpus declares. The rig writes the + * artifact before `verify()` runs, so a failed run still leaves a file on disk: the read-back count + * and the gated shapes' row counts are what tell a finished run from a failed one. + */ +export const assertRunCompleted = (artifact: Artifact): void => { + const { event_count_read_back: readBack, events } = artifact.document + if (readBack !== events) { + refuse(`${artifact.path}: event_count_read_back ${renderJson(readBack)} does not match events ${renderJson(events)}`) + } + + for (const name of [...REQ_SHAPES, INGEST_SHAPE]) { + const rows = shapeRowsOf(artifact).find((row) => row.shape === name)?.rows + if (!Number.isSafeInteger(rows)) { + refuse(`${artifact.path}: shape ${name} rows is not a non-negative integer`) + } + + if (rows === 0) { + refuse(`${artifact.path}: shape ${name} returned 0 rows`) + } + } } /** One band, refused unless it is three non-negative safe integers ordered `p10 <= median <= p90`. */ -const bandOf = (artifact: Artifact, shape: string, metric: string): Band => { +export const bandOf = (artifact: Artifact, shape: string, metric: string): Band => { const repeats = artifact.document.volatile?.repeats const metrics = isRecord(repeats) ? repeats[shape] : undefined const band = isRecord(metrics) ? metrics[metric] : undefined @@ -200,7 +283,7 @@ const bandOf = (artifact: Artifact, shape: string, metric: string): Band => { return { median: band.median, p10: band.p10, p90: band.p90 } } -const reqVerdict = (lmdb: Band, postgres: Band): string => { +export const reqVerdict = (lmdb: Band, postgres: Band): string => { const medianWithin = lmdb.median * REQ_MARGIN_DEN <= postgres.median * REQ_MARGIN_NUM const edgeWithin = lmdb.p90 * REQ_MARGIN_DEN <= postgres.p90 * REQ_MARGIN_NUM @@ -211,9 +294,10 @@ const reqVerdict = (lmdb: Band, postgres: Band): string => { return medianWithin ? 'straddle 1.5x' : 'outside 1.5x' } -const ingestVerdict = (lmdb: Band, postgres: Band): string => { - const medianAtOrAbove = lmdb.median * INGEST_FLOOR >= postgres.median * INGEST_FLOOR - const edgeAtOrAbove = lmdb.p10 * INGEST_FLOOR >= postgres.p10 * INGEST_FLOOR +export const ingestVerdict = (lmdb: Band, postgres: Band): string => { + // #868's floor is 1x, so each comparison is against the Postgres value itself. + const medianAtOrAbove = lmdb.median >= postgres.median + const edgeAtOrAbove = lmdb.p10 >= postgres.p10 if (medianAtOrAbove && edgeAtOrAbove) { return 'at or above 1.0x' @@ -224,7 +308,8 @@ const ingestVerdict = (lmdb: Band, postgres: Band): string => { const describeMachine = (artifact: Artifact): string => { const machine = machineOf(artifact) - return `${machine.cpu_model} (${machine.os} ${machine.arch}, profile ${machine.profile})` + const cpu = machine.cpu_model ?? 'unknown' + return `${cpu} (${machine.os} ${machine.arch}, profile ${machine.profile})` } export const runBenchGate = async (argv: string[] = process.argv.slice(2)): Promise => { @@ -259,27 +344,10 @@ export const runBenchGate = async (argv: string[] = process.argv.slice(2)): Prom refuse(`artifacts name different seeds: ${first.document.seed} and ${second.document.seed}`) } - const backends = artifacts.map((artifact) => artifact.document.backend) - const lmdbArtifacts = artifacts.filter((artifact) => artifact.document.backend === 'lmdb') - const postgresArtifacts = artifacts.filter((artifact) => artifact.document.backend === 'postgres') - if (lmdbArtifacts.length !== 1 || postgresArtifacts.length !== 1) { - refuse(`expected one lmdb and one postgres artifact, got ${backends[0]} and ${backends[1]}`) - } + const { lmdb: lmdbArtifact, postgres: postgresArtifact } = resolveRoles(first, second) + assertRepeatCounts(lmdbArtifact, postgresArtifact) - const [lmdbArtifact] = lmdbArtifacts - const [postgresArtifact] = postgresArtifacts - - const lmdbWorkload = workloadOf(lmdbArtifact) - const repeats = lmdbWorkload.repeats - if (!Number.isSafeInteger(repeats)) { - refuse(`${lmdbArtifact.path}: workload.repeats is not a non-negative integer`) - } - - if (repeats < MIN_LMDB_REPEATS) { - refuse(`${lmdbArtifact.path}: workload.repeats ${repeats} is below the minimum of 3`) - } - - const difference = findDifference(workloadOf(first), workloadOf(second), 'workload', true) + const difference = findWorkloadDifference(workloadOf(first), workloadOf(second)) if (difference !== undefined) { refuse(`${difference.path} differs: ${renderJson(difference.left)} and ${renderJson(difference.right)}`) } @@ -290,7 +358,14 @@ export const runBenchGate = async (argv: string[] = process.argv.slice(2)): Prom if (!(field in machine)) { refuse(`${artifact.path}: volatile.machine.${field} is missing`) } + } + // The rig writes `cpu_model` as `Option`, null where `/proc` is absent. + if (machine.cpu_model !== null && typeof machine.cpu_model !== 'string') { + refuse(`${artifact.path}: volatile.machine.cpu_model is not a string or null`) + } + + for (const field of MACHINE_STRING_FIELDS) { if (typeof machine[field] !== 'string') { refuse(`${artifact.path}: volatile.machine.${field} is not a string`) } @@ -316,6 +391,10 @@ export const runBenchGate = async (argv: string[] = process.argv.slice(2)): Prom } } + for (const artifact of artifacts) { + assertRunCompleted(artifact) + } + const reqBands = REQ_SHAPES.map((shape) => ({ shape, lmdb: bandOf(lmdbArtifact, shape, 'p95_us'), diff --git a/test/unit/scripts/bench-gate-units.spec.ts b/test/unit/scripts/bench-gate-units.spec.ts new file mode 100644 index 000000000..c393badba --- /dev/null +++ b/test/unit/scripts/bench-gate-units.spec.ts @@ -0,0 +1,268 @@ +import { expect } from 'chai' + +import { + type Artifact, + type Band, + assertRepeatCounts, + assertRunCompleted, + bandOf, + findWorkloadDifference, + ingestVerdict, + parseGateArgs, + reqVerdict, + resolveRoles, +} from '../../../src/scripts/bench-gate' + +/** + * The gate's pure functions, exercised in process. The spawn cases in + * `bench-gate.spec.ts` are the contract for exit status and exact stderr; these + * pin the arithmetic and the refusals they build on, which a spawn cannot show + * one branch at a time. + */ + +const artifactOf = (document: Record): Artifact => ({ path: 'artifact.json', document }) + +const shapeRows = (overrides: Record = {}): Array<{ shape: string; rows: unknown }> => + ['create_many', 'create', 'by_id', 'author_kind', 'kind_since', 'tag', 'count'].map((shape) => ({ + shape, + rows: overrides[shape] ?? 1, + })) + +const point = (value: number): Band => ({ median: value, p10: value, p90: value }) + +const withBand = (shape: string, metric: string, band: unknown): Artifact => + artifactOf({ volatile: { repeats: { [shape]: { [metric]: band } } } }) + +describe('parseGateArgs', () => { + it('takes two arguments as paths, whatever they start with', () => { + expect(parseGateArgs(['--lmdb.json', 'postgres.json'])).to.deep.equal(['--lmdb.json', 'postgres.json']) + }) + + it('refuses zero arguments', () => { + expect(() => parseGateArgs([])).to.throw('expected exactly two artifact paths, got 0') + }) + + it('refuses one argument', () => { + expect(() => parseGateArgs(['only.json'])).to.throw('expected exactly two artifact paths, got 1') + }) + + it('refuses three arguments', () => { + expect(() => parseGateArgs(['a.json', 'b.json', 'c.json'])).to.throw( + 'expected exactly two artifact paths, got 3', + ) + }) +}) + +describe('resolveRoles', () => { + it('reads the roles from backend, not from argument order', () => { + const lmdb = artifactOf({ backend: 'lmdb' }) + const postgres = artifactOf({ backend: 'postgres' }) + const roles = resolveRoles(postgres, lmdb) + + expect(roles.lmdb).to.equal(lmdb) + expect(roles.postgres).to.equal(postgres) + }) + + it('refuses two artifacts of one backend', () => { + const first = artifactOf({ backend: 'lmdb' }) + const second = artifactOf({ backend: 'lmdb' }) + + expect(() => resolveRoles(first, second)).to.throw( + 'expected one lmdb and one postgres artifact, got lmdb and lmdb', + ) + }) + + it('refuses an unknown backend by name', () => { + const first = artifactOf({ backend: 'lmdb' }) + const second = artifactOf({ backend: 'sqlite' }) + + expect(() => resolveRoles(first, second)).to.throw( + 'expected one lmdb and one postgres artifact, got lmdb and sqlite', + ) + }) + + it('names a missing backend as absent rather than undefined', () => { + const first = artifactOf({ backend: 'lmdb' }) + const second = artifactOf({}) + + expect(() => resolveRoles(first, second)).to.throw( + 'expected one lmdb and one postgres artifact, got lmdb and absent', + ) + }) +}) + +describe('assertRepeatCounts', () => { + const withRepeats = (repeats: unknown): Artifact => artifactOf({ workload: { repeats } }) + + it('accepts three LMDB repeats against one Postgres repeat', () => { + expect(() => assertRepeatCounts(withRepeats(3), withRepeats(1))).to.not.throw() + }) + + it('refuses a one-repeat LMDB artifact', () => { + expect(() => assertRepeatCounts(withRepeats(1), withRepeats(1))).to.throw( + 'artifact.json: workload.repeats 1 is below the minimum of 3', + ) + }) + + it('refuses a zero-repeat Postgres artifact', () => { + expect(() => assertRepeatCounts(withRepeats(3), withRepeats(0))).to.throw( + 'artifact.json: workload.repeats 0 is below the minimum of 1', + ) + }) + + it('refuses an LMDB repeat count that is not an integer', () => { + expect(() => assertRepeatCounts(withRepeats('3'), withRepeats(1))).to.throw( + 'artifact.json: workload.repeats is not a non-negative integer', + ) + }) + + it('refuses a Postgres repeat count that is missing', () => { + expect(() => assertRepeatCounts(withRepeats(3), artifactOf({ workload: {} }))).to.throw( + 'artifact.json: workload.repeats is not a non-negative integer', + ) + }) +}) + +describe('assertRunCompleted', () => { + const complete = (overrides: Record = {}): Artifact => + artifactOf({ + events: 1_000_000, + event_count_read_back: 1_000_000, + shapes: shapeRows(), + ...overrides, + }) + + it('accepts an artifact whose read-back and gated rows agree with its corpus', () => { + expect(() => assertRunCompleted(complete())).to.not.throw() + }) + + it('refuses a read-back count short of the corpus', () => { + expect(() => assertRunCompleted(complete({ event_count_read_back: 999_000 }))).to.throw( + 'artifact.json: event_count_read_back 999000 does not match events 1000000', + ) + }) + + it('refuses a missing read-back count as absent', () => { + expect(() => assertRunCompleted(complete({ event_count_read_back: undefined }))).to.throw( + 'artifact.json: event_count_read_back absent does not match events 1000000', + ) + }) + + it('refuses a gated REQ shape with zero rows', () => { + expect(() => assertRunCompleted(complete({ shapes: shapeRows({ tag: 0 }) }))).to.throw( + 'artifact.json: shape tag returned 0 rows', + ) + }) + + it('refuses the ingest shape with zero rows', () => { + expect(() => assertRunCompleted(complete({ shapes: shapeRows({ create: 0 }) }))).to.throw( + 'artifact.json: shape create returned 0 rows', + ) + }) + + it('refuses a gated shape whose row count is not an integer', () => { + expect(() => assertRunCompleted(complete({ shapes: shapeRows({ by_id: '200' }) }))).to.throw( + 'artifact.json: shape by_id rows is not a non-negative integer', + ) + }) + + it('does not gate a shape outside the five, such as count', () => { + expect(() => assertRunCompleted(complete({ shapes: shapeRows({ count: 0 }) }))).to.not.throw() + }) +}) + +describe('bandOf', () => { + it('reads a band that is ordered', () => { + expect(bandOf(withBand('tag', 'p95_us', { median: 120, p10: 100, p90: 160 }), 'tag', 'p95_us')).to.deep.equal({ + median: 120, + p10: 100, + p90: 160, + }) + }) + + it('refuses a missing metric', () => { + expect(() => bandOf(artifactOf({}), 'tag', 'p95_us')).to.throw( + 'artifact.json: volatile.repeats.tag.p95_us is missing', + ) + }) + + it('refuses a field that is not a non-negative integer', () => { + expect(() => bandOf(withBand('tag', 'p95_us', { median: '120', p10: 100, p90: 160 }), 'tag', 'p95_us')).to.throw( + 'artifact.json: volatile.repeats.tag.p95_us.median is not a non-negative integer', + ) + }) + + it('refuses a band whose p10 is above its median', () => { + expect(() => bandOf(withBand('tag', 'p95_us', { median: 120, p10: 130, p90: 140 }), 'tag', 'p95_us')).to.throw( + 'artifact.json: volatile.repeats.tag.p95_us is not ordered p10 <= median <= p90', + ) + }) +}) + +describe('reqVerdict', () => { + it('is within at exactly 1.5x', () => { + expect(reqVerdict(point(150), point(100))).to.equal('within 1.5x') + }) + + it('is outside one microsecond above the margin', () => { + expect(reqVerdict(point(151), point(100))).to.equal('outside 1.5x') + }) + + it('is a straddle when the median holds and p90 does not', () => { + expect(reqVerdict({ median: 120, p10: 100, p90: 160 }, point(100))).to.equal('straddle 1.5x') + }) + + it('compares the Postgres p90, not its p10', () => { + expect(reqVerdict(point(120), { median: 140, p10: 50, p90: 200 })).to.equal('within 1.5x') + }) +}) + +describe('ingestVerdict', () => { + it('is at or above at exactly the floor', () => { + expect(ingestVerdict(point(100), point(100))).to.equal('at or above 1.0x') + }) + + it('is below one operation per second under the floor', () => { + expect(ingestVerdict(point(99), point(100))).to.equal('below 1.0x') + }) + + it('is a straddle when the median holds and p10 does not', () => { + expect(ingestVerdict({ median: 100, p10: 50, p90: 150 }, point(100))).to.equal('straddle 1.0x') + }) +}) + +describe('findWorkloadDifference', () => { + it('returns undefined for equal echoes', () => { + expect(findWorkloadDifference({ corpus: { authors: 200 } }, { corpus: { authors: 200 } })).to.equal(undefined) + }) + + it('ignores workload.repeats', () => { + expect(findWorkloadDifference({ repeats: 3, corpus: {} }, { repeats: 1, corpus: {} })).to.equal(undefined) + }) + + it('names the first differing leaf by its dotted path', () => { + const left = { reads: { limits: { tag: 100 } } } + const right = { reads: { limits: { tag: 50 } } } + + expect(findWorkloadDifference(left, right)).to.deep.equal({ + path: 'workload.reads.limits.tag', + left: 100, + right: 50, + }) + }) + + it('names a differing array by its own path, order significant', () => { + const left = { corpus: { kind_cycle: [1, 1, 7] } } + const right = { corpus: { kind_cycle: [1, 7, 1] } } + + expect(findWorkloadDifference(left, right)?.path).to.equal('workload.corpus.kind_cycle') + }) + + it('names a key present on one side only', () => { + const difference = findWorkloadDifference({ writes: { ingest_events: 1000 } }, { writes: {} }) + + expect(difference?.path).to.equal('workload.writes.ingest_events') + expect(difference?.left).to.equal(1000) + expect(difference?.right).to.equal(undefined) + }) +}) diff --git a/test/unit/scripts/bench-gate.spec.ts b/test/unit/scripts/bench-gate.spec.ts index 5860f1ffe..2588944c2 100644 --- a/test/unit/scripts/bench-gate.spec.ts +++ b/test/unit/scripts/bench-gate.spec.ts @@ -343,6 +343,77 @@ describe('bench-gate (src/scripts/bench-gate.ts)', function () { expectRefusal(runGate(pair.lmdb, pair.postgres), `${pair.postgres}: shape count is missing`) }) + it('refuses an LMDB artifact whose read-back count is short of its corpus', () => { + const pair = writePair( + directory, + 'incomplete-readback-lmdb', + (lmdb) => set(lmdb, 'event_count_read_back', 999_000), + ) + + expectRefusal( + runGate(pair.lmdb, pair.postgres), + `${pair.lmdb}: event_count_read_back 999000 does not match events 1000000`, + ) + }) + + it('refuses a Postgres artifact whose read-back count is short of its corpus', () => { + const pair = writePair( + directory, + 'incomplete-readback-postgres', + () => {}, + (postgres) => set(postgres, 'event_count_read_back', 999_000), + ) + + expectRefusal( + runGate(pair.lmdb, pair.postgres), + `${pair.postgres}: event_count_read_back 999000 does not match events 1000000`, + ) + }) + + it('refuses an artifact whose REQ shape returned zero rows', () => { + const pair = writePair( + directory, + 'empty-reads-shape', + (lmdb) => { + const row = (lmdb.shapes as Artifact[]).find((shape) => shape.shape === 'tag') as Artifact + row.rows = 0 + }, + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), `${pair.lmdb}: shape tag returned 0 rows`) + }) + + it('refuses an artifact whose ingest shape returned zero rows', () => { + const pair = writePair( + directory, + 'empty-reads-ingest', + () => {}, + (postgres) => { + const row = (postgres.shapes as Artifact[]).find((shape) => shape.shape === 'create') as Artifact + row.rows = 0 + }, + ) + + expectRefusal(runGate(pair.lmdb, pair.postgres), `${pair.postgres}: shape create returned 0 rows`) + }) + + it('passes when cpu_model is null on both hosts', () => { + const pair = writePair( + directory, + 'cpu-model-null', + (lmdb) => set(lmdb, 'volatile.machine.cpu_model', null), + (postgres) => set(postgres, 'volatile.machine.cpu_model', null), + ) + + const expected = replaceLine( + PASS_LINES, + 'hosts:', + 'hosts: lmdb unknown (linux x86_64, profile release); postgres unknown (linux x86_64, profile release)', + ) + + expectVerdict(runGate(pair.lmdb, pair.postgres), 0, expected) + }) + it('passes a comparable pair, reading the roles from backend', () => { const pair = writePair(directory, 'pass') From e4a4731baf90073c97ecce832b7e32cb99e6ba00 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Mon, 30 Nov 2026 00:40:43 -0500 Subject: [PATCH 4/4] fix(bench): refuse a negative row count alongside a non-integer --- src/scripts/bench-gate.ts | 2 +- test/unit/scripts/bench-gate-units.spec.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/scripts/bench-gate.ts b/src/scripts/bench-gate.ts index bc550f73e..6e046e01c 100644 --- a/src/scripts/bench-gate.ts +++ b/src/scripts/bench-gate.ts @@ -251,7 +251,7 @@ export const assertRunCompleted = (artifact: Artifact): void => { for (const name of [...REQ_SHAPES, INGEST_SHAPE]) { const rows = shapeRowsOf(artifact).find((row) => row.shape === name)?.rows - if (!Number.isSafeInteger(rows)) { + if (!Number.isSafeInteger(rows) || rows < 0) { refuse(`${artifact.path}: shape ${name} rows is not a non-negative integer`) } diff --git a/test/unit/scripts/bench-gate-units.spec.ts b/test/unit/scripts/bench-gate-units.spec.ts index c393badba..26f26e5cd 100644 --- a/test/unit/scripts/bench-gate-units.spec.ts +++ b/test/unit/scripts/bench-gate-units.spec.ts @@ -166,6 +166,12 @@ describe('assertRunCompleted', () => { ) }) + it('refuses a gated shape whose row count is below zero', () => { + expect(() => assertRunCompleted(complete({ shapes: shapeRows({ tag: -1 }) }))).to.throw( + 'artifact.json: shape tag rows is not a non-negative integer', + ) + }) + it('does not gate a shape outside the five, such as count', () => { expect(() => assertRunCompleted(complete({ shapes: shapeRows({ count: 0 }) }))).to.not.throw() })