run.mjs

benches/minima/run.mjs

run.mjs729 lines← Benchmarks
1#!/usr/bin/env node2import assert from 'node:assert/strict';3import {createHash} from 'node:crypto';4import {appendFile, mkdir, readFile, readdir, stat, writeFile} from 'node:fs/promises';5import {dirname, join, resolve} from 'node:path';6import {fileURLToPath, pathToFileURL} from 'node:url';7import {gzipSync} from 'node:zlib';8import {createSession, inspectCanister, json, traceCall} from './measurement.mjs';9import {createWireActor, encodeWireInit} from '../../tests/pocketic/wire-client.mjs';10import {verifyBuild} from '../../tests/pocketic/verify-build.mjs';1112const HERE = dirname(fileURLToPath(import.meta.url));13const POPULATION = 100_000n, MASK64 = (1n << 64n) - 1n, SAMPLES = 32;14const VALUE_XOR = 0xd6e8_feb8_6659_fd93n;15const KINDS = ['fixed-vec', 'slot-arena', 'bitmap', 'frozen-hash', 'frozen-sorted',16  'hylix-map', 'hylix-vec', 'hylix-set', 'nyxus-map', 'prefix-sums', 'frozen-hash-set'];17const PATTERNS = ['repeat', 'neighbor', 'distant', 'missing'];18const MISSING = new Set([2, 3, 4, 5, 7, 8, 10]);19const MUTABLE = new Set([0, 1, 5, 6, 8]);20const SCANNABLE = [0, 4, 5, 6, 8];21const STARTS = Array.from({length: SAMPLES}, (_, sample) => (BigInt(sample + 1) * 7919n + 17n) % POPULATION);22const sha = bytes => createHash('sha256').update(bytes).digest('hex');23const save = (path, value) => writeFile(path, JSON.stringify(value, json, 2) + '\n', {flag: 'wx'});2425export function value(index) {26  index &= MASK64;27  return (((index << 17n) | (index >> 47n)) & MASK64) ^ VALUE_XOR;28}2930function prefixBefore(end) {31  const cycles = end / 17n, tail = end % 17n;32  return cycles * 153n + tail * (tail + 1n) / 2n;33}3435export function prefixRange(index) {36  const end = index + 4096n < POPULATION ? index + 4096n : POPULATION;37  return prefixBefore(end) - prefixBefore(index);38}3940function indices(pattern, start, count) {41  return Array.from({length: count}, (_, offset) => pattern === 0 ? start % POPULATION :42    (start + BigInt(offset) * (pattern === 1 ? 1n : 104729n)) % POPULATION);43}4445export function expected(row, start, replacements = new Map()) {46  if (row.method === 'hll_observe') return {checksum: row.newItems ? null : 0n, found: BigInt(row.count), misses: 0n};47  if (row.method === 'modify') return {checksum: modifiedValue(start), found: 1n, misses: 0n};48  if (row.method === 'scan') {49    let checksum = 0n, found = 0n;50    const begin = start % POPULATION;51    for (let index = begin; index < begin + BigInt(row.count) && index < POPULATION; index++) {52      checksum = (checksum + value(index)) & MASK64; found++;53    }54    return {checksum, found, misses: 0n};55  }56  let checksum = 0n, found = 0n, misses = 0n;57  const ids = indices(row.pattern ?? 2, start, row.count);58  for (let offset = 0; offset < ids.length; offset++) {59    const index = ids[offset];60    const missing = row.method === 'bloom_lookup'61      ? (start + BigInt(offset) * 37n) % 100n < BigInt(row.missPercent)62      : row.pattern === 3;63    if (missing) {misses++; continue;}64    const item = row.method === 'bloom_lookup' ? value(index) : row.kind === 9 ? prefixRange(index) :65      row.kind === 2 || row.kind === 7 || row.kind === 10 ? 1n :66      MUTABLE.has(row.kind) && replacements.has(index) ? replacements.get(index) : value(index);67    checksum = (checksum + item) & MASK64;68    found++;69  }70  return {checksum, found, misses};71}7273function checkMeasurement(actual, row, start, replacements) {74  const wanted = expected(row, start, replacements);75  if (wanted.checksum === null) assert.ok(BigInt(actual.checksum) >= 0n && BigInt(actual.checksum) <= BigInt(row.count));76  else assert.equal(BigInt(actual.checksum), wanted.checksum, `${row.label}: checksum at ${start}`);77  assert.equal(BigInt(actual.found), wanted.found, `${row.label}: found at ${start}`);78  assert.ok(BigInt(actual.body_instructions) > 0n, `${row.label}: missing body Counter0`);79  const exact = BigInt(actual.exact_lookups);80  const noExact = ['hll_observe', 'modify', 'scan'].includes(row.method);81  if (noExact) assert.equal(exact, 0n);82  else if (row.method !== 'bloom_lookup' || !row.filtered) assert.equal(exact, BigInt(row.count));83  else assert.ok(exact >= wanted.found && exact <= BigInt(row.count), `${row.label}: exact lookup count`);84  return {...wanted, exactLookups: exact, excessExactLookups: noExact ? 0n : exact - wanted.found};85}8687export function matrix() {88  const rows = [];89  for (let kind = 0; kind < KINDS.length; kind++) {90    for (const count of [1, 32]) {91      for (const pattern of [0, 1, 2, ...(MISSING.has(kind) ? [3] : [])]) {92        rows.push({method: 'lookup', kind, count, pattern, grouped: false,93          label: `${KINDS[kind]}-${PATTERNS[pattern]}-${count}-scalar`});94      }95    }96  }97  for (const kind of [0, 2]) {98    for (const pattern of [0, 1, 2, ...(kind === 2 ? [3] : [])]) {99      rows.push({method: 'lookup', kind, count: 32, pattern, grouped: true,100        label: `${KINDS[kind]}-${PATTERNS[pattern]}-32-grouped`});101    }102  }103  for (const count of [1, 100]) {104    for (const missPercent of [0, 50, 90, 99]) {105      for (const mode of ['baseline', 'scalar', 'grouped']) {106        rows.push({method: 'bloom_lookup', count, missPercent, grouped: mode === 'grouped',107          filtered: mode !== 'baseline', label: `bloom-${missPercent}miss-${count}-${mode}`});108      }109    }110  }111  for (const precision of [12, 14, 16]) {112    for (const count of [1, 1000]) {113      for (const newItems of [false, true]) {114        for (const batched of [false, true]) {115          rows.push({method: 'hll_observe', precision, count, batched, newItems,116            label: `hll-p${precision}-${newItems ? 'new' : 'duplicate'}-${count}-${batched ? 'batch' : 'scalar'}`});117        }118      }119    }120  }121  for (const kind of SCANNABLE) {122    for (const count of [32, 1024, 4096]) rows.push({method: 'scan', kind, count,123      label: `${KINDS[kind]}-scan-${count}`});124  }125  return rows;126}127128export function profileCases(rows = matrix()) {129  const labels = ['fixed-vec-distant-1-scalar', 'frozen-hash-distant-1-scalar',130    'frozen-sorted-distant-1-scalar', 'bitmap-distant-1-scalar', 'frozen-hash-set-distant-1-scalar',131    'fixed-vec-repeat-32-scalar', 'frozen-hash-repeat-32-scalar', 'frozen-sorted-repeat-32-scalar',132    'bitmap-repeat-32-scalar', 'fixed-vec-distant-32-grouped', 'bitmap-distant-32-grouped',133    'fixed-vec-scan-32', 'frozen-sorted-scan-32', 'hll-p12-duplicate-1-scalar'];134  const selected = labels.map(label => {135    const row = rows.find(row => row.label === label);136    assert.ok(row, `Missing diagnostic scenario ${label}`);137    return row;138  });139  for (const [source, label] of [140    ['bloom-99miss-100-scalar', 'bloom-99miss-32-scalar'],141    ['bloom-99miss-100-grouped', 'bloom-99miss-32-grouped'],142    ['hll-p16-duplicate-1000-batch', 'hll-p16-duplicate-32-batch'],143  ]) {144    const row = rows.find(row => row.label === source);145    assert.ok(row, `Missing diagnostic source ${source}`);146    selected.push({...row, count: 32, label});147  }148  assert.ok(selected.every(row => row.count <= 32), 'Diagnostic profiles must remain bounded');149  return selected;150}151152function modifiedValue(index) {153  return value(index) ^ 0x0123_4567_89ab_cdefn;154}155156function startsFor(row) {157  return row.method !== 'hll_observe' ? STARTS : row.newItems158    ? STARTS.map((_, sample) => 200_000n + BigInt(sample * row.count))159    : STARTS.map(start => start % (POPULATION - BigInt(row.count) + 1n));160}161162function invoke(actor, row, start) {163  if (row.method === 'hll_observe') return actor.hll_observe(row.precision, start, row.count, row.batched);164  if (row.method === 'scan') return actor.scan(row.kind, start, row.count);165  if (row.method === 'modify') return actor.modify(row.kind, start, modifiedValue(start));166  return row.method === 'lookup'167    ? actor.lookup(row.kind, row.pattern, start, row.count, row.grouped)168    : actor.bloom_lookup(start, row.count, row.missPercent, row.grouped, row.filtered);169}170171function meanDecimal(total, count) {172  const denominator = BigInt(count), whole = total / denominator;173  const fraction = ((total % denominator) * 100_000_000n / denominator).toString().padStart(8, '0').replace(/0+$/, '');174  return whole.toString() + (fraction ? '.' + fraction : '');175}176177export function stats(values) {178  assert.ok(values.length);179  const exact = values.map(BigInt), total = exact.reduce((sum, item) => sum + item, 0n);180  return {samples: exact.length, total, min: exact.reduce((a, b) => a < b ? a : b),181    max: exact.reduce((a, b) => a > b ? a : b), mean: meanDecimal(total, exact.length),182    meanNumerator: total, meanDenominator: exact.length};183}184185export function executionRows(measurement, method, calls) {186  assert.equal(measurement.summary.instructionTotalsComplete, true);187  assert.equal(measurement.summary.memoryDetailsComplete, true);188  const rows = measurement.summary.rows.filter(row => row.category === 'replicated');189  assert.equal(rows.length, calls, 'Expected one complete update execution per submitted call');190  assert.equal(measurement.summary.groups.query.executions, 0);191  for (const row of rows) {192    assert.equal(row.function, `canister_update ${method}`);193    assert.equal(row.attempt.status, 'completed');194    assert.equal(row.disposition.state, 'committed');195  }196  return rows;197}198199function summarizeRow(row, measurement, replies, models) {200  const executions = executionRows(measurement, row.method, SAMPLES);201  const sum = key => models.reduce((total, model) => total + model[key], 0n);202  return {...row, samples: SAMPLES, starts: startsFor(row), requestedItems: row.count * SAMPLES,203    instructions: stats(executions.map(item => item.instructions)),204    bodyCounter0: stats(replies.map(item => item.body_instructions)),205    replies,206    heapPageFees: stats(executions.map(item => item.pageAccessInstructions)),207    accessedHeapRegions: stats(executions.map(item => item.accessedPages)),208    dirtyHeapRegions: stats(executions.map(item => item.dirtyPages)),209    exactLookups: stats(replies.map(item => item.exact_lookups)),210    registerIncreases: row.method === 'hll_observe' ? stats(replies.map(item => item.checksum)) : null,211    found: sum('found'), misses: sum('misses'),212    realizedMissPercent: meanDecimal(sum('misses') * 100n, row.count * SAMPLES),213    excessExactLookups: sum('excessExactLookups'),214    filterFalsePositives: row.method === 'bloom_lookup' && row.filtered ? sum('excessExactLookups') : null,215    tracePath: measurement.tracePath, cycleDebit: measurement.metadata.cycleDebit,216    hostMillis: measurement.hostMillis,217    scope: 'Complete update endpoint instructions. Body Counter0 and observed heap tracking are separate; no baseline subtraction.'};218}219220export function profileDetails(measurement) {221  const profiles = measurement.trace.executions.filter(row => row.instruction_profile).map(row => {222    const profile = row.instruction_profile;223    assert.equal(profile.truncated, false, 'Truncated profile preserved; qualification fails');224    assert.equal(profile.page_details_truncated, false);225    assert.equal(profile.stack_details_truncated, false);226    assert.equal(profile.ledger.reconciled, true);227    assert.equal(BigInt(profile.ledger.reported_instructions), BigInt(row.instructions));228    assert.equal(BigInt(profile.ledger.unexplained_instructions), 0n);229    return {sequence: row.sequence_number, instructions: row.instructions, ledger: profile.ledger,230      rules: profile.rules, apiCalls: profile.api_calls, pageCharges: profile.page_charges,231      limitations: profile.limitations, truncated: profile.truncated,232      pageDetailsTruncated: profile.page_details_truncated, stackDetailsTruncated: profile.stack_details_truncated};233  });234  assert.equal(profiles.length, 1, 'Exactly one execution must have a bounded profile');235  return profiles[0];236}237238function deref(schema, iface) {239  for (let left = Object.keys(iface.types).length + 1; schema.k === 'ref'; left--) {240    assert.ok(left && Object.hasOwn(iface.types, schema.name), 'Invalid Wire reference');241    schema = iface.types[schema.name];242  }243  return schema;244}245246function checkShape(schema, wanted, iface) {247  const actual = deref(schema, iface);248  assert.equal(actual.k, wanted.k);249  if (wanted.bits) assert.equal(actual.bits, wanted.bits);250  if (wanted.items) {251    assert.equal(actual.items.length, wanted.items.length);252    actual.items.forEach((item, index) => checkShape(item, wanted.items[index], iface));253  }254  if (wanted.item) checkShape(actual.item, wanted.item, iface);255  if (wanted.fields) {256    assert.deepEqual(actual.fields.map(field => field.name), Object.keys(wanted.fields));257    for (const field of actual.fields) checkShape(field.value, wanted.fields[field.name], iface);258  }259}260261export function methodCore(schema, length) {262  assert.equal(schema.k, 'extension-tuple');263  assert.equal(schema.projected, true);264  assert.deepEqual(schema.extensions, []);265  assert.equal(schema.items.length, length);266  return schema.items;267}268269function checkInterface(iface) {270  assert.equal(iface.format, 'cdk-rsx-wire-v1');271  const u = bits => ({k: 'u', bits}), unit = {k: 'unit'}, bool = {k: 'bool'};272  const tuple = (...items) => ({k: 'tuple', items});273  const measurement = {k: 'record', fields: {checksum: u(64), found: u(64), body_instructions: u(64), exact_lookups: u(64)}};274  const hll = {k: 'record', fields: {estimate: {k: 'float', bits: 64}, nominal_relative_error: {k: 'float', bits: 64},275    zero_registers: u(32), saturated: bool, body_instructions: u(64)}};276  const expectedMethods = {277    noop: ['update', unit, unit], seed: ['update', tuple(u(64), u(32)), unit],278    freeze: ['update', unit, unit], lookup: ['update', tuple(u(8), u(8), u(64), u(32), bool), measurement],279    replace: ['update', tuple(u(64), u(64), bool), unit],280    snapshot: ['query', tuple(u(64)), {k: 'list', item: u(64)}],281    reuse_slot: ['update', unit, {k: 'list', item: u(64)}],282    bloom_lookup: ['update', tuple(u(64), u(32), u(8), bool, bool), measurement],283    hll_estimate: ['update', tuple(u(8)), hll],284    hll_observe: ['update', tuple(u(8), u(64), u(32), bool), measurement],285    hll_reset: ['update', tuple(u(8)), unit],286    scan: ['update', tuple(u(8), u(64), u(32)), measurement],287    modify: ['update', tuple(u(8), u(64), u(64)), measurement],288    layout: ['query', unit, {k: 'list', item: u(64)}],289  };290  for (const [name, [mode, request, response]] of Object.entries(expectedMethods)) {291    const method = iface.methods.find(method => method.name === name);292    assert.ok(method, `Missing expected Wire method ${name}`);293    assert.equal(method.mode, mode);294    const requestItems = request.items ?? [];295    const core = methodCore(method.request, requestItems.length);296    core.forEach((item, index) => checkShape(item, requestItems[index], iface));297    checkShape(methodCore(method.response, 1)[0], response, iface);298  }299}300301export async function loadArtifact({artifact, wasm, iface, manifest}, label) {302  if (artifact) {303    assert.ok(!wasm && !iface && !manifest, 'Use an artifact directory or an explicit Wasm/interface pair');304    const selected = resolve(artifact);305    if ((await stat(selected)).isDirectory()) {306      const candidates = (await readdir(selected)).filter(name => name.endsWith('.manifest.json'));307      assert.equal(candidates.length, 1, `${label}: directory must contain exactly one prepared manifest`);308      manifest = join(selected, candidates[0]);309      const stem = manifest.slice(0, -'.manifest.json'.length);310      wasm = stem + '.wasm'; iface = stem + '.wire.json';311    } else {312      assert.ok(selected.endsWith('.wasm'), `${label}: artifact must be a prepared directory or .wasm`);313      wasm = selected; iface = selected.slice(0, -5) + '.wire.json';314      manifest = selected.slice(0, -5) + '.manifest.json';315    }316  }317  assert.ok(wasm && iface, `${label}: supply --artifact or both --wasm and --iface`);318  wasm = resolve(wasm); iface = resolve(iface);319  manifest = resolve(manifest ?? wasm.slice(0, -'.wasm'.length) + '.manifest.json');320  const parsed = JSON.parse(await readFile(manifest, 'utf8'));321  assert.equal(parsed.format, 'cdk-rsx-typed-root-artifacts-v1');322  assert.equal(parsed.sourceUnchangedDuringBuild, true);323  const checked = await verifyBuild(manifest);324  const wasmBytes = await readFile(wasm), interfaceBytes = await readFile(iface);325  assert.equal(sha(wasmBytes), parsed.wasmSha256);326  assert.ok(parsed.outputs.some(output => resolve(output.path) === iface && output.sha256 === sha(interfaceBytes)),327    `${label}: interface is not a verified output of this artifact`);328  const wire = JSON.parse(interfaceBytes);329  checkInterface(wire);330  return {wasm: wasmBytes, iface: wire, init: encodeWireInit(wire, []), receipt: {331    label, wasmPath: wasm, interfacePath: iface, manifestPath: manifest, manifestSha256: sha(await readFile(manifest)),332    wasmSha256: sha(wasmBytes), interfaceSha256: sha(interfaceBytes), filesChecked: checked.filesChecked,333    commit: parsed.commit, features: parsed.features, sourceUnchangedDuringBuild: true}};334}335336async function sourceReceipt() {337  const files = ['run.mjs', 'README.md', 'measurement.mjs', 'pic-http.mjs',338    '../../tests/pocketic/wire-client.mjs', '../../tests/pocketic/wire-runtime.mjs', '../../tests/pocketic/.generated/wire-runtime.mjs', '../../tests/pocketic/.generated/wire-codec.mjs',339    '../../tests/pocketic/verify-build.mjs', '../../tests/pocketic/package-lock.json',340    'src/lib.rs', 'src/api.rs', 'src/tables/mod.rs'];341  return Object.fromEntries(await Promise.all(files.map(async name => {342    const path = resolve(HERE, name), bytes = await readFile(path);343    return [name, {path, bytes: bytes.length, sha256: sha(bytes)}];344  })));345}346347function checkHll(actual, precision, cardinality = POPULATION) {348  const trueCardinality = Number(cardinality), estimate = Number(actual.estimate);349  assert.ok(Number.isFinite(estimate) && estimate > 0, 'HLL estimate must be finite and positive');350  const trueRelativeError = (estimate - trueCardinality) / trueCardinality;351  assert.ok(Math.abs(trueRelativeError) <= 0.1, 'HLL exceeds the conservative 10% observed-accuracy bound');352  assert.equal(actual.saturated, false);353  assert.ok(Number.isInteger(actual.zero_registers) && actual.zero_registers >= 0 && actual.zero_registers <= 2 ** precision);354  assert.ok(Math.abs(actual.nominal_relative_error - 1.04 / Math.sqrt(2 ** precision)) <= 1e-12);355  assert.ok(BigInt(actual.body_instructions) > 0n);356  return {precision, trueCardinality, estimate, nominalRelativeError: actual.nominal_relative_error,357    trueRelativeError, zeroRegisters: actual.zero_registers, saturated: actual.saturated,358    qualification: 'Observed accuracy on this input, with a conservative 10% bound; nominal error is not a deterministic guarantee.'};359}360361function checkLayout(values) {362  const names = ['population', 'fixedVec', 'slotArena', 'bitmap', 'frozenHash', 'frozenSorted',363    'prefix', 'bloom', 'hll12', 'hll14', 'hll16', 'totalArenaAllocated', 'frozenHashSet'];364  assert.equal(values.length, names.length);365  assert.equal(BigInt(values[0]), POPULATION);366  const counts = Object.fromEntries(names.map((name, index) => [name, BigInt(values[index])]));367  const collections = Object.fromEntries(names.filter(name => name !== 'population' && name !== 'totalArenaAllocated').map(name => [name,368    {blocks: counts[name], reservedBytes: counts[name] * 65_536n}]));369  const known = Object.values(collections).reduce((sum, item) => sum + item.blocks, 0n);370  assert.ok(known <= counts.totalArenaAllocated);371  return {population: counts.population, collections, totalArenaAllocatedBlocksIncludingHylix: counts.totalArenaAllocated,372    totalLivePayloadBytes: counts.totalArenaAllocated * 65_536n,373    scope: 'Whole reserved payload blocks; excludes retained Root/authority/directories. Total includes Hylix virtual blocks. Physical block zero is additional; free physical blocks/high-water are separate.'};374}375376async function sampleAll(actor, replacements = new Map(), hllCardinality = POPULATION) {377  const result = [];378  for (const index of [0n, 255n, 256n, 4095n, 4096n, 50_000n, POPULATION - 1n]) {379    const current = replacements.get(index) ?? value(index);380    const snapshot = await actor.snapshot(index);381    assert.deepEqual(snapshot.map(BigInt), [POPULATION, current, current, current]);382    const kinds = [];383    for (let kind = 0; kind < KINDS.length; kind++) {384      const row = {label: `lifecycle-${KINDS[kind]}`, method: 'lookup', kind, pattern: 0, count: 1, grouped: false};385      const actual = await invoke(actor, row, index);386      checkMeasurement(actual, row, index, replacements);387      kinds.push({kind, checksum: actual.checksum, found: actual.found});388    }389    const bloom = {label: 'lifecycle-bloom', method: 'bloom_lookup', count: 100,390      missPercent: 50, grouped: true, filtered: true};391    const actualBloom = await invoke(actor, bloom, index);392    checkMeasurement(actualBloom, bloom, index);393    result.push({index, snapshot, kinds, bloom: {checksum: actualBloom.checksum, found: actualBloom.found}});394  }395  const hll = [];396  for (const precision of [12, 14, 16]) hll.push(checkHll(await actor.hll_estimate(precision), precision, hllCardinality));397  return {entries: result, hll};398}399400async function lifecycle(session, id, actor, artifact, rejectedArtifact) {401  const stages = [], upgrade = selected => session.pic.upgradeCanister({canisterId: id,402    wasm: gzipSync(selected.wasm), arg: selected.init,403    upgradeModeOptions: {skip_pre_upgrade: [], wasm_memory_persistence: [{keep: null}]}});404  const reused = await actor.reuse_slot();405  assert.deepEqual(reused.map(BigInt), [POPULATION, 1n, POPULATION, 2n, 0n, 456n]);406  const before = await sampleAll(actor);407  await upgrade(artifact);408  assert.deepEqual(await sampleAll(actor), before);409  const layoutAfterKeep = checkLayout(await actor.layout());410  const reusedAfterKeep = await actor.reuse_slot();411  assert.deepEqual(reusedAfterKeep.map(BigInt), [POPULATION, 3n, POPULATION, 4n, 0n, 456n]);412  stages.push({name: 'same-wasm-keep', status: 'PASS', samples: before, reused, reusedAfterKeep, layoutAfterKeep});413  if (rejectedArtifact) {414    await assert.rejects(() => upgrade(rejectedArtifact), /root catalog rejected[\s\S]*CanisterCalledTrap/);415    assert.deepEqual(await sampleAll(actor), before);416    stages.push({name: 'incompatible-contract-upgrade-rollback', status: 'PASS'});417  } else stages.push({name: 'incompatible-contract-upgrade-rollback', status: 'NOT_RUN', reason: 'No --reject-artifact supplied'});418419  const changedIndex = 4096n, changedValue = 0x1357_9bdf_2468_ace0n;420  await assert.rejects(() => actor.replace(changedIndex, changedValue, true), /Minima rollback probe/);421  assert.deepEqual(await sampleAll(actor), before);422  stages.push({name: 'trapped-replacement-rollback', status: 'PASS'});423  await actor.replace(changedIndex, changedValue, false);424  const changed = await sampleAll(actor, new Map([[changedIndex, changedValue]]));425  await upgrade(artifact);426  assert.deepEqual(await sampleAll(actor, new Map([[changedIndex, changedValue]])), changed);427  await actor.replace(changedIndex, value(changedIndex), false);428  assert.deepEqual(await sampleAll(actor), before);429  await upgrade(artifact);430  assert.deepEqual(await sampleAll(actor), before);431  stages.push({name: 'committed-replacement-keep-and-original-value-restore', status: 'PASS', changedIndex, changedValue});432  const hllUpdates = [];433  for (const precision of [12, 14, 16]) {434    const added = await actor.hll_observe(precision, 200_000n, 1000, true);435    assert.equal(BigInt(added.found), 1000n);436    assert.equal(BigInt(added.exact_lookups), 0n);437    assert.ok(BigInt(added.checksum) >= 0n && BigInt(added.checksum) <= 1000n);438    const duplicate = await actor.hll_observe(precision, 200_000n, 1000, false);439    assert.equal(BigInt(duplicate.checksum), 0n);440    assert.equal(BigInt(duplicate.found), 1000n);441    assert.equal(BigInt(duplicate.exact_lookups), 0n);442    hllUpdates.push({precision, addedRegisterIncreases: added.checksum});443  }444  const afterNew = await sampleAll(actor, new Map(), POPULATION + 1000n);445  await upgrade(artifact);446  assert.deepEqual(await sampleAll(actor, new Map(), POPULATION + 1000n), afterNew);447  for (const precision of [12, 14, 16]) {448    const duplicate = await actor.hll_observe(precision, 200_000n, 1000, true);449    assert.equal(BigInt(duplicate.checksum), 0n);450    assert.equal(BigInt(duplicate.found), 1000n);451    assert.equal(BigInt(duplicate.exact_lookups), 0n);452  }453  assert.deepEqual(await sampleAll(actor, new Map(), POPULATION + 1000n), afterNew);454  stages.push({name: 'new-hll-batch-idempotency-and-keep', status: 'PASS', hllUpdates, hll: afterNew.hll});455  return stages;456}457458function reportMarkdown(result) {459  const lines = ['# Minima complete endpoint measurements', '',460    'Each row is 32 fresh update calls after one warmup. Count is work inside each call. No no-op subtraction.', '',461    '| Row | Count | Endpoint instructions mean | Min | Max | Body Counter0 mean | Heap fees mean | Heap access/dirty regions mean |',462    '| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |'];463  for (const row of result.rows) lines.push(`| ${row.label} | ${row.count ?? 0} | ${row.instructions.mean} | ${row.instructions.min} | ${row.instructions.max} | ${row.bodyCounter0?.mean ?? '—'} | ${row.heapPageFees.mean} | ${row.accessedHeapRegions.mean}/${row.dirtyHeapRegions.mean} |`);464  lines.push('', 'Bloom rows include host-selected requests but all hashing, preparation and grouping execute inside the guest endpoint.', '',465    '| Bloom row | Realized misses % | Exact lookups | Found | Excess exact lookups | Filter false positives |',466    '| --- | ---: | ---: | ---: | ---: | ---: |');467  for (const row of result.rows.filter(row => row.method === 'bloom_lookup')) lines.push(`| ${row.label} | ${row.realizedMissPercent} | ${row.exactLookups.total} | ${row.found} | ${row.excessExactLookups} | ${row.filterFalsePositives ?? '—'} |`);468  lines.push('', '| HLL row | Actual register increases | Final true cardinality | Final estimate | True relative error |',469    '| --- | ---: | ---: | ---: | ---: |');470  for (const row of result.rows.filter(row => row.method.startsWith('hll_'))) {471    const accuracy = row.accuracy;472    lines.push(`| ${row.label} | ${row.registerIncreases?.total ?? '—'} | ${accuracy.trueCardinality} | ${accuracy.estimate} | ${accuracy.trueRelativeError} |`);473  }474  lines.push('', 'New HLL rows reset to the same 100k baseline, warm one duplicate, and observe the same 32 disjoint key batches per precision/count/mode. Reset and final estimation are outside traces. Scalar counts increase events; batch counts distinct registers changed per call. Final estimate summaries must match between modes.');475  lines.push('', 'Heap regions are the trace’s observed aligned 64 KiB tracking regions. They are not a stable-page trace.', '',476    'Prefix sums are standalone range-aggregation rows, not point-map comparisons. Body Counter0 excludes generated wrapper/cleanup work and is never substituted for endpoint totals.', '',477    `Lifecycle: ${result.lifecycle.map(stage => `${stage.name}: ${stage.status}`).join('; ')}.`, '',478    'Raw compressed traces and their completeness/profile receipts are retained under `traces/`. Profiles report full ledgers, API calls, rules and page charges separately from the 32-call rows.', '');479  return lines.join('\n');480}481482export function selfTest() {483  assert.ok(!STARTS.includes(431n), 'Mutation warmup must be outside the measured index series');484  assert.equal(value(0n), VALUE_XOR);485  assert.equal(value(1n), VALUE_XOR ^ (1n << 17n));486  assert.equal(value(MASK64), MASK64 ^ VALUE_XOR);487  for (const index of [0n, 1n, 16n, 17n, 4095n, 95_904n, 99_999n]) {488    let slow = 0n;489    for (let at = index; at < index + 4096n && at < POPULATION; at++) slow += at % 17n + 1n;490    assert.equal(prefixRange(index), slow);491  }492  const rows = matrix();493  assert.equal(rows.length, 150);494  for (const row of rows) {495    assert.ok(!row.grouped || row.method === 'bloom_lookup' || row.kind === 0 || row.kind === 2);496    assert.ok(row.pattern !== 3 || MISSING.has(row.kind));497    for (const start of startsFor(row)) {498      const model = expected(row, start);499      if (row.method === 'scan') assert.ok(model.found > 0n && model.found <= BigInt(row.count));500      else assert.equal(model.found + model.misses, BigInt(row.count));501      assert.ok(model.checksum === null || model.checksum >= 0n && model.checksum <= MASK64);502      if (row.method === 'bloom_lookup' && row.count === 100) assert.equal(model.misses, BigInt(row.missPercent));503      if (row.method === 'hll_observe') assert.ok(row.newItems ? start >= 200_000n : start + BigInt(row.count) <= POPULATION);504    }505  }506  const repeat = {method: 'lookup', kind: 0, count: 32, pattern: 0};507  assert.equal(expected(repeat, 7n).checksum, (32n * value(7n)) & MASK64);508  assert.equal(expected(repeat, 7n, new Map([[7n, 9n]])).checksum, 288n);509  assert.equal(expected({...repeat, kind: 3}, 7n, new Map([[7n, 9n]])).checksum, (32n * value(7n)) & MASK64);510  assert.equal(expected({...repeat, kind: 2}, 7n).checksum, 32n);511  assert.equal(expected({...repeat, kind: 10}, 7n).checksum, 32n);512  assert.deepEqual(expected({...repeat, kind: 3, pattern: 3}, 7n), {checksum: 0n, found: 0n, misses: 32n});513  assert.deepEqual(expected({...repeat, kind: 10, pattern: 3}, 7n), {checksum: 0n, found: 0n, misses: 32n});514  assert.equal(meanDecimal(33n, 32), '1.03125');515  assert.equal(expected({method: 'hll_observe', count: 1000, newItems: false}, 431n).checksum, 0n);516  assert.equal(expected({method: 'hll_observe', count: 1000, newItems: true}, 200_000n).checksum, null);517  assert.deepEqual(expected({method: 'scan', kind: 0, count: 4096}, POPULATION - 1n),518    {checksum: value(POPULATION - 1n), found: 1n, misses: 0n});519  assert.equal(expected({method: 'modify', kind: 0, count: 1}, 431n).checksum, modifiedValue(431n));520  const diagnostics = profileCases(rows);521  assert.equal(diagnostics.length, 17);522  assert.equal(new Set(diagnostics.map(row => row.label)).size, diagnostics.length);523  for (const row of diagnostics) {524    for (const start of startsFor(row)) {525      const model = expected(row, start);526      assert.equal(model.found + model.misses, BigInt(row.count));527    }528  }529  return {status: 'PASS', rows: rows.length, starts: STARTS.length, diagnosticProfiles: diagnostics.length,530    checks: ['u64 rotate/xor/wrapping sums', 'prefix closed form vs loop', 'all matrix oracle bounds',531      'exact within-call Bloom miss counts', 'missing/grouped eligibility', 'mutable vs frozen replacement model',532      'HLL duplicate/new key separation', 'bounded end-of-range scan', 'replacement mutation value',533      'FrozenHashSet exact membership/misses', 'diagnostic profiles bounded to 32 items']};534}535536function options(argv) {537  const result = {};538  for (let index = 0; index < argv.length; index++) {539    const match = /^--([a-z-]+)(?:=(.*))?$/.exec(argv[index]);540    assert.ok(match, `Unexpected argument ${argv[index]}`);541    const name = match[1];542    assert.ok(['artifact', 'wasm', 'iface', 'manifest', 'reject-artifact', 'out', 'pocket-ic', 'self-test', 'help'].includes(name), `Unknown option --${name}`);543    assert.ok(!Object.hasOwn(result, name), `Repeated option --${name}`);544    result[name] = ['self-test', 'help'].includes(name) ? true : match[2] ?? argv[++index];545    assert.ok(result[name] !== undefined && result[name] !== '', `Missing --${name} value`);546  }547  return result;548}549550async function main(argv) {551  const args = options(argv);552  if (args.help) {553    console.log('node benches/minima/run.mjs --artifact DIR --out NEW_DIR --pocket-ic BINARY [--reject-artifact DIR]\n' +554      '  or --wasm PREPARED.wasm --iface PREPARED.wire.json [--manifest PREPARED.manifest.json]\n' +555      '  --self-test checks the host model without a server or artifacts.');556    return;557  }558  const hostChecks = selfTest();559  if (args['self-test']) {console.log(JSON.stringify(hostChecks, json, 2)); return;}560  assert.ok(args.out && args['pocket-ic'], 'Required: --out NEW_DIR and --pocket-ic BINARY');561  const output = resolve(args.out);562  await mkdir(dirname(output), {recursive: true});563  await mkdir(output);564  const rows = [], profiles = [], checks = [];565  let session, artifact, rejectedArtifact, provenance;566  try {567    provenance = await sourceReceipt();568    await save(join(output, 'host-receipt.json'), {started: new Date().toISOString(), argv, node: process.version,569      provenance, hostChecks, population: POPULATION, seedBatch: 1000, samples: SAMPLES, starts: STARTS});570    artifact = await loadArtifact({artifact: args.artifact, wasm: args.wasm, iface: args.iface, manifest: args.manifest}, 'normal');571    if (args['reject-artifact']) rejectedArtifact = await loadArtifact({artifact: args['reject-artifact']}, 'reject-contract');572    if (rejectedArtifact) assert.notEqual(rejectedArtifact.receipt.wasmSha256, artifact.receipt.wasmSha256);573    await save(join(output, 'artifacts.json'), {normal: artifact.receipt, reject: rejectedArtifact?.receipt ?? null});574    await writeFile(join(output, 'rows.jsonl'), '', {flag: 'wx'});575    session = await createSession({outputDir: output, binaryPath: resolve(args['pocket-ic'])});576    const id = await session.pic.createCanister({cycles: 1_000_000_000_000_000n});577    await session.pic.installCode({canisterId: id, wasm: gzipSync(artifact.wasm), arg: artifact.init});578    const actor = createWireActor({pic: session.pic, canisterId: id, interface: artifact.iface});579    // Tracing remains off for all 100 committed population calls and freeze.580    for (let start = 0n; start < POPULATION; start += 1000n) await actor.seed(start, 1000);581    await actor.freeze();582    checks.push('100 committed seed calls plus freeze');583    await save(join(output, 'layout-after-freeze.json'), checkLayout(await actor.layout()));584    await save(join(output, 'population-samples.json'), await sampleAll(actor));585    await inspectCanister(session, id, {label: 'populated'});586587    await actor.noop();588    const noop = await traceCall(session, {canisterId: id, label: 'noop-32-fresh', expectedCalls: SAMPLES,589      invoke: async () => {for (let sample = 0; sample < SAMPLES; sample++) await actor.noop();}});590    const noopExecutions = executionRows(noop, 'noop', SAMPLES);591    rows.push({label: 'noop-32-fresh', method: 'noop', count: 0, samples: SAMPLES,592      instructions: stats(noopExecutions.map(item => item.instructions)),593      heapPageFees: stats(noopExecutions.map(item => item.pageAccessInstructions)),594      accessedHeapRegions: stats(noopExecutions.map(item => item.accessedPages)),595      dirtyHeapRegions: stats(noopExecutions.map(item => item.dirtyPages)), tracePath: noop.tracePath});596    await appendFile(join(output, 'rows.jsonl'), JSON.stringify(rows.at(-1), json) + '\n');597598    const scenarios = matrix(), hllFinalStates = new Map();599    await writeFile(join(output, 'setup.jsonl'), '', {flag: 'wx'});600    for (const row of scenarios) {601      const starts = startsFor(row);602      if (row.method === 'hll_observe' && row.newItems) {603        await actor.hll_reset(row.precision);604        await appendFile(join(output, 'setup.jsonl'), JSON.stringify({row: row.label,605          operation: 'hll_reset', precision: row.precision, phase: 'before', population: POPULATION}, json) + '\n');606        const warm = {...row, newItems: false, count: 1};607        checkMeasurement(await invoke(actor, warm, 431n), warm, 431n);608      } else checkMeasurement(await invoke(actor, row, starts[0]), row, starts[0]);609      const replies = [], models = [];610      const measurement = await traceCall(session, {canisterId: id, label: row.label, expectedCalls: SAMPLES,611        invoke: async () => {612          for (const start of starts) {613            const actual = await invoke(actor, row, start);614            models.push(checkMeasurement(actual, row, start)); replies.push(actual);615          }616        }});617      const summary = summarizeRow(row, measurement, replies, models);618      if (row.method === 'hll_observe') {619        summary.accuracy = checkHll(await actor.hll_estimate(row.precision), row.precision,620          POPULATION + (row.newItems ? BigInt(SAMPLES * row.count) : 0n));621        if (row.newItems) {622          const key = `${row.precision}/${row.count}`;623          if (hllFinalStates.has(key)) assert.deepEqual(summary.accuracy, hllFinalStates.get(key),624            'Matched scalar/batch HLL runs must produce identical final estimate/register summaries');625          else hllFinalStates.set(key, summary.accuracy);626          await actor.hll_reset(row.precision);627          await appendFile(join(output, 'setup.jsonl'), JSON.stringify({row: row.label,628            operation: 'hll_reset', precision: row.precision, phase: 'after', population: POPULATION,629            measuredFinalAccuracy: summary.accuracy}, json) + '\n');630        }631      }632      rows.push(summary);633      await appendFile(join(output, 'rows.jsonl'), JSON.stringify(rows.at(-1), json) + '\n');634      console.log(`${row.label}: ${rows.at(-1).instructions.mean} endpoint instructions`);635    }636    checks.push('lookup/Bloom/scan oracles; HLL duplicate idempotency and matched reset/new rows');637638    for (const precision of [12, 14, 16]) {639      checkHll(await actor.hll_estimate(precision), precision);640      const replies = [], accuracies = [], label = `hll-p${precision}-estimate`;641      const measurement = await traceCall(session, {canisterId: id, label, expectedCalls: SAMPLES,642        invoke: async () => {643          for (let sample = 0; sample < SAMPLES; sample++) {644            const actual = await actor.hll_estimate(precision);645            accuracies.push(checkHll(actual, precision)); replies.push(actual);646          }647        }});648      const executions = executionRows(measurement, 'hll_estimate', SAMPLES);649      for (const accuracy of accuracies) assert.deepEqual(accuracy, accuracies[0]);650      rows.push({label, method: 'hll_estimate', precision, count: 1, samples: SAMPLES,651        instructions: stats(executions.map(item => item.instructions)),652        bodyCounter0: stats(replies.map(item => item.body_instructions)),653        replies,654        heapPageFees: stats(executions.map(item => item.pageAccessInstructions)),655        accessedHeapRegions: stats(executions.map(item => item.accessedPages)),656        dirtyHeapRegions: stats(executions.map(item => item.dirtyPages)),657        accuracy: accuracies[0], tracePath: measurement.tracePath});658      await appendFile(join(output, 'rows.jsonl'), JSON.stringify(rows.at(-1), json) + '\n');659    }660661    for (const row of profileCases(scenarios)) {662      const label = row.label;663      const starts = startsFor(row);664      checkMeasurement(await invoke(actor, row, starts[0]), row, starts[0]);665      const reference = await traceCall(session, {canisterId: id, label: `reference-${label}`, expectedCalls: 1,666        invoke: async () => {667          const actual = await invoke(actor, row, starts[1]);668          checkMeasurement(actual, row, starts[1]); return actual;669        }});670      const referenceExecution = executionRows(reference, row.method, 1)[0];671      const measurement = await traceCall(session, {canisterId: id, label: `profile-${label}`, profile: true, expectedCalls: 1,672        invoke: async () => {673          const actual = await invoke(actor, row, starts[1]);674          checkMeasurement(actual, row, starts[1]); return actual;675        }});676      const profiledExecution = executionRows(measurement, row.method, 1)[0];677      profiles.push({label, start: starts[1], tracePath: measurement.tracePath,678        measurement: measurement.value, profile: profileDetails(measurement),679        unprofiledCompanion: {tracePath: reference.tracePath, execution: referenceExecution, measurement: reference.value},680        observerInstructionDelta: BigInt(profiledExecution.instructions) - BigInt(referenceExecution.instructions),681        scope: 'Adjacent same-input unprofiled/profiled calls, with no intervening warmup; read/duplicate operations leave domain contents unchanged. Cache history may evolve.'});682    }683    await save(join(output, 'profiles.json'), profiles);684    for (const kind of MUTABLE) {685      const row = {method: 'modify', kind, count: 1, label: `${KINDS[kind]}-modify-1`};686      checkMeasurement(await invoke(actor, row, 431n), row, 431n);687      const replies = [], models = [];688      const measurement = await traceCall(session, {canisterId: id, label: row.label, expectedCalls: SAMPLES,689        invoke: async () => {690          for (const start of STARTS) {691            const actual = await invoke(actor, row, start);692            models.push(checkMeasurement(actual, row, start)); replies.push(actual);693          }694        }});695      const changedIndices = [...new Set([431n, ...STARTS])];696      const read = {method: 'lookup', kind, pattern: 0, count: 1, grouped: false, label: `${row.label}-verify`};697      const replacements = new Map(changedIndices.map(index => [index, modifiedValue(index)]));698      for (const index of changedIndices) checkMeasurement(await invoke(actor, read, index), read, index, replacements);699      for (const index of changedIndices) await actor.replace(index, value(index), false);700      for (const index of changedIndices) checkMeasurement(await invoke(actor, read, index), read, index);701      const summary = summarizeRow(row, measurement, replies, models);702      summary.validation = {verifiedStoredValues: changedIndices.length, originalsRestored: true,703        warmupIndex: 431n, warmupOutsideMeasuredSeries: !STARTS.includes(431n)};704      rows.push(summary);705      await appendFile(join(output, 'rows.jsonl'), JSON.stringify(summary, json) + '\n');706      await appendFile(join(output, 'setup.jsonl'), JSON.stringify({row: row.label,707        operation: 'replace-original-values', outsideCapture: true, indices: changedIndices}, json) + '\n');708    }709    const stages = await lifecycle(session, id, actor, artifact, rejectedArtifact);710    checks.push('stored mutation values verified and originals restored; actual KEEP and rollback lifecycle');711    await inspectCanister(session, id, {label: 'after-lifecycle'});712    assert.deepEqual(await sourceReceipt(), provenance, 'Harness/API sources changed during measurement');713    const result = {status: rejectedArtifact ? 'PASS' : 'PASS_WITH_NOT_RUN_CHECK', checks,714      artifacts: {normal: artifact.receipt, reject: rejectedArtifact?.receipt ?? null},715      canisterId: id.toText(), rows, profiles, lifecycle: stages, provenance,716      scope: '32 fresh physical update executions per row, one preceding warmup. Profiles are separate one-execution captures. No instruction subtraction.'};717    await save(join(output, 'results.json'), result);718    await writeFile(join(output, 'results.md'), reportMarkdown(result), {flag: 'wx'});719    console.log(`${result.status}: ${rows.length} rows; ${profiles.length} profiles; lifecycle checks saved in ${output}`);720  } catch (error) {721    await save(join(output, 'failure.json'), {error: String(error.stack ?? error), checks, completedRows: rows,722      completedProfiles: profiles, artifacts: {normal: artifact?.receipt, reject: rejectedArtifact?.receipt}, provenance});723    throw error;724  } finally {if (session) await session.shutdown();}725}726727if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {728  await main(process.argv.slice(2));729}