From b32b09f56b8cabfc3cdf5c8d3aa1c04e90da033a Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 28 Aug 2026 18:54:40 +0000 Subject: [PATCH] lib: add runId, fileRunId, entryFile, namePath to node:bench Signed-off-by: James M Snell Assisted-by: Opencode PR-URL: https://github.com/nodejs/node/pull/65631 Reviewed-By: Filip Skokan --- doc/api/bench.md | 45 +++++-- lib/internal/bench_runner/benchmark.js | 20 ++- lib/internal/bench_runner/cli.js | 90 +++++++++++++- lib/internal/bench_runner/harness.js | 117 +++++++++++++++--- .../bench-runner/identity-child-a.cjs | 11 ++ .../bench-runner/identity-child-b.cjs | 11 ++ .../bench-runner/identity-entry-a.cjs | 10 ++ .../bench-runner/identity-entry-b.cjs | 10 ++ test/fixtures/bench-runner/identity-hook.cjs | 9 ++ .../bench-runner/identity-preload.cjs | 9 ++ .../fixtures/bench-runner/identity-shared.cjs | 11 ++ test/fixtures/bench-runner/identity-suite.cjs | 10 ++ .../bench-runner/malformed-record.cjs | 13 +- test/parallel/test-bench-cli.js | 101 +++++++++++++++ test/parallel/test-bench-create-runner.js | 10 ++ 15 files changed, 440 insertions(+), 37 deletions(-) create mode 100644 test/fixtures/bench-runner/identity-child-a.cjs create mode 100644 test/fixtures/bench-runner/identity-child-b.cjs create mode 100644 test/fixtures/bench-runner/identity-entry-a.cjs create mode 100644 test/fixtures/bench-runner/identity-entry-b.cjs create mode 100644 test/fixtures/bench-runner/identity-hook.cjs create mode 100644 test/fixtures/bench-runner/identity-preload.cjs create mode 100644 test/fixtures/bench-runner/identity-shared.cjs create mode 100644 test/fixtures/bench-runner/identity-suite.cjs diff --git a/doc/api/bench.md b/doc/api/bench.md index 7cb5720ffe2..9c24d04ee4f 100644 --- a/doc/api/bench.md +++ b/doc/api/bench.md @@ -137,6 +137,12 @@ Benchmark files passed to `--bench` should declare benchmarks but must not call `--bench-warmup`, `--bench-reporter`, and `--bench-reporter-destination`. See the [command-line options documentation][] for details. +Preload modules passed through `--require` or `--import` should not declare +benchmarks. Such declarations are not associated with an entry file and have +an `entryFile` value of `null`. Their `fileRunId` identifies the runner or child +execution in which they occurred. With process isolation, a preload is evaluated +and its declarations run once for every benchmark child process. + ## Benchmark reporters The built-in reporters are available from the scheme-only @@ -262,9 +268,19 @@ benchmark. Later benchmarks continue to run. A timeout or abort cannot interrupt synchronous JavaScript and does not forcibly cancel asynchronous work that ignores `context.signal`. -The stable `benchId` is based on the source file, hierarchical suite and -benchmark names, and canonicalized parameters. Declaring the same identity -more than once reports an error rather than merging the samples. +The `benchId` is based on the declaration source file, hierarchical suite and +benchmark names, and canonicalized parameters. It is stable for repeated runs +from the same source location, but the embedded source value is not normalized +across checkout roots, module formats, operating systems, or path casing. + +Execution scope is represented separately. A `runId` identifies one logical +run, while `fileRunId` identifies a file runner or child execution within that +run. The `entryFile` field records which entry-file import caused a declaration +and is `null` for declarations made by preload modules. +The same `benchId` can therefore occur under multiple `fileRunId` values when +entry files use a shared declaration helper. Declaring the same `benchId` more +than once within one file execution scope reports an error rather than merging +the samples. ### `bench.skip([name][, options], fn)` @@ -537,14 +553,20 @@ The events are emitted in execution order: * `'bench:diagnostic'` * `'bench:summary'` -Every benchmark-scoped event contains `benchId` and `parentId`. +Every benchmark-scoped event contains `runId`, `fileRunId`, `entryFile`, +`benchId`, `parentId`, and `namePath`. `runId` and `fileRunId` are opaque and +change between runs. `entryFile` identifies the top-level benchmark file whose +loading caused the declaration, while `file` identifies the source location of +the declaration itself. `parentId` is based on the containing suite's source +file and hierarchical name path. + `'bench:complete'` data contains a [benchmark result][]. A failed result has an additional `error` property and may contain samples recorded before the error. A skipped result has an additional `skip` property and an empty `samples` array. `'bench:diagnostic'` reports suite and hook errors. `'bench:summary'` -contains overall `success`, `counts`, `duration_ns`, and `file` properties. The -`file` is {string|null}; it is `null` when the summary aggregates multiple -files. +contains overall `runId`, `fileRunId`, `entryFile`, `success`, `counts`, +`duration_ns`, and `file` properties. `fileRunId`, `entryFile`, and `file` are +{string|null}; they are `null` when the summary aggregates multiple files. ## Sample result @@ -560,10 +582,15 @@ Each measured sample has the following properties: A completed benchmark result contains: -* `benchId` {string} The stable benchmark identity. +* `runId` {string} The opaque logical run identity. +* `fileRunId` {string} The opaque file runner or child execution identity. +* `entryFile` {string|null} The top-level file that caused this declaration. +* `benchId` {string} The stable declaration identity within the same source + layout. * `parentId` {string|null} The stable containing suite identity. * `name` {string} The benchmark name. -* `file` {string} The source file. +* `namePath` {string\[]} The hierarchical suite and benchmark names. +* `file` {string} The declaration source file. * `line` {number} The source line. * `column` {number} The source column. * `tags` {string\[]} The inherited canonical tags. diff --git a/lib/internal/bench_runner/benchmark.js b/lib/internal/bench_runner/benchmark.js index d3c55c1b2ef..dae60f6e059 100644 --- a/lib/internal/bench_runner/benchmark.js +++ b/lib/internal/bench_runner/benchmark.js @@ -48,6 +48,7 @@ const { structuredClone } = require('internal/worker/js_transferable'); const { bigint: hrtime } = process.hrtime; const kDefaultSamples = 30; const kDefaultWarmup = 0; +const kEmptyNamePath = ObjectFreeze([]); const kEmptyParams = ObjectFreeze({ __proto__: null }); const kEmptyTags = ObjectFreeze([]); @@ -163,10 +164,19 @@ class Suite extends AsyncResource { this.name = name; this.fn = fn; this.loc = createLocation(loc, harness.entryFile); + this.isRoot = isRoot; + this.fileScope = isRoot ? null : + (parent.isRoot ? harness.getFileScope() : parent.fileScope); + this.namePath = isRoot ? kEmptyNamePath : + ObjectFreeze(getNamePath(parent, name)); + this.suiteId = isRoot ? null : JSONStringify([ + this.loc.file, + this.namePath, + ]); + this.parentId = isRoot || parent.isRoot ? null : parent.suiteId; this.only = validated.only; this.skip = validated.skip; this.tags = validated.tags; - this.isRoot = isRoot; this.children = []; this.hooks = { __proto__: null, @@ -214,17 +224,15 @@ class Bench extends AsyncResource { this.warmup = warmup; this.timeout = timeout; this.outerSignal = signal; - this.namePath = getNamePath(parent, name); + this.fileScope = parent.isRoot ? harness.getFileScope() : parent.fileScope; + this.namePath = ObjectFreeze(getNamePath(parent, name)); this.fullName = ArrayPrototypeJoin(this.namePath, ' '); this.benchId = JSONStringify([ this.loc.file, this.namePath, this.params, ]); - this.parentId = parent.isRoot ? null : JSONStringify([ - this.loc.file, - getNamePath(parent.parent, parent.name), - ]); + this.parentId = parent.suiteId; this.finished = false; this.result = null; this.completion = PromiseWithResolvers(); diff --git a/lib/internal/bench_runner/cli.js b/lib/internal/bench_runner/cli.js index ce54be0e1e2..6c717aab6ff 100644 --- a/lib/internal/bench_runner/cli.js +++ b/lib/internal/bench_runner/cli.js @@ -2,6 +2,7 @@ const { ArrayFrom, + ArrayIsArray, ArrayPrototypeFilter, ArrayPrototypeIncludes, ArrayPrototypeJoin, @@ -32,6 +33,9 @@ const { kBenchmarksStreamDrain, } = require('internal/bench_runner/benchmarks_stream'); const { + configureRunScope, + createRunId, + runInFileScope, runBenchmarks, } = require('internal/bench_runner/harness'); const { deserializeError, serializeError } = require('internal/error_serdes'); @@ -116,6 +120,19 @@ function createChildFileList(patterns, cwd) { return null; } +function createFileScopes(files, options) { + const scopes = []; + for (let i = 0; i < files.length; i++) { + ArrayPrototypePush(scopes, { + __proto__: null, + entryFile: resolve(options.cwd, files[i]), + fileRunId: options.isChild && i === 0 && + options.fileRunId !== undefined ? options.fileRunId : createRunId(), + }); + } + return scopes; +} + function parseNamePattern(value) { if (value.length === 0) return undefined; try { @@ -163,11 +180,15 @@ function parseCommandLine() { __proto__: null, cwd: process.cwd(), destinations, + fileRunId: isChild && process.env.NODE_BENCH_FILE_RUN_ID ? + process.env.NODE_BENCH_FILE_RUN_ID : undefined, isChild, isolation: getOptionValue('--bench-isolation'), namePattern: parseNamePattern(getOptionValue('--bench-name-pattern')), namePatternSource: getOptionValue('--bench-name-pattern'), reporters, + runId: isChild && process.env.NODE_BENCH_RUN_ID ? + process.env.NODE_BENCH_RUN_ID : undefined, samples, warmup, }; @@ -292,7 +313,24 @@ function deserializeRecord(record) { function validateRecord(record) { if (record === null || typeof record !== 'object' || !kEventTypes.has(record.type) || record.data === null || - typeof record.data !== 'object') { + typeof record.data !== 'object' || + typeof record.data.runId !== 'string' || + (record.data.fileRunId !== null && + typeof record.data.fileRunId !== 'string') || + (record.data.entryFile !== null && + typeof record.data.entryFile !== 'string')) { + throw new ERR_INVALID_ARG_VALUE( + 'benchmark child message', record, 'is not a valid benchmark record'); + } + if ((record.type === 'bench:start' || record.type === 'bench:sample' || + record.type === 'bench:complete') && + (typeof record.data.benchId !== 'string' || + (record.data.parentId !== null && + typeof record.data.parentId !== 'string') || + typeof record.data.name !== 'string' || + !ArrayIsArray(record.data.namePath) || + ArrayPrototypeSome( + record.data.namePath, (name) => typeof name !== 'string'))) { throw new ERR_INVALID_ARG_VALUE( 'benchmark child message', record, 'is not a valid benchmark record'); } @@ -345,7 +383,8 @@ async function loadBenchmarkFiles(files, options, modules, onRecord) { for (let i = 0; i < files.length; i++) { const file = resolve(options.cwd, files[i]); try { - await loader.import(pathToFileURL(file), parentURL, kEmptyObject); + await runInFileScope(options.fileScopes[i], () => + loader.import(pathToFileURL(file), parentURL, kEmptyObject)); } catch (error) { loadFailed = true; await onRecord({ @@ -353,6 +392,8 @@ async function loadBenchmarkFiles(files, options, modules, onRecord) { type: 'bench:diagnostic', data: { __proto__: null, + runId: options.runId, + ...options.fileScopes[i], message: error?.message ?? String(error), error, level: 'error', @@ -377,6 +418,10 @@ async function loadBenchmarkFiles(files, options, modules, onRecord) { if (record.type === 'bench:summary') { record.data.file = files.length === 1 ? resolve(options.cwd, files[0]) : null; + record.data.fileRunId = files.length === 1 ? + options.fileScopes[0].fileRunId : null; + record.data.entryFile = files.length === 1 ? + options.fileScopes[0].entryFile : null; summary = record.data; } await onRecord(record); @@ -445,7 +490,7 @@ function getChildArgs(path, options) { return args; } -async function runChild(path, options, onRecord) { +async function runChild(path, options, scope, onRecord) { const child = spawn(process.execPath, getChildArgs(path, options), { __proto__: null, cwd: options.cwd, @@ -453,6 +498,8 @@ async function runChild(path, options, onRecord) { __proto__: null, ...process.env, NODE_BENCH_CONTEXT: 'child', + NODE_BENCH_FILE_RUN_ID: scope.fileRunId, + NODE_BENCH_RUN_ID: options.runId, }, serialization: 'advanced', stdio: ['inherit', 'pipe', 'pipe', 'ipc'], @@ -487,6 +534,8 @@ async function runChild(path, options, onRecord) { type: 'bench:diagnostic', data: { __proto__: null, + runId: options.runId, + ...scope, message, level: 'info', file: path, @@ -506,8 +555,15 @@ async function runChild(path, options, onRecord) { child.on('message', (message) => { if (message?.type !== kChildMessageType) return; try { - const pending = handleRecord( - deserializeRecord(validateRecord(message.record))); + const record = deserializeRecord(validateRecord(message.record)); + record.data.runId = options.runId; + if (record.data.fileRunId !== null) { + record.data.fileRunId = scope.fileRunId; + } + if (record.data.entryFile !== null) { + record.data.entryFile = scope.entryFile; + } + const pending = handleRecord(record); trackPending(pending); } catch (error) { protocolError = error; @@ -533,10 +589,11 @@ async function runIsolated(files, options, output) { for (let i = 0; i < files.length; i++) { const path = files[i]; + const scope = options.fileScopes[i]; let childSummary; let result; try { - result = await runChild(path, options, (record) => { + result = await runChild(path, options, scope, (record) => { if (record.type === 'bench:summary') { childSummary = record.data; return; @@ -547,6 +604,8 @@ async function runIsolated(files, options, output) { success = false; output.diagnostic({ __proto__: null, + runId: options.runId, + ...scope, message: error.message, error, level: 'error', @@ -570,6 +629,8 @@ async function runIsolated(files, options, output) { `exit code ${result.code}` : `signal ${result.signal}`; output.diagnostic({ __proto__: null, + runId: options.runId, + ...scope, message: `Benchmark file '${path}' failed with ${status}`, level: 'error', file: path, @@ -578,8 +639,12 @@ async function runIsolated(files, options, output) { } } + const scope = files.length === 1 ? options.fileScopes[0] : null; const summary = { __proto__: null, + runId: options.runId, + fileRunId: scope?.fileRunId ?? null, + entryFile: scope?.entryFile ?? null, success: success && (process.exitCode ?? 0) === 0, counts, duration_ns: hrtime() - start, @@ -596,6 +661,19 @@ async function run(patterns) { createBenchmarkFileList(patterns, options.cwd); if (files === null) return { __proto__: null, success: false }; + options.runId ??= createRunId(); + options.fileScopes = createFileScopes(files, options); + const scope = files.length === 1 ? options.fileScopes[0] : { + __proto__: null, + entryFile: null, + fileRunId: options.runId, + }; + configureRunScope({ + __proto__: null, + runId: options.runId, + ...scope, + }); + if (options.isChild) { try { const modules = await loadUserImports(options); diff --git a/lib/internal/bench_runner/harness.js b/lib/internal/bench_runner/harness.js index 59b85860c2e..09c06245c23 100644 --- a/lib/internal/bench_runner/harness.js +++ b/lib/internal/bench_runner/harness.js @@ -6,6 +6,7 @@ const { ArrayPrototypeSlice, BigInt, FunctionPrototypeCall, + JSONStringify, MathCeil, Promise, PromisePrototypeThen, @@ -16,6 +17,7 @@ const { RegExpPrototypeExec, SafeMap, SafePromiseRace, + String, SymbolDispose, } = primordials; const { getCallerLocation } = internalBinding('util'); @@ -59,6 +61,11 @@ const { const { bigint: hrtime } = process.hrtime; const kHookNames = ['after', 'afterEach', 'before', 'beforeEach']; const kIsCliRunner = getOptionValue('--bench'); +let nextRunId = 0; + +function createRunId() { + return `${process.pid}:${String(hrtime())}:${nextRunId++}`; +} function eventLoopTurn() { return new Promise((resolve) => setImmediate(resolve)); @@ -78,6 +85,7 @@ class Harness { #buildPromises = []; #duplicateErrors = new SafeMap(); #explicitRun = false; + #fileScopeStorage = new AsyncLocalStorage(); #hasOnly = false; #runPromise = null; #scheduled = false; @@ -96,7 +104,9 @@ class Harness { yieldBetweenSamples, 'options.yieldBetweenSamples'); this.#autoRun = autoRun; this.#yieldBetweenSamples = yieldBetweenSamples; - this.entryFile = process.argv?.[1]; + this.runId = createRunId(); + this.fileRunId = this.runId; + this.entryFile = process.argv?.[1] ?? null; this.stream = new BenchmarksStream(); this.state = 'collecting'; this.namePattern = null; @@ -122,6 +132,24 @@ class Harness { ); } + getFileScope() { + return this.#fileScopeStorage.getStore() ?? null; + } + + runInFileScope(scope, fn) { + return this.#fileScopeStorage.run(scope, fn); + } + + setRunScope({ entryFile, fileRunId, runId }) { + if (this.state !== 'collecting') { + throw new ERR_INVALID_STATE( + 'benchmark execution scope cannot change after execution has started'); + } + this.entryFile = entryFile; + this.fileRunId = fileRunId; + this.runId = runId; + } + #ensureCollecting() { if (this.state === 'building' && this.#storage.getStore() instanceof Suite) return; @@ -178,6 +206,7 @@ class Harness { const parent = this.#getParent(); ArrayPrototypePush(parent.hooks[name], { __proto__: null, + fileScope: parent.isRoot ? this.getFileScope() : parent.fileScope, fn, loc: getCallerLocation(), }); @@ -312,9 +341,13 @@ class Harness { if (!(node instanceof Bench)) return; this.counts.total++; - const existing = identities.get(node.benchId); + const identity = JSONStringify([ + this.#getRecordScope(node).fileRunId, + node.benchId, + ]); + const existing = identities.get(identity); if (existing === undefined) { - identities.set(node.benchId, node); + identities.set(identity, node); } else { this.#duplicateErrors.set(node, new ERR_INVALID_STATE( `duplicate benchmark identity for "${node.fullName}"`)); @@ -378,13 +411,48 @@ class Harness { name: suite.name, signal: this.outerSignal, }; - await this.#runHooks(suite, name, suite, suite, context); + const hooks = suite.hooks[name]; + for (let i = 0; i < hooks.length; i++) { + try { + await this.#invoke(suite, suite, hooks[i].fn, [context]); + } catch (error) { + return { __proto__: null, error, hook: hooks[i] }; + } + } + return null; } - #diagnostic(error, loc, level = 'info') { + #getRecordScope(node = undefined) { + const scope = node?.fileScope; + if (scope !== null && scope !== undefined) { + return { + __proto__: null, + runId: this.runId, + fileRunId: scope.fileRunId, + entryFile: scope.entryFile, + }; + } + if (node !== undefined && kIsCliRunner) { + return { + __proto__: null, + runId: this.runId, + fileRunId: this.fileRunId, + entryFile: null, + }; + } + return { + __proto__: null, + runId: this.runId, + fileRunId: this.fileRunId, + entryFile: this.entryFile, + }; + } + + #diagnostic(error, loc, level = 'info', node = undefined) { this.success = false; this.stream.diagnostic({ __proto__: null, + ...this.#getRecordScope(node), message: error?.message ?? `${error}`, error, level, @@ -410,7 +478,7 @@ class Harness { async #executeSuite(suite) { if (suite.buildError !== null) { - this.#diagnostic(suite.buildError, suite.loc, 'error'); + this.#diagnostic(suite.buildError, suite.loc, 'error', suite); await this.#completeSubtree(suite, suite.buildError); suite.finished = true; suite.completion.resolve(); @@ -421,11 +489,11 @@ class Harness { const active = this.#suiteHasActiveBench(suite); let beforeError; if (active) { - try { - await this.#runSuiteHooks(suite, 'before'); - } catch (error) { - beforeError = error; - this.#diagnostic(error, suite.loc, 'error'); + const failure = await this.#runSuiteHooks(suite, 'before'); + if (failure !== null) { + beforeError = failure.error; + this.#diagnostic( + failure.error, failure.hook.loc, 'error', failure.hook); } } @@ -443,10 +511,10 @@ class Harness { } if (active) { - try { - await this.#runSuiteHooks(suite, 'after'); - } catch (error) { - this.#diagnostic(error, suite.loc, 'error'); + const failure = await this.#runSuiteHooks(suite, 'after'); + if (failure !== null) { + this.#diagnostic( + failure.error, failure.hook.loc, 'error', failure.hook); } } suite.finished = true; @@ -537,9 +605,11 @@ class Harness { #createResult(benchmark, samples, extra = kEmptyObject) { return { __proto__: null, + ...this.#getRecordScope(benchmark), benchId: benchmark.benchId, parentId: benchmark.parentId, name: benchmark.name, + namePath: ArrayPrototypeSlice(benchmark.namePath), file: benchmark.loc.file, line: benchmark.loc.line, column: benchmark.loc.column, @@ -595,9 +665,11 @@ class Harness { this.stream.start({ __proto__: null, + ...this.#getRecordScope(benchmark), benchId: benchmark.benchId, parentId: benchmark.parentId, name: benchmark.name, + namePath: ArrayPrototypeSlice(benchmark.namePath), file: benchmark.loc.file, line: benchmark.loc.line, column: benchmark.loc.column, @@ -648,9 +720,11 @@ class Harness { ArrayPrototypePush(samples, sample); this.stream.sample({ __proto__: null, + ...this.#getRecordScope(benchmark), benchId: benchmark.benchId, parentId: benchmark.parentId, name: benchmark.name, + namePath: ArrayPrototypeSlice(benchmark.namePath), index: i - warmup, ...sample, }); @@ -697,6 +771,7 @@ class Harness { const duration = startTime === undefined ? 0n : hrtime() - startTime; this.stream.summary({ __proto__: null, + ...this.#getRecordScope(), success: this.success, counts: this.counts, duration_ns: duration, @@ -716,6 +791,7 @@ class Harness { this.state = 'building'; const startTime = hrtime(); await this.#waitForBuild(); + this.#fileScopeStorage.disable(); this.#prepare(); this.state = 'running'; await this.#executeSuite(this.root); @@ -780,6 +856,14 @@ function createRunner(options = kEmptyObject) { }; } +function configureRunScope(scope) { + lazyHarness().setRunScope(scope); +} + +function runInFileScope(scope, fn) { + return lazyHarness().runInFileScope(scope, fn); +} + function runBenchmarks(options, force) { return lazyHarness().run(options, force); } @@ -791,7 +875,10 @@ module.exports = { before: createHook(kHookNames[2], lazyHarness), beforeEach: createHook(kHookNames[3], lazyHarness), bench, + configureRunScope, + createRunId, createRunner, + runInFileScope, runBenchmarks, suite, }; diff --git a/test/fixtures/bench-runner/identity-child-a.cjs b/test/fixtures/bench-runner/identity-child-a.cjs new file mode 100644 index 00000000000..2b8c4b728b1 --- /dev/null +++ b/test/fixtures/bench-runner/identity-child-a.cjs @@ -0,0 +1,11 @@ +'use strict'; + +const { bench } = require('node:bench'); + +module.exports = function declareChildA() { + bench('child a', { samples: 1 }, (b) => { + b.start(); + process.hrtime.bigint(); + b.end(1); + }); +}; diff --git a/test/fixtures/bench-runner/identity-child-b.cjs b/test/fixtures/bench-runner/identity-child-b.cjs new file mode 100644 index 00000000000..249bcdcfc4f --- /dev/null +++ b/test/fixtures/bench-runner/identity-child-b.cjs @@ -0,0 +1,11 @@ +'use strict'; + +const { bench } = require('node:bench'); + +module.exports = function declareChildB() { + bench('child b', { samples: 1 }, (b) => { + b.start(); + process.hrtime.bigint(); + b.end(1); + }); +}; diff --git a/test/fixtures/bench-runner/identity-entry-a.cjs b/test/fixtures/bench-runner/identity-entry-a.cjs new file mode 100644 index 00000000000..2892ea3f3ec --- /dev/null +++ b/test/fixtures/bench-runner/identity-entry-a.cjs @@ -0,0 +1,10 @@ +'use strict'; + +const { suite } = require('node:bench'); +const { setImmediate } = require('timers/promises'); +const registerSharedIdentity = require('./identity-shared.cjs'); + +suite('shared suite', async () => { + await setImmediate(); + registerSharedIdentity(); +}); diff --git a/test/fixtures/bench-runner/identity-entry-b.cjs b/test/fixtures/bench-runner/identity-entry-b.cjs new file mode 100644 index 00000000000..2892ea3f3ec --- /dev/null +++ b/test/fixtures/bench-runner/identity-entry-b.cjs @@ -0,0 +1,10 @@ +'use strict'; + +const { suite } = require('node:bench'); +const { setImmediate } = require('timers/promises'); +const registerSharedIdentity = require('./identity-shared.cjs'); + +suite('shared suite', async () => { + await setImmediate(); + registerSharedIdentity(); +}); diff --git a/test/fixtures/bench-runner/identity-hook.cjs b/test/fixtures/bench-runner/identity-hook.cjs new file mode 100644 index 00000000000..14c4cacd9cd --- /dev/null +++ b/test/fixtures/bench-runner/identity-hook.cjs @@ -0,0 +1,9 @@ +'use strict'; + +const { before, bench } = require('node:bench'); + +before(() => { + throw new Error('scoped hook failed'); +}); + +bench('scoped hook benchmark', { samples: 1 }, () => {}); diff --git a/test/fixtures/bench-runner/identity-preload.cjs b/test/fixtures/bench-runner/identity-preload.cjs new file mode 100644 index 00000000000..ed55e627527 --- /dev/null +++ b/test/fixtures/bench-runner/identity-preload.cjs @@ -0,0 +1,9 @@ +'use strict'; + +const { bench } = require('node:bench'); + +bench('preload identity', { samples: 1 }, (b) => { + b.start(); + process.hrtime.bigint(); + b.end(1); +}); diff --git a/test/fixtures/bench-runner/identity-shared.cjs b/test/fixtures/bench-runner/identity-shared.cjs new file mode 100644 index 00000000000..40ce0f27be2 --- /dev/null +++ b/test/fixtures/bench-runner/identity-shared.cjs @@ -0,0 +1,11 @@ +'use strict'; + +const { bench } = require('node:bench'); + +module.exports = function registerSharedIdentity() { + bench('shared identity', { samples: 1 }, (b) => { + b.start(); + process.hrtime.bigint(); + b.end(1); + }); +}; diff --git a/test/fixtures/bench-runner/identity-suite.cjs b/test/fixtures/bench-runner/identity-suite.cjs new file mode 100644 index 00000000000..53c5982ce1a --- /dev/null +++ b/test/fixtures/bench-runner/identity-suite.cjs @@ -0,0 +1,10 @@ +'use strict'; + +const { suite } = require('node:bench'); +const declareChildA = require('./identity-child-a.cjs'); +const declareChildB = require('./identity-child-b.cjs'); + +suite('cross-module suite', () => { + declareChildA(); + declareChildB(); +}); diff --git a/test/fixtures/bench-runner/malformed-record.cjs b/test/fixtures/bench-runner/malformed-record.cjs index 5744bf1ea4b..ab8b4bb84dc 100644 --- a/test/fixtures/bench-runner/malformed-record.cjs +++ b/test/fixtures/bench-runner/malformed-record.cjs @@ -2,13 +2,24 @@ const common = require('../../common'); -const record = process.env.NODE_BENCH_MALFORMED_RECORD === 'summary' ? { +const kind = process.env.NODE_BENCH_MALFORMED_RECORD; +const record = kind === 'summary' ? { type: 'bench:summary', data: { counts: { completed: 0, failed: 0, skipped: 0, total: -1 }, duration_ns: 1n, + entryFile: __filename, + fileRunId: process.env.NODE_BENCH_FILE_RUN_ID, + runId: process.env.NODE_BENCH_RUN_ID, success: true, }, +} : kind === 'identity' ? { + type: 'bench:complete', + data: { + entryFile: __filename, + fileRunId: process.env.NODE_BENCH_FILE_RUN_ID, + runId: process.env.NODE_BENCH_RUN_ID, + }, } : null; process.send?.({ type: 'node:bench:record', record }); diff --git a/test/parallel/test-bench-cli.js b/test/parallel/test-bench-cli.js index 28dcc8b2dbb..8130bf38dc9 100644 --- a/test/parallel/test-bench-cli.js +++ b/test/parallel/test-bench-cli.js @@ -121,6 +121,106 @@ for (const { patterns, message } of [ }); } +for (const isolation of ['process', 'none']) { + const result = spawnBench([ + `--bench-isolation=${isolation}`, + '--bench-reporter=json', + fixtures.path('bench-runner/identity-entry-*.cjs'), + ]); + assert.strictEqual(result.status, 0); + const records = parseRecords(result); + const completions = records.filter( + ({ type }) => type === 'bench:complete').map(({ data }) => data); + const summary = records.at(-1).data; + + assert.strictEqual(completions.length, 2); + assert.strictEqual(completions[0].benchId, completions[1].benchId); + assert.strictEqual(completions[0].runId, completions[1].runId); + assert.strictEqual(completions[0].runId, summary.runId); + assert.notStrictEqual( + completions[0].fileRunId, completions[1].fileRunId); + assert.deepStrictEqual(completions.map(({ entryFile }) => entryFile), [ + fixtures.path('bench-runner/identity-entry-a.cjs'), + fixtures.path('bench-runner/identity-entry-b.cjs'), + ]); + assert.deepStrictEqual(completions.map(({ namePath }) => namePath), [ + ['shared suite', 'shared identity'], + ['shared suite', 'shared identity'], + ]); + assert.strictEqual(summary.fileRunId, null); + assert.strictEqual(summary.entryFile, null); +} + +{ + const result = spawnBench([ + '--bench-reporter=json', + fixtures.path('bench-runner/identity-suite.cjs'), + ]); + assert.strictEqual(result.status, 0); + const records = parseRecords(result); + const completions = records.filter( + ({ type }) => type === 'bench:complete').map(({ data }) => data); + const parentId = JSON.stringify([ + fixtures.path('bench-runner/identity-suite.cjs'), + ['cross-module suite'], + ]); + + assert.deepStrictEqual(completions.map(({ name }) => name), [ + 'child a', + 'child b', + ]); + assert(completions.every((completion) => + completion.parentId === parentId)); + assert.deepStrictEqual(completions.map(({ namePath }) => namePath), [ + ['cross-module suite', 'child a'], + ['cross-module suite', 'child b'], + ]); + assert(completions.every(({ entryFile }) => + entryFile === fixtures.path('bench-runner/identity-suite.cjs'))); +} + +for (const isolation of ['process', 'none']) { + const result = spawnBench([ + '--require', fixtures.path('bench-runner/identity-preload.cjs'), + `--bench-isolation=${isolation}`, + '--bench-reporter=json', + fixtures.path('bench-runner/identity-entry-*.cjs'), + ]); + assert.strictEqual(result.status, 0); + const records = parseRecords(result); + const preloads = records.filter( + ({ type, data }) => type === 'bench:complete' && + data.name === 'preload identity').map(({ data }) => data); + assert.strictEqual(preloads.length, isolation === 'process' ? 2 : 1); + assert.strictEqual( + new Set(preloads.map(({ fileRunId }) => fileRunId)).size, + preloads.length, + ); + assert(preloads.every(({ entryFile }) => entryFile === null)); + assert(preloads.every( + ({ runId }) => runId === records.at(-1).data.runId)); +} + +{ + const result = spawnBench([ + '--bench-isolation=none', + '--bench-reporter=json', + fixtures.path('bench-runner/a.cjs'), + fixtures.path('bench-runner/identity-hook.cjs'), + ]); + assert.strictEqual(result.status, 1); + const records = parseRecords(result); + const diagnostic = records.find( + ({ type, data }) => type === 'bench:diagnostic' && + data.message === 'scoped hook failed').data; + const completion = records.find( + ({ type, data }) => type === 'bench:complete' && + data.name === 'scoped hook benchmark').data; + assert.strictEqual(diagnostic.entryFile, + fixtures.path('bench-runner/identity-hook.cjs')); + assert.strictEqual(diagnostic.fileRunId, completion.fileRunId); +} + { const result = spawnBench([ '--bench-reporter=json', @@ -297,6 +397,7 @@ for (const isolation of ['process', 'none']) { for (const { kind, message } of [ { kind: 'record', message: /not a valid benchmark record/ }, + { kind: 'identity', message: /not a valid benchmark record/ }, { kind: 'summary', message: /not a valid benchmark summary/ }, ]) { const result = spawnBench([ diff --git a/test/parallel/test-bench-create-runner.js b/test/parallel/test-bench-create-runner.js index a7194d002d5..5540a189ad5 100644 --- a/test/parallel/test-bench-create-runner.js +++ b/test/parallel/test-bench-create-runner.js @@ -54,6 +54,16 @@ const { setImmediate } = require('timers/promises'); assert.strictEqual(secondResult.samples.length, 1); assert.strictEqual(firstResult.error, undefined); assert.strictEqual(secondResult.error, undefined); + assert.strictEqual(firstResult.benchId, secondResult.benchId); + assert.notStrictEqual(firstResult.runId, secondResult.runId); + assert.strictEqual(firstResult.fileRunId, firstResult.runId); + assert.strictEqual(secondResult.fileRunId, secondResult.runId); + assert.strictEqual(firstResult.entryFile, process.argv[1]); + assert.strictEqual(secondResult.entryFile, process.argv[1]); + assert.deepStrictEqual(firstResult.namePath, ['same name']); + assert.deepStrictEqual(secondResult.namePath, ['same name']); + assert(firstRecords.every(({ data }) => data.runId === firstResult.runId)); + assert(secondRecords.every(({ data }) => data.runId === secondResult.runId)); assert.strictEqual( firstRecords.filter(({ type }) => type === 'bench:summary').length, 1); assert.strictEqual(