benchmark.mjs
benches/rrt/host/benchmark.mjs
This JavaScript runner executes the RRT workloads in PocketIC and calculates the totals and rates reported for runs such as Heavy16.
1import assert from 'node:assert/strict';2import {readFile, writeFile} from 'node:fs/promises';3import {createHash} from 'node:crypto';4import {spawnSync} from 'node:child_process';5import {createReadStream} from 'node:fs';6import {resolve} from 'node:path';7import {fileURLToPath, pathToFileURL} from 'node:url';8import {flagValue, instructionBudget, checkWasm, reserveResults, selectBlockVerifier} from '../support/run-io.mjs';9import {Principal} from '@icp-sdk/core/principal';10import {getBlocks, getTipCertificate, hashBlock} from '../support/rechain-client.mjs';11import {verifyTipCertificate} from '../../../tests/pocketic/rechain-verification.mjs';12import {group, options, states, drained, json, owner, canisterLogs, kinds, heavyKinds, receiptTimes, latencySummary} from './support.mjs';13import {load, expectedWork} from './load.mjs';14import {report} from './report.mjs';15import {session as createSession} from './session.mjs';16import {summarizeProfile} from './profile.mjs';17import {instructions} from './runtime-metrics.mjs';18import {measureMaintenanceTail, combinedTotals} from './maintenance-tail.mjs';19import {capturePageProfiles, summarizePageInterval} from './page-profile.mjs';20import {buildDirectory} from '../support/harness.mjs';21import {verifyBuild} from '../../../tests/pocketic/verify-build.mjs';22import {resources} from '../../../tests/pocketic/resources.mjs';23import {instructionProfiles, profileDelta} from '../../../tests/pocketic/instruction-profile.mjs';24import {startNativeMemoryTrace} from '../../../tests/pocketic/native-memory-trace.mjs';25import {runtimeSourceUrls} from '../../../tests/pocketic/wire-runtime.mjs';2627const get = (key, fallback) => flagValue(process.argv, key, fallback);28const loads = get('loads', '1,8,32').split(',').map(Number);29const canisters = Number(get('canisters', '16'));30const workloadName = get('workload', 'heavy');31assert.ok(['mixed', 'heavy'].includes(workloadName));32const selectedKinds = workloadName === 'heavy' ? heavyKinds : kinds;33const mixSize = canisters * selectedKinds.length;34const roundMillis = Number(get('round-ms', '600'));35const rates = get('rates', '1000').split(',').filter(Boolean).map(Number);36const arrivalRounds = Number(get('arrival-rounds', '30'));37const mode = rates.length ? 'sustained' : 'burst';38const crossSubnet = get('topology', 'same') === 'cross';39const batchSizes = get('batches', '1024').split(',').map(Number);40const budget = instructionBudget(get('budget', '500000000'));41const concurrency = Number(get('concurrency', '4096'));42const batchBytes = Number(get('batch-bytes', '1900000'));43const callbacks = Number(get('callbacks', '40'));44const maxRounds = Number(get('max-rounds', '1000'));45const tailMaxRounds = Number(get('tail-max-rounds', '100'));46const tailRegionFlag = get('tail-region-stats', 'false');47assert.ok(['false', 'true'].includes(tailRegionFlag));48const tailRegionStats = tailRegionFlag === 'true';49assert.ok(Number.isSafeInteger(tailMaxRounds) && tailMaxRounds > 0);50const profilingBinary = get('pocket-ic', '');51const nativeTraceFlag = get('memory-tracing', 'false');52assert.ok(['false', 'true'].includes(nativeTraceFlag));53const nativeMemoryTracing = nativeTraceFlag === 'true';54const traceScope = get('trace-scope', 'window');55assert.ok(['window', 'complete'].includes(traceScope));56const traceStartRound = Number(get('trace-start-round', '15'));57const traceRounds = Number(get('trace-rounds', '3'));58assert.ok(Number.isSafeInteger(traceStartRound) && traceStartRound > 0);59assert.ok(Number.isSafeInteger(traceRounds) && traceRounds > 0 && traceStartRound + traceRounds - 1 <= maxRounds);60assert.ok(!nativeMemoryTracing || profilingBinary, 'Native memory tracing requires an explicit custom PocketIC binary');61const replicaRoundInstructions = get('replica-round-instructions', '');62const replicaNonDtsInstructions = get('replica-non-dts-instructions', '');63assert.ok([replicaRoundInstructions, replicaNonDtsInstructions].every(value => !value ||64 (profilingBinary && Number.isSafeInteger(Number(value)) && Number(value) > 0)),65 'Replica instruction overrides require the profiling binary and positive instruction counts');66assert.ok(loads.every(n => Number.isInteger(n) && n > 0 && n <= 500));67assert.ok(Number.isInteger(canisters) && canisters >= 4);68assert.ok(batchSizes.every(n => Number.isInteger(n) && n >= 1 && n <= 1024));69assert.ok(Number.isInteger(roundMillis) && roundMillis > 0);70assert.ok(Number.isInteger(concurrency) && concurrency > 0 && concurrency <= 4096);71assert.ok(budget > 0n && budget <= 18_446_744_073_709_551_615n);72assert.ok(Number.isInteger(batchBytes) && batchBytes >= 1024 && batchBytes <= 1_900_000);73assert.ok(Number.isInteger(callbacks) && callbacks >= 6 && callbacks <= 256,74 'Keep four callback units reserved for control and at least two for a transport call');75assert.ok(Number.isInteger(arrivalRounds) && arrivalRounds > 0);76assert.ok(Number.isInteger(maxRounds) && maxRounds >= arrivalRounds);77assert.ok(rates.every(rate => Number.isInteger(rate) && rate > 0 && Number.isSafeInteger(rate * roundMillis / 1000)),78 'Each round must contain a whole number of ingress messages; partial workload mixes continue in the next round');79const sum = (rows, field) => rows.reduce((n, r) => n + r.metrics[field], 0n);80const workflowSum = (rows, field) => rows.reduce((n, r) => n + r.workflow[field], 0n);81const endpointMessages = rows => sum(rows, 'processedRequests') + sum(rows, 'processedNotifications');82const total = (rows, field) => rows.reduce((n, r) => n + Number(r[field]), 0);8384async function hashFile(path) {85 const hash = createHash('sha256'); for await (const chunk of createReadStream(path)) hash.update(chunk); return hash.digest('hex');86}87const exec = (cmd, args, cwd) => spawnSync(cmd, args, {cwd, encoding: 'utf8'}).stdout.trim();8889const binary = profilingBinary ? resolve(profilingBinary) : new URL('../../../cdk-rsx/tmp/pocketic16/pocket-ic', import.meta.url).pathname;90const buildPath = resolve(get('build-manifest', new URL('manifest.json', buildDirectory).pathname));91const {manifest: build, filesChecked} = await verifyBuild(buildPath);92await selectBlockVerifier(build);93const pageMetadata = build.pageProfile?.metadata ?? null;94const wasmSha256 = await hashFile(new URL('reactor_cell.wasm', buildDirectory));95checkWasm(process.argv, wasmSha256);96assert.equal(build.wasmSha256 ?? build.outputs?.find(f => f.path.endsWith('.wasm'))?.sha256, wasmSha256, 'Build provenance must match the measured Wasm');97const harness = await Promise.all(['benchmark','support','session','load','report','profile','runtime-metrics','maintenance-tail','page-profile'].map(async name => {const path=fileURLToPath(new URL(`./${name}.mjs`,import.meta.url));const bytes=await readFile(path);return {path,bytes:bytes.length,sha256:createHash('sha256').update(bytes).digest('hex'),source:bytes.toString('utf8')}}));98for (const url of [...['../../../tests/pocketic/native-memory-trace.mjs',99 '../../../tests/pocketic/verify-build.mjs',100 '../../../tests/pocketic/package.json',101 '../../../tests/pocketic/package-lock.json',102 '../../../tests/pocketic/rechain-verification.mjs',103 '../support/run-io.mjs', '../support/harness.mjs', '../support/rechain-client.mjs', '../support/tripwire-client.mjs',104 '../../../tests/pocketic/resources.mjs',105 '../../../tests/pocketic/session.mjs',106 '../../../tests/pocketic/strict-tick.mjs',107 '../../../tests/pocketic/instruction-profile.mjs',108 '../../../tests/pocketic/reactor-wire.mjs', '../../../tests/pocketic/wire-client.mjs',109 '../../../tests/pocketic/wire-runtime.mjs'].map(relative => new URL(relative, import.meta.url)), ...runtimeSourceUrls]) {110 const path = fileURLToPath(url), bytes = await readFile(path);111 harness.push({path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), source: bytes.toString('utf8')});112}113const manifest = {114 harness,115 measuredAt: new Date().toISOString(), pocketIcServerUrl: process.env.RRT_PIC_SERVER_URL ?? null, pocketIc: exec(binary, ['--version']), pocketIcBinary: binary, pocketIcSha256: await hashFile(binary),116 wasmSha256, artifactDirectory: buildDirectory.pathname,117 implementation: build.implementation ?? 'motoko', build, verifiedBuildFiles: filesChecked,118 configuration: {mode, workloadName, selectedKinds, canisters, mixSize, roundMillis, crossSubnet, budget, concurrency, batchBytes, callbacks,119 loads, rates, arrivalRounds, maxRounds, batchSizes, tailMaxRounds, tailRegionStats, pageProfiling: Boolean(pageMetadata),120 nativeMemoryTracing, nativeTraceWindow: nativeMemoryTracing && traceScope === 'window' ? {startRound: traceStartRound, rounds: traceRounds} : null, nativeTraceScope: nativeMemoryTracing ? traceScope : null, replicaProfiling: Boolean(profilingBinary), replicaRoundInstructions: replicaRoundInstructions || null,121 replicaNonDtsInstructions: replicaNonDtsInstructions || null, dts: true, benchmarkingInstructionLimits: false},122 scope: `Replica execution simulation, not a mainnet TPS prediction. No consensus/network simulation. ${canisters} cells, seven definitions each, running the ${workloadName} mix; ${selectedKinds.filter(k => k === 'Child').length}/${selectedKinds.length} root workflows await block notifications.`,123 endpointMessages: 'Completed Reactor router request/notification deliveries, counted by receivers. Excludes response/event frames, expired requests, deferred attempts, wire duplicates and physical batch envelopes.',124 counting: 'sentBatches is every application cross-canister update attempt. Each successful attempt has an ack response. Request/result/event items count separately; returned results are independent batch calls. Self async launchers and timers are not cross-canister messages. No application calls bypass Reactor.',125 steps: 'A workflow step is one completed graph-state visit, including transforms, choices, waits, parallel control and terminal states. Parallel branch and child visits count separately; retries are attempts of the same visit. Native RRT counters survive result pruning and qualified KEEP upgrades. No upgrades occur during throughput measurements.',126 instructions: nativeMemoryTracing127 ? `Native host MemoryAccessTrace records complete finished replicated Wasm entry instructions and the included heap-page component. ${traceScope === 'window' ? 'Only the bounded execution-start cohort is traced; these are not whole-workload instruction totals.' : 'The complete primary workload and normal maintenance tail are traced; setup and subsequent management inspection are excluded.'} Query/inspect/composite-query callback rows are preserved separately; no cycle conversion or additional Wasm observer is used.`128 : `Unavailable/null for Rust. When reported by Motoko: delta of RTS cumulative lifetime instructions across all ${canisters} canisters, including mutator and GC work, sampled with read-only queries after each round. Accounting occurs when a message completes: DTS work may be charged to its finishing round, and trapped work is not retained. This is not the exact replica round instruction metric and excludes native scheduler overhead. Last-message mutator/collector fields are samples, not cumulative totals.`,129};130const runs = [];131const workloads = mode === 'sustained'132 ? rates.map(rate => ({rate, cyclesPerRound: rate * roundMillis / (mixSize * 1000), ingressPerRound: rate * roundMillis / 1000, arrivalRounds}))133 : loads.map(cycles => ({cyclesPerRound: cycles, arrivalRounds: 1}));134const directory = get('results-dir', '') ? pathToFileURL(resolve(get('results-dir')) + '/') : new URL('../tmp/results/', import.meta.url);135const stem = `${workloadName}-${mode === 'sustained' ? `sustained-${arrivalRounds}rounds-${rates.join('-')}rps-` : `burst-${loads.join('-')}mixes-`}${canisters}can-${crossSubnet ? 'cross' : 'same'}-${roundMillis}ms-${budget}-concurrency${concurrency}-batches${batchSizes.join('-')}-bytes${batchBytes}-callbacks${callbacks}-${manifest.wasmSha256.slice(0, 8)}${nativeMemoryTracing ? `-native-trace-${traceScope === 'complete' ? 'complete' : `r${traceStartRound}-${traceStartRound + traceRounds - 1}`}` : ''}${profilingBinary ? `-pic${manifest.pocketIcSha256.slice(0, 8)}-round${replicaRoundInstructions || 'default'}-nd${replicaNonDtsInstructions || 'default'}` : ''}`;136const output = await reserveResults(directory, stem);137try {138for (const workload of workloads) for (const batchItems of batchSizes) {139 const session = await createSession(options(crossSubnet, canisters), {binary,140 roundInstructions: replicaRoundInstructions, nonDtsInstructions: replicaNonDtsInstructions});141 let nativeTrace = null;142 let nativeWindow = null;143 try {144 const pic = session.pic;145 const cells = await group(pic, {canisters, batchItems, budget, concurrency, batchBytes, callbacks, crossSubnet});146 const resourcesBefore = await resources(pic, cells, Principal.anonymous());147 const profileBefore = await instructionProfiles(pic, cells);148 const pagePrefix = `${stem}-${workload.rate ?? workload.cyclesPerRound}load-${batchItems}batch-pages`;149 const pageBefore = pageMetadata ? await capturePageProfiles(pic, cells, pageMetadata, owner, directory, `${pagePrefix}-before`) : null;150 const initial = await states(cells);151 assert.ok(initial.every(drained));152 assert.equal(sum(initial, 'sentBatches'), 0n);153 const balancesBefore = await Promise.all(cells.map(c => pic.getCyclesBalance(c.canisterId)));154 const initialTime = await pic.getTime();155 const initialReplicaProfile = session.profile ? await session.profile() : null;156 const replicaProfile = initialReplicaProfile ? {initial: initialReplicaProfile, rounds: []} : null;157 const traceBoundary = async (rows, round, submitted) => ({round, submitted,158 icTimeMillis: await pic.getTime(), admitted: total(rows, 'admitted'), rejected: total(rows, 'rejected'),159 pending: total(rows, 'pending'), completedSteps: workflowSum(rows, 'completed'),160 taskAttempts: workflowSum(rows, 'attempts'), completedWorkflows: workflowSum(rows, 'succeeded'),161 processedEndpointMessages: endpointMessages(rows), blocks: total(rows, 'total'),162 physicalCalls: sum(rows, 'sentBatches'), acceptedFrames: sum(rows, 'acceptedFrames'),163 offeredFrames: ['sentRequests', 'sentResults', 'sentNotifications', 'sentEvents']164 .reduce((n, field) => n + sum(rows, field), 0n)});165 const traceTransition = async (rows, round, submitted) => {166 if (!nativeMemoryTracing) return;167 if (round === (traceScope === 'complete' ? 0 : traceStartRound - 1)) {168 nativeWindow = {mode: traceScope, startRound: traceScope === 'complete' ? 1 : traceStartRound, rounds: traceScope === 'complete' ? null : traceRounds,169 start: await traceBoundary(rows, round, submitted),170 serverUrl: process.env.RRT_PIC_SERVER_URL ?? null, instancePath: pic.client.instancePath,171 canisterIds: cells.map(cell => cell.canisterId.toText()),172 scope: traceScope === 'complete'173 ? 'Complete finished entries from before primary workload through ordinary publication/maintenance completion. Setup and subsequent management inspection are excluded.'174 : 'Complete entries selected at execution start in the fixed round window. DTS entries may finish after stop; final export follows ordinary workload and maintenance completion. Boundary work deltas are not equal-work normalization and totals are not whole-workload instructions.'};175 nativeTrace = await startNativeMemoryTrace(pic, cells, directory,176 `${workload.rate ?? workload.cyclesPerRound}load-${batchItems}batch`);177 console.log(JSON.stringify({nativeTraceStarted: nativeWindow}, json));178 }179 if (traceScope === 'window' && round === traceStartRound + traceRounds - 1 && nativeTrace) {180 await nativeTrace.stop();181 nativeWindow.end = await traceBoundary(rows, round, submitted);182 nativeWindow.completedWorkDelta = Object.fromEntries(Object.entries(nativeWindow.end)183 .filter(([key]) => !['round', 'icTimeMillis'].includes(key))184 .map(([key, value]) => [key, value - nativeWindow.start[key]]));185 console.log(JSON.stringify({nativeTraceStopped: nativeWindow}, json));186 }187 };188 await traceTransition(initial, 0, 0);189 const wallStart = performance.now();190 let previousInstructions = instructions(initial);191 const result = await load(pic, cells, {...workload, selectedKinds, roundMillis, maxRounds, returnPartial: true,192 onRound: async (rows, round, submitted) => {193 await traceTransition(rows, round, submitted);194 if (nativeTrace) await nativeTrace.flush();195 if (replicaProfile) replicaProfile.rounds.push({round, profile: await session.profile()});196 const currentInstructions = instructions(rows);197 const roundInstructions = currentInstructions === null || previousInstructions === null ? null : currentInstructions - previousInstructions;198 assert.ok(roundInstructions === null || roundInstructions >= 0n);199 previousInstructions = currentInstructions;200 if (round % 10 === 0 || round === workload.arrivalRounds) console.log(JSON.stringify({canisters, rate: workload.rate,201 batchItems, round, submitted, admitted: total(rows, 'admitted'), rejected: total(rows, 'rejected'),202 pending: total(rows, 'pending'), completedSteps: workflowSum(rows, 'completed'), completedWorkflows: workflowSum(rows, 'succeeded'),203 processedEndpointMessages: endpointMessages(rows), blocks: total(rows, 'total'),204 accountedInstructions: roundInstructions, heapMiB: rows.map(r => r.rts ? Math.round(Number(r.rts.heapBytes) / 1048576) : null),205 lastGcMillions: rows.map(r => r.rts ? Math.round(Number(r.rts.lastMessageCollectorInstructions) / 1e6) : null),206 ...(replicaProfile ? {replica: replicaProfile.rounds.at(-1).profile.subnets.map(({last_round: r}) => ({207 stop: r.stop_reason, wasm: r.wasm_instructions, charged: r.charged_instructions,208 threads: r.threads.map(t => t.charged_instructions), rateLimited: r.rate_limited_canisters.length}))} : {})}, json));209 },210 });211 const wallMillis = performance.now() - wallStart;212 if (nativeMemoryTracing && traceScope === 'window') assert.ok(nativeWindow?.end, 'Workload ended before the requested trace window closed');213 const nativePrimary = nativeTrace && traceScope === 'complete' ? await nativeTrace.capture('primary') : null;214 if (nativePrimary) nativeWindow.primaryEnd = await traceBoundary(result.rows, result.rounds, result.receipts.length);215 // Finishing alone does not prove trap-free progress: another deadline can216 // wake a scheduler whose earlier turn rolled back. Query controller logs217 // without ticking so completed runs also detect that failure.218 const logs = await Promise.all(cells.map(async cell => {219 try {return await canisterLogs(pic, cell)} catch (error) {return {error: String(error)}}220 }));221 const logErrors = logs.some(log => !Array.isArray(log));222 const traps = logs.flatMap((entries, cell) => Array.isArray(entries)223 ? entries.filter(entry => entry.text.includes('[TRAP]')).map(entry => ({cell, ...entry})) : []);224 if (!result.finished || logErrors || traps.length) {225 const reason = !result.finished ? 'Did not drain within the configured round limit'226 : logErrors ? 'Could not verify canister logs' : 'Canister trapped during the workload';227 let pageFailure = null;228 if (pageMetadata) {229 try {230 const pages = await capturePageProfiles(pic, cells, pageMetadata, owner, directory, `${pagePrefix}-failed`);231 pageFailure = summarizePageInterval(pageBefore, pages, pageMetadata);232 } catch (error) {pageFailure = {error: String(error)}}233 }234 const failure = {manifest, workload, batchItems, reason, replicaProfile, pageProfile: pageFailure,235 rounds: result.rounds, simulatedMillis: result.simulatedMillis, wallMillis, logs, rows: result.rows,236 samples: result.samples, admissions: result.receipts.map(({cell, kind, reply}) => ({cell, kind, reply}))};237 const path = new URL(`${stem}-${workload.rate ?? workload.cyclesPerRound}load-${batchItems}batch-failed.json`, directory);238 await writeFile(path, JSON.stringify(failure, json, 2) + '\n', {flag: 'wx'});239 throw new Error(`${reason}; saved diagnostics in ${path.pathname}`);240 }241 const expected = expectedWork(result.receipts, canisters);242 for (let i = 0; i < cells.length; i++) {243 const row = result.rows[i], target = expected.cells[i];244 assert.deepEqual(row.counts, target.counts);245 assert.equal(row.admitted, target.roots);246 assert.equal(row.workflow.admitted, target.workflows);247 assert.equal(row.workflow.succeeded, target.workflows);248 assert.equal(row.workflow.failedExecutions, 0n);249 assert.equal(row.workflow.entered, target.steps);250 assert.equal(row.workflow.completed, target.steps);251 assert.equal(row.workflow.failed, 0n);252 assert.equal(row.total, Object.values(target.counts).reduce((n, x) => n + x, 0n));253 assert.equal(row.fingerprints, row.total);254 if (row.total > 0n) assert.equal(Principal.fromUint8Array(row.lastCaller.some).toText(), owner.toText());255 }256 const finalTime = await pic.getTime();257 assert.equal(finalTime - initialTime, result.simulatedMillis, 'Only explicit rounds may advance the measurement clock');258 const balancesAfter = await Promise.all(cells.map(c => pic.getCyclesBalance(c.canisterId)));259 const latencies = [], rootLatencies = [], queueDelays = [];260 // Observer queries do not advance IC time, but their traces share the261 // instance-wide recording budget. Export during the audit as well as ticks.262 const receivedTimes = await receiptTimes(cells, result.receipts, {263 onBatch: nativeTrace ? async count => {264 if (count % 512 === 0) await nativeTrace.flush();265 } : undefined,266 });267 if (nativeTrace) await nativeTrace.flush();268 let verifiedCanonicalBlocks = 0;269 const certifiedThrough = [];270 for (const [i, cell] of cells.entries()) {271 const info = await cell.actor.get_chain_info({from: null}, null);272 assert.equal(info.ok.log_length, result.rows[i].total, 'Each committed action must have exactly one permanent block');273 const length = info.ok.log_length;274 if (length) {275 const ranges = [{start: 0n, length: 32n}];276 if (length > 32n) ranges.push({start: length > 64n ? length - 32n : 32n, length: 32n});277 const sampled = await getBlocks(cell.actor, ranges);278 assert.equal(sampled.blocks.length, Number(length < 64n ? length : 64n));279 const certificate = (await getTipCertificate(cell.actor)).some;280 await verifyTipCertificate(pic, cell.canisterId, certificate);281 // Rechain publishes certificates on a fixed deadline under load. Check282 // the published block without ticking to flush its deferred tail.283 const tip = certificate.tips.find(value => value.chain === 0)?.tip.value;284 assert.ok(tip && tip.index < length);285 const published = sampled.blocks.find(value => value.id === tip.index)286 ?? (await getBlocks(cell.actor, [{start: tip.index, length: 1n}])).blocks[0];287 assert.equal(published.id, tip.index);288 assert.deepEqual(hashBlock(published.block), Uint8Array.from(tip.hash));289 certifiedThrough.push(tip.index);290 verifiedCanonicalBlocks += sampled.blocks.length;291 }292 for (const kind of new Set(selectedKinds)) {293 let from = null;294 do {295 const page = (await cell.actor.takt_inspect({tag: kind, value: {tag: 'Executions', value: {from, limit: 64n}}})).value.value;296 for (const execution of page.items) {297 assert.equal(execution.status.tag, 'Succeeded');298 latencies.push(Number(execution.finishedAt.some - execution.createdAt) / 1_000_000);299 const receivedAt = receivedTimes[i].get(`${kind}:${execution.id}`);300 if (receivedAt !== undefined) {301 assert.ok(execution.createdAt >= receivedAt, 'Workflow cannot start before receipt');302 rootLatencies.push(Number(execution.finishedAt.some - receivedAt) / 1_000_000);303 queueDelays.push(Number(execution.createdAt - receivedAt) / 1_000_000);304 }305 }306 from = page.nextFrom;307 } while (from !== null);308 }309 if (nativeTrace) await nativeTrace.flush();310 }311 assert.equal(await pic.getTime(), finalTime, 'Inspection must not run extra rounds');312 latencies.sort((a, b) => a - b);313 const percentile = p => latencies[Math.min(latencies.length - 1, Math.ceil(latencies.length * p) - 1)];314 const rows = result.rows;315 const physicalCalls = sum(rows, 'sentBatches');316 assert.equal(physicalCalls, sum(rows, 'receivedBatches'), 'Every send must arrive exactly once in a healthy run');317 assert.equal(physicalCalls, sum(rows, 'acknowledgements'));318 assert.equal(sum(rows, 'callFailures'), 0n);319 // A healthy large batch can be acknowledged only in part when receive()320 // reaches its instruction budget. Offered suffixes are sent again; they321 // are not extra logical requests or business effects.322 const requestItems = expected.requests, resultItems = expected.requests;323 const scheduleItems = expected.children, eventItems = expected.children;324 assert.equal(sum(rows, 'processedRequests'), requestItems);325 assert.equal(sum(rows, 'processedNotifications'), scheduleItems);326 const offeredFrames = {requests: sum(rows, 'sentRequests'), results: sum(rows, 'sentResults'),327 schedules: sum(rows, 'sentNotifications'), events: sum(rows, 'sentEvents')};328 assert.ok(offeredFrames.requests >= requestItems); assert.ok(offeredFrames.results >= resultItems);329 assert.ok(offeredFrames.schedules >= scheduleItems); assert.ok(offeredFrames.events >= eventItems);330 const wireItems = requestItems + resultItems + scheduleItems + eventItems;331 const wireFramesOffered = Object.values(offeredFrames).reduce((n, count) => n + count, 0n);332 assert.equal(sum(rows, 'acceptedFrames'), wireItems);333 assert.equal(sum(rows, 'duplicateFrames'), 0n);334 const seconds = result.simulatedMillis / 1000;335 const roots = result.receipts.length - expected.rejected, workflows = Number(workflowSum(rows, 'succeeded')), dispatches = total(rows, 'total');336 const workflowSteps = Number(workflowSum(rows, 'completed'));337 if (cells.every(cell => cell.deferredAdmission) && latencies.length === workflows) {338 assert.equal(rootLatencies.length, roots, 'Every retained root must resolve to a receipt timestamp');339 }340 const instructionRounds = instructions(initial) === null ? null : result.samples.map((sample, i) => {341 const previous = i ? result.samples[i - 1].rows : initial;342 const perCanister = sample.rows.map((row, c) => row.rts.lifetimeInstructions - previous[c].rts.lifetimeInstructions);343 assert.ok(perCanister.every(n => n >= 0n));344 return {total: perCanister.reduce((sum, n) => sum + n, 0n), perCanister};345 });346 const totalInstructions = instructionRounds === null ? null : instructions(rows) - instructions(initial);347 const feed = result.samples[workload.arrivalRounds - 1].rows;348 const feedSeconds = workload.arrivalRounds * roundMillis / 1000;349 const warmupRounds = Math.min(20, Math.floor(workload.arrivalRounds / 5));350 const warmup = warmupRounds ? result.samples[warmupRounds - 1].rows : initial;351 const steadySeconds = (workload.arrivalRounds - warmupRounds) * roundMillis / 1000;352 const instructionProfile = profileDelta(profileBefore, await instructionProfiles(pic, cells));353 const pageAfter = pageMetadata ? await capturePageProfiles(pic, cells, pageMetadata, owner, directory, `${pagePrefix}-primary`) : null;354 const run = {mode, workloadName, canisters, cycles: workload.cyclesPerRound * workload.arrivalRounds, batchItems, replicaProfile,355 nativeMemoryTrace: nativeWindow ? (traceScope === 'complete' ? {scope: 'complete', boundaries: nativeWindow, primary: nativePrimary} : {window: nativeWindow, cohort: null}) : null,356 resourcesBefore, instructionProfile, pageProfile: pageMetadata ? {primary: summarizePageInterval(pageBefore, pageAfter, pageMetadata)} : null,357 replica: summarizeProfile(replicaProfile, workload.arrivalRounds, result.rounds),358 ingressPerSecond: workload.rate ?? null, ingressPerRound: workload.cyclesPerRound * mixSize, arrivalRounds: workload.arrivalRounds,359 ingressSubmitted: result.receipts.length, ingressRejected: expected.rejected,360 canisterLogEntries: logs.map(entries => entries.length), traps: 0, verifiedCanonicalBlocks, certifiedThrough,361 rootWorkflows: roots, childWorkflows: Number(expected.children), totalWorkflows: workflows,362 workflowSteps, workflowStepsPerSimulatedSecond: workflowSteps / seconds,363 processedEndpointMessages: endpointMessages(rows), endpointMessagesPerSimulatedSecond: Number(endpointMessages(rows)) / seconds,364 steadyArrivals: {fromRound: warmupRounds + 1, throughRound: workload.arrivalRounds, seconds: steadySeconds,365 endpointMessagesPerSecond: Number(endpointMessages(feed) - endpointMessages(warmup)) / steadySeconds,366 blocksPerSecond: (total(feed, 'total') - total(warmup, 'total')) / steadySeconds,367 pendingAtStart: total(warmup, 'pending'), pendingAtEnd: total(feed, 'pending')},368 taskAttempts: workflowSum(rows, 'attempts'),369 instructions: instructionRounds === null ? null : {total: totalInstructions, perCompletedStep: Number(totalInstructions) / workflowSteps,370 perBusinessBlock: Number(totalInstructions) / dispatches,371 meanPerRound: Number(totalInstructions) / result.rounds,372 peakAccountedRound: Math.max(...instructionRounds.map(r => Number(r.total))),373 peakAccountedCanisterRound: Math.max(...instructionRounds.flatMap(r => r.perCanister.map(Number))),374 peakHeapBytes: Math.max(...result.samples.flatMap(s => s.rows.map(r => Number(r.rts.heapBytes)))),375 peakLastMessageCollectorInstructions: Math.max(...result.samples.flatMap(s => s.rows.map(r => Number(r.rts.lastMessageCollectorInstructions))))},376 duringArrivals: {seconds: feedSeconds, admitted: total(feed, 'admitted'), rejected: total(feed, 'rejected'),377 processedEndpointMessages: endpointMessages(feed), endpointMessagesPerSecond: Number(endpointMessages(feed)) / feedSeconds,378 blocks: total(feed, 'total'), blocksPerSecond: total(feed, 'total') / feedSeconds,379 ingressBacklog: result.receipts.length - total(feed, 'admitted') - total(feed, 'rejected'),380 durableRequestsQueued: feed.reduce((n, row) => n + Number(row.queuedRequests ?? 0n), 0),381 pendingWorkflows: total(feed, 'pending'),382 completedWorkflows: workflowSum(feed, 'succeeded'), completedSteps: workflowSum(feed, 'completed'),383 stepsPerSecond: Number(workflowSum(feed, 'completed')) / feedSeconds,384 workflowsPerSecond: Number(workflowSum(feed, 'succeeded')) / feedSeconds},385 drainMillis: (result.rounds - workload.arrivalRounds) * roundMillis,386 dispatches, requestItems, resultItems, scheduleItems, eventItems, wireItems,387 offeredFrames, wireFramesOffered, reofferedFrames: wireFramesOffered - wireItems,388 physicalCalls, crossCanisterMessages: physicalCalls * 2n,389 unbatchedProtocolCalls: wireItems, callsSaved: wireItems - physicalCalls, packingFactor: Number(wireItems) / Number(physicalCalls),390 // Direct RPC would return the business result in its reply, unlike this391 // durable asynchronous channel. Keep that estimate separate and honest.392 directRpcEquivalentCalls: requestItems + scheduleItems + eventItems,393 rounds: result.rounds, simulatedMillis: result.simulatedMillis, wallMillis,394 rootWorkflowsPerSimulatedSecond: roots / seconds, workflowsPerSimulatedSecond: workflows / seconds,395 dispatchesPerSimulatedSecond: dispatches / seconds,396 physicalCallsPerSimulatedSecond: Number(physicalCalls) / seconds,397 crossCanisterMessagesPerSimulatedSecond: Number(physicalCalls * 2n) / seconds,398 logicalRequestsPerSimulatedSecond: Number(requestItems + scheduleItems) / seconds,399 cyclesCharged: balancesBefore.reduce((n, x, i) => n + x - balancesAfter[i], 0),400 peakPending: Math.max(...result.samples.map(s => s.rows.reduce((n, r) => n + Number(r.pending), 0))),401 peakPhysicalPerCanister: Math.max(...rows.map(r => Number(r.transport.peakActiveCalls))),402 peakCallbackUnits: Math.max(...result.samples.flatMap(s => s.rows.map(r => Number(r.scheduler.callbackUnits)))),403 deferredAdmission: cells.every(cell => cell.deferredAdmission),404 rootLatencyMillis: latencySummary(rootLatencies, 'request receipt to completion; excludes IC ingress queue', roots),405 queueDelayMillis: latencySummary(queueDelays, 'durable request receipt to workflow start', roots),406 latencyMillis: {scope: 'admission-to-completion', retainedExecutions: latencies.length, totalExecutions: workflows,407 p50: percentile(0.5), p95: percentile(0.95), maximum: latencies.at(-1)},408 schedulerTurns: rows.reduce((n, r) => n + r.scheduler.turns, 0n),409 instructionYields: rows.reduce((n, r) => n + r.scheduler.instructionYields, 0n),410 // Preserve the pre-arrival query already taken above, so allocation and411 // reclamation can be reported as workload deltas without extra queries.412 initialRts: initial.map(row => row.rts ?? null),413 perCanister: rows,414 roundsSeries: result.samples.map((s, i) => ({round: s.round,415 submitted: Math.min(s.round, workload.arrivalRounds) * workload.cyclesPerRound * mixSize,416 admitted: total(s.rows, 'admitted'), rejected: total(s.rows, 'rejected'), completedWorkflows: workflowSum(s.rows, 'succeeded'),417 completedSteps: workflowSum(s.rows, 'completed'),418 processedEndpointMessages: endpointMessages(s.rows), blocks: total(s.rows, 'total'),419 endpointMessagesPerSecond: Number(endpointMessages(s.rows) - endpointMessages(i ? result.samples[i - 1].rows : initial)) * 1000 / roundMillis,420 blocksPerSecond: (total(s.rows, 'total') - total(i ? result.samples[i - 1].rows : initial, 'total')) * 1000 / roundMillis,421 stepsPerSecond: Number(workflowSum(s.rows, 'completed') - (i ? workflowSum(result.samples[i - 1].rows, 'completed') : 0n)) * 1000 / roundMillis,422 accountedInstructions: instructionRounds?.[i].total ?? null, perCanisterInstructions: instructionRounds?.[i].perCanister ?? null,423 rts: s.rows.map(row => row.rts ?? null),424 pending: total(s.rows, 'pending'), sentBatches: sum(s.rows, 'sentBatches'),425 backlog: s.rows.reduce((n, r) => n + Number(r.transport.outgoing + r.transport.incoming), 0)})),426 };427 runs.push(run);428 // Persist the primary result before any tail or management call can fail.429 await output.write(JSON.stringify({manifest, runs}, json, 2) + '\n', report({manifest, runs}));430 try {431 run.maintenanceTail = await measureMaintenanceTail(pic, cells, {432 primary: run, balancesBefore: balancesAfter, timeBefore: finalTime,433 maxRounds: tailMaxRounds, regionStats: tailRegionStats,434 onRound: nativeTrace ? () => nativeTrace.flush() : undefined,435 });436 if (!run.maintenanceTail.finished) throw new Error(run.maintenanceTail.reason);437 } catch (error) {438 run.maintenanceTail = error.maintenanceTail ?? run.maintenanceTail ?? {finished: false, reason: String(error)};439 if (pageMetadata) {440 try {441 const pages = await capturePageProfiles(pic, cells, pageMetadata, owner, directory, `${pagePrefix}-tail-failed`);442 run.pageProfile.failedTail = summarizePageInterval(pageAfter, pages, pageMetadata);443 } catch (pageError) {run.pageProfile.failedTail = {error: String(pageError)}}444 }445 const path = new URL(`${stem}-${workload.rate ?? workload.cyclesPerRound}load-${batchItems}batch-tail-failed.json`, directory);446 await writeFile(path, JSON.stringify({manifest, workload, batchItems, primary: run, maintenanceTail: run.maintenanceTail}, json, 2) + '\n', {flag: 'wx'});447 await output.write(JSON.stringify({manifest, runs}, json, 2) + '\n', report({manifest, runs}));448 throw new Error(`Publication/maintenance tail failed; saved diagnostics in ${path.pathname}`, {cause: error});449 }450 run.completedWithMaintenance = combinedTotals(run, run.maintenanceTail);451 if (nativeTrace) {452 await nativeTrace.stop();453 if (traceScope === 'complete') {454 const completed = await nativeTrace.capture('completed');455 run.nativeMemoryTrace.completedWithMaintenance = completed;456 run.nativeMemoryTrace.tail = Object.fromEntries(Object.entries(completed.replicated).map(([key, value]) => {457 const difference = value - nativePrimary.replicated[key];458 assert.ok(difference >= 0);459 return [key, difference];460 }));461 nativeWindow.exportTimeMillis = await pic.getTime();462 } else run.nativeMemoryTrace.cohort = await nativeTrace.capture('cohort-completed');463 run.nativeMemoryTrace.exportedAfterRound = run.completedWithMaintenance.rounds;464 }465 if (pageMetadata) {466 const pageTail = await capturePageProfiles(pic, cells, pageMetadata, owner, directory, `${pagePrefix}-tail`);467 run.pageProfile.tail = summarizePageInterval(pageAfter, pageTail, pageMetadata);468 run.pageProfile.completedWithMaintenance = summarizePageInterval(pageBefore, pageTail, pageMetadata);469 }470 // These management updates can execute further rounds. Keep their memory471 // observations explicitly outside both measured intervals.472 run.resourcesAfterDrain = {...await resources(pic, cells, Principal.anonymous()),473 scope: 'Sampled after the measured publication/maintenance tail; management inspection can execute further replica rounds, outside both timed intervals. Logical allocation lengths, not live payload or resident RAM.'};474 console.log(JSON.stringify({maintenanceTail: {rounds: run.maintenanceTail.rounds,475 simulatedMillis: run.maintenanceTail.simulatedMillis, cyclesCharged: run.maintenanceTail.cyclesCharged,476 messageInstructions: run.maintenanceTail.messageInstructions?.total ?? null,477 instructions: run.maintenanceTail.instructions?.total ?? null,478 certifiedThrough: run.maintenanceTail.certifiedThrough}, completedWithMaintenance: run.completedWithMaintenance}, json));479 console.log(JSON.stringify({canisters, rate: workload.rate, batchItems, roots, rounds: run.rounds, calls: physicalCalls, saved: run.callsSaved,480 packing: run.packingFactor.toFixed(2), workflowsPerSimulatedSecond: run.workflowsPerSimulatedSecond.toFixed(2),481 workflowStepsPerSimulatedSecond: run.workflowStepsPerSimulatedSecond.toFixed(2),482 endpointMessagesPerSecond: run.endpointMessagesPerSimulatedSecond.toFixed(2), blocksPerSecond: run.dispatchesPerSimulatedSecond.toFixed(2)}, json));483 await output.write(JSON.stringify({manifest, runs}, json, 2) + '\n', report({manifest, runs}));484 } finally {485 try {486 if (nativeTrace && !nativeTrace.has(traceScope === 'complete' ? 'completed' : 'cohort-completed')) {487 try {await nativeTrace.capture('failed')} catch (error) {console.error('Could not preserve failed native trace:', error)}488 }489 if (nativeTrace) await nativeTrace.stop();490 } finally {await session.shutdown()}491 }492}493} finally {await output.close()}