diff --git a/resources/benchmark-runner.mjs b/resources/benchmark-runner.mjs index 76adecb6f..7761e74ce 100644 --- a/resources/benchmark-runner.mjs +++ b/resources/benchmark-runner.mjs @@ -509,10 +509,14 @@ export class BenchmarkRunner { await this._wakeLock.release(); } + _suiteRunnerType(suite, runParams = params) { + return suite.type ?? ((runParams.useAsyncSteps && "async") || (runParams.measurementMethod === "continuous" && "continuous") || "default"); + } + async runSuite(suite) { // FIXME: Encapsulate more state in the SuiteRunner. // FIXME: Return and use measured values from SuiteRunner. - const type = suite.type ?? ((params.useAsyncSteps && "async") || "default"); + const type = this._suiteRunnerType(suite); const suiteRunnerClass = SUITE_RUNNER_LOOKUP[type]; const suiteRunner = new suiteRunnerClass(this._frame, this._page, params, suite, this._client, this._measuredValues); await suiteRunner.run(); diff --git a/resources/shared/params.mjs b/resources/shared/params.mjs index f9e0a0541..8a4534d4c 100644 --- a/resources/shared/params.mjs +++ b/resources/shared/params.mjs @@ -17,8 +17,10 @@ export class Params { // toggle async type vs default raf type. useAsyncSteps = false; // Change how a test measurement is triggered and async time is measured: - // "timer": The classic (as in Speedometer 2.x) way using setTimeout - // "raf": Using rAF callbacks, both for triggering the sync part and for measuring async time. + // "timer": The classic (as in Speedometer 2.x) way using setTimeout + // "raf": Using rAF callbacks, both for triggering the sync part and for measuring async time. + // "continuous": Chains steps via MessageChannel with a continuous clock (no unmeasured inter-step rAF gap) + // and closes the final step with a standard rAF + setTimeout async paint. measurementMethod = "raf"; // Wait time after suite preparation in ms. waitAfterSetup = 0; @@ -82,7 +84,7 @@ export class Params { this.waitBeforeSync = this._parseIntParam(searchParams, "waitBeforeSync", 0); this.waitAfterSuite = this._parseIntParam(searchParams, "waitAfterSuite", 0); this.warmupBeforeSync = this._parseIntParam(searchParams, "warmupBeforeSync", 0); - this.measurementMethod = this._parseEnumParam(searchParams, "measurementMethod", ["raf"]); + this.measurementMethod = this._parseEnumParam(searchParams, "measurementMethod", ["raf", "continuous"]); this.shuffleSeed = this._parseShuffleSeed(searchParams); this.complexity = this._parserNumberParam(searchParams, "complexity", 0); this.layoutMode = this._parseEnumParam(searchParams, "layoutMode", LAYOUT_MODES); diff --git a/resources/shared/step-runner.mjs b/resources/shared/step-runner.mjs index 3e86cbd9e..bf96404e5 100644 --- a/resources/shared/step-runner.mjs +++ b/resources/shared/step-runner.mjs @@ -89,7 +89,8 @@ export class StepRunner { performance.measure(`${suiteName}.${stepName}-async`, syncEndLabel, asyncEndLabel); }; - const schedulerType = this.#suite.type === "async" || this.#params.useAsyncSteps ? "async" : this.#params.measurementMethod; + const measurementMethod = this.#params.measurementMethod === "continuous" ? "raf" : this.#params.measurementMethod; + const schedulerType = this.#suite.type === "async" || this.#params.useAsyncSteps ? "async" : measurementMethod; const schedulerClass = STEP_SCHEDULER_LOOKUP[schedulerType]; const scheduler = new schedulerClass(runSync, measureAsync, this.#params); await scheduler.start(); diff --git a/resources/shared/step-scheduler.mjs b/resources/shared/step-scheduler.mjs index c7e74c298..4e088ba96 100644 --- a/resources/shared/step-scheduler.mjs +++ b/resources/shared/step-scheduler.mjs @@ -70,6 +70,61 @@ class AsyncRAFStepScheduler extends StepScheduler { } } +export class ContinuousStepScheduler extends StepScheduler { + constructor(steps, syncCallback, asyncCallback, params) { + super(syncCallback, asyncCallback, params); + this._steps = steps; + } + + _scheduleCallbacks(resolve) { + const steps = this._steps; + if (!steps.length) { + resolve([]); + return; + } + const lastIndex = steps.length - 1; + const results = new Array(steps.length); + const mc = lastIndex > 0 ? new MessageChannel() : null; + let idx = 0; + let stepStartTime = 0; + let syncEndTime = 0; + + const finishFinalAsync = () => { + const asyncEndTime = this._asyncCallback(steps[lastIndex], true); + results[lastIndex] = { step: steps[lastIndex], syncTime: syncEndTime - stepStartTime, asyncTime: asyncEndTime - syncEndTime }; + setTimeout(() => { + mc?.port1.close(); + mc?.port2.close(); + resolve(results); + }, 0); + }; + + const runCurrentStep = (startTime) => { + const isFinal = idx === lastIndex; + const times = this._syncCallback(steps[idx], startTime, !isFinal); + stepStartTime = times.startTime; + syncEndTime = times.syncEndTime; + if (!isFinal) + mc.port2.postMessage(null); + else if (lastIndex > 0) + requestAnimationFrame(() => setTimeout(finishFinalAsync, 0)); + }; + + if (mc) { + mc.port1.onmessage = () => { + const boundaryTime = this._asyncCallback(steps[idx], false); + results[idx] = { step: steps[idx], syncTime: syncEndTime - stepStartTime, asyncTime: boundaryTime - syncEndTime }; + idx++; + runCurrentStep(boundaryTime); + }; + } + + requestAnimationFrame(() => runCurrentStep(null)); + if (lastIndex === 0) + requestAnimationFrame(() => setTimeout(finishFinalAsync, 0)); + } +} + export const STEP_SCHEDULER_LOOKUP = { __proto__: null, raf: RAFStepScheduler, diff --git a/resources/suite-runner.mjs b/resources/suite-runner.mjs index 33eb20be7..8d7bccea4 100644 --- a/resources/suite-runner.mjs +++ b/resources/suite-runner.mjs @@ -1,4 +1,6 @@ import { STEP_RUNNER_LOOKUP } from "./shared/step-runner.mjs"; +import { ContinuousStepScheduler } from "./shared/step-scheduler.mjs"; +import { forceLayout } from "./shared/helpers.mjs"; import { MESSAGE_TYPE } from "./shared/benchmark.mjs"; import { WarmupSuite } from "./benchmark-runner.mjs"; @@ -269,9 +271,71 @@ export class RemoteSuiteRunner extends SuiteRunner { } } +export class ContinuousSuiteRunner extends SuiteRunner { + async _runSuite() { + const suiteName = this.suite.name; + const suiteStartLabel = `suite-${suiteName}-start`; + const suiteEndLabel = `suite-${suiteName}-end`; + const steps = this.suite.tests; + + await delay(this.params.waitAfterSetup); + + performance.mark(suiteStartLabel); + // Notify the client once before entering the continuous chain; awaiting + // between steps would introduce an unmeasured gap. + if (steps.length) + await this.client?.willRunTest?.(this.suite, steps[0]); + + const doLayout = () => { + const body = this.frame?.contentDocument?.body ?? document.body; + body._leakedLayoutValue = forceLayout(body, this.params.layoutMode); + }; + const runSync = (step, startTime, layoutAfterSync) => { + if (startTime === null && this.params.warmupBeforeSync) { + performance.mark("warmup-start"); + const warmupStart = performance.now(); + while (performance.now() - warmupStart < this.params.warmupBeforeSync) + continue; + performance.mark("warmup-end"); + } + const startMark = performance.mark(`${suiteName}.${step.name}-start`); + step.run(this.page); + if (layoutAfterSync) + doLayout(); + const syncEndMark = performance.mark(`${suiteName}.${step.name}-sync-end`); + return { startTime: startTime ?? startMark.startTime, syncEndTime: syncEndMark.startTime }; + }; + const runAsync = (step, isFinal) => { + if (isFinal) + doLayout(); + return performance.mark(`${suiteName}.${step.name}-async-end`).startTime; + }; + + const scheduler = new ContinuousStepScheduler(steps, runSync, runAsync, this.params); + const results = await scheduler.start(); + + if (steps.length && this.params.warmupBeforeSync) + performance.measure("warmup", "warmup-start", "warmup-end"); + for (const { step, syncTime, asyncTime } of results) { + performance.measure(`${suiteName}.${step.name}-sync`, `${suiteName}.${step.name}-start`, `${suiteName}.${step.name}-sync-end`); + performance.measure(`${suiteName}.${step.name}-async`, `${suiteName}.${step.name}-sync-end`, `${suiteName}.${step.name}-async-end`); + await this._recordTestResults(step, syncTime, asyncTime); + } + + performance.mark(suiteEndLabel); + + await delay(this.params.waitAfterSuite); + + performance.measure(`suite-${suiteName}`, suiteStartLabel, suiteEndLabel); + this._validateSuiteResults(); + await this._updateClient(); + } +} + export const SUITE_RUNNER_LOOKUP = { __proto__: null, default: SuiteRunner, async: SuiteRunner, + continuous: ContinuousSuiteRunner, remote: RemoteSuiteRunner, }; diff --git a/tests/unittests/benchmark-runner.mjs b/tests/unittests/benchmark-runner.mjs index a95a28790..78a262a0c 100644 --- a/tests/unittests/benchmark-runner.mjs +++ b/tests/unittests/benchmark-runner.mjs @@ -1,8 +1,8 @@ import { BenchmarkRunner, BenchmarkTestStep } from "../../resources/benchmark-runner.mjs"; -import { SuiteRunner } from "../../resources/suite-runner.mjs"; +import { SuiteRunner, ContinuousSuiteRunner } from "../../resources/suite-runner.mjs"; import { StepRunner, AsyncStepRunner } from "../../resources/shared/step-runner.mjs"; -import { STEP_SCHEDULER_LOOKUP } from "../../resources/shared/step-scheduler.mjs"; -import { defaultParams } from "../../resources/shared/params.mjs"; +import { STEP_SCHEDULER_LOOKUP, ContinuousStepScheduler } from "../../resources/shared/step-scheduler.mjs"; +import { Params, defaultParams } from "../../resources/shared/params.mjs"; import { skipInShell } from "../../resources/shared/helpers.mjs"; function TEST_FIXTURE(name) { @@ -305,6 +305,158 @@ describe("BenchmarkRunner", () => { assert.calledOnce(syncCallback); assert.calledOnce(asyncCallback); }); + + it("should chain multi-step callbacks continuously in ContinuousStepScheduler", async () => { + const steps = [TEST_FIXTURE("Step 1"), TEST_FIXTURE("Step 2"), TEST_FIXTURE("Step 3")]; + const events = []; + const timestamps = [100, 130, 145, 190, 200, 250, 265]; + let cursor = 0; + + const syncCallback = (step, startTime, layoutAfterSync) => { + const effectiveStart = startTime ?? timestamps[cursor++]; + const syncEndTime = timestamps[cursor++]; + events.push({ phase: "sync", name: step.name, startTime, layoutAfterSync }); + return { startTime: effectiveStart, syncEndTime }; + }; + const asyncCallback = (step, isFinal) => { + const asyncEndTime = timestamps[cursor++]; + events.push({ phase: "async", name: step.name, isFinal }); + return asyncEndTime; + }; + + const scheduler = new ContinuousStepScheduler(steps, syncCallback, asyncCallback, { waitBeforeSync: 0 }); + const results = await scheduler.start(); + + expect(events).to.eql([ + { phase: "sync", name: "Step 1", startTime: null, layoutAfterSync: true }, + { phase: "async", name: "Step 1", isFinal: false }, + { phase: "sync", name: "Step 2", startTime: 145, layoutAfterSync: true }, + { phase: "async", name: "Step 2", isFinal: false }, + { phase: "sync", name: "Step 3", startTime: 200, layoutAfterSync: false }, + { phase: "async", name: "Step 3", isFinal: true }, + ]); + expect(results).to.eql([ + { step: steps[0], syncTime: 30, asyncTime: 15 }, + { step: steps[1], syncTime: 45, asyncTime: 10 }, + { step: steps[2], syncTime: 50, asyncTime: 15 }, + ]); + const total = results.reduce((sum, r) => sum + r.syncTime + r.asyncTime, 0); + expect(total).to.equal(265 - 100); + }); + + it("should support single-step and empty suites in ContinuousStepScheduler", async () => { + const emptyScheduler = new ContinuousStepScheduler([], sinon.stub(), sinon.stub(), { waitBeforeSync: 0 }); + expect(await emptyScheduler.start()).to.eql([]); + + const step = TEST_FIXTURE("Only Step"); + const syncStub = sinon.stub().returns({ startTime: 10, syncEndTime: 25 }); + const asyncStub = sinon.stub().returns(32); + const singleScheduler = new ContinuousStepScheduler([step], syncStub, asyncStub, { waitBeforeSync: 0 }); + const results = await singleScheduler.start(); + + assert.calledOnceWithExactly(syncStub, step, null, false); + assert.calledOnceWithExactly(asyncStub, step, true); + expect(results).to.eql([{ step, syncTime: 15, asyncTime: 7 }]); + }); + }); + + describe("ContinuousSuiteRunner", () => { + it("should run steps in order with continuous zero-gap timing and sum suiteResults.total", async () => { + const callOrder = []; + const suite = { + name: "ContinuousSuite", + type: "continuous", + async prepare(page) {}, + enabled: true, + tests: [ + { name: "Step 1", run: sinon.stub().callsFake(() => callOrder.push("Step 1")) }, + { name: "Step 2", run: sinon.stub().callsFake(() => callOrder.push("Step 2")) }, + { name: "Step 3", run: sinon.stub().callsFake(() => callOrder.push("Step 3")) }, + ], + }; + const client = { + willRunTest: sinon.stub(), + didFinishSuite: sinon.stub(), + }; + const measuredValues = { tests: {} }; + const stepMarks = new Map([ + ["ContinuousSuite.Step 1-start", 1000], + ["ContinuousSuite.Step 1-sync-end", 1020], + ["ContinuousSuite.Step 1-async-end", 1030], + ["ContinuousSuite.Step 2-start", 1031], + ["ContinuousSuite.Step 2-sync-end", 1070], + ["ContinuousSuite.Step 2-async-end", 1085], + ["ContinuousSuite.Step 3-start", 1086], + ["ContinuousSuite.Step 3-sync-end", 1110], + ["ContinuousSuite.Step 3-async-end", 1125], + ]); + const originalMark = window.performance.mark.bind(window.performance); + const markStub = stub(window.performance, "mark").callsFake((name) => { + if (stepMarks.has(name)) + return originalMark(name, { startTime: stepMarks.get(name) }); + return originalMark(name); + }); + + await runner._appendFrame(); + const suiteRunner = new ContinuousSuiteRunner(runner._frame, runner._page, { measurementMethod: "continuous" }, suite, client, measuredValues); + await suiteRunner._runSuite(); + + expect(callOrder).to.eql(["Step 1", "Step 2", "Step 3"]); + assert.calledOnceWithExactly(client.willRunTest, suite, suite.tests[0]); + assert.calledOnceWithExactly(client.didFinishSuite, suite); + + assert.calledWith(markStub, "suite-ContinuousSuite-start"); + assert.calledWith(markStub, "suite-ContinuousSuite-end"); + for (const step of suite.tests) { + assert.calledWith(markStub, `ContinuousSuite.${step.name}-start`); + assert.calledWith(markStub, `ContinuousSuite.${step.name}-sync-end`); + assert.calledWith(markStub, `ContinuousSuite.${step.name}-async-end`); + } + // 2 suite marks + 3 marks per step. + expect(markStub.callCount).to.equal(11); + + const results = measuredValues.tests.ContinuousSuite; + // Step 2 starts from Step 1's async-end (1030) and Step 3 from Step 2's async-end (1085), + // so total equals exact continuous span (1125 - 1000 = 125) with 0 ms unmeasured gap. + expect(results.tests["Step 1"]).to.eql({ tests: { Sync: 20, Async: 10 }, total: 30 }); + expect(results.tests["Step 2"]).to.eql({ tests: { Sync: 40, Async: 15 }, total: 55 }); + expect(results.tests["Step 3"]).to.eql({ tests: { Sync: 25, Async: 15 }, total: 40 }); + expect(results.total).to.equal(125); + }); + + it("should route suite.type='continuous' and params.measurementMethod='continuous' to ContinuousSuiteRunner", async () => { + const continuousSuite = { + name: "ContinuousRoutedSuite", + type: "continuous", + async prepare(page) {}, + enabled: true, + tests: [TEST_FIXTURE("Only Step")], + }; + const loadFrameStub = stub(SuiteRunner.prototype, "_loadFrame").callsFake(async () => null); + const runSuiteStub = stub(ContinuousSuiteRunner.prototype, "_runSuite").callsFake(async () => null); + + await runner.runSuite(continuousSuite); + assert.calledOnce(loadFrameStub); + assert.calledOnce(runSuiteStub); + + const defaultSuite = { name: "DefaultSuite" }; + const continuousParams = new Params(new URLSearchParams({ measurementMethod: "continuous" })); + const asyncParams = new Params(new URLSearchParams({ useAsyncSteps: "" })); + expect(runner._suiteRunnerType(defaultSuite, defaultParams)).to.equal("default"); + expect(runner._suiteRunnerType(defaultSuite, continuousParams)).to.equal("continuous"); + expect(runner._suiteRunnerType(defaultSuite, asyncParams)).to.equal("async"); + expect(runner._suiteRunnerType(continuousSuite, defaultParams)).to.equal("continuous"); + expect(runner._suiteRunnerType({ name: "RemoteSuite", type: "remote" }, continuousParams)).to.equal("remote"); + }); + + it("should fall back to RAFStepScheduler in StepRunner when measurementMethod='continuous'", async () => { + const step = new BenchmarkTestStep("SingleStep", sinon.stub()); + const stepRunner = new StepRunner(null, null, { measurementMethod: "continuous", warmupBeforeSync: 0 }, SUITES_FIXTURE[0], step); + const { syncTime, asyncTime } = await stepRunner.runStep(); + expect(typeof syncTime).to.equal("number"); + expect(typeof asyncTime).to.equal("number"); + assert.calledOnce(step.run); + }); }); }); diff --git a/tests/unittests/params.mjs b/tests/unittests/params.mjs index 0b3821445..2f5d0c9f9 100644 --- a/tests/unittests/params.mjs +++ b/tests/unittests/params.mjs @@ -74,6 +74,22 @@ describe("Params", () => { ); expect(params.toSearchParams()).to.equal("suites="); }); + it("should contain custom measurementMethod", () => { + const params = new Params( + new URLSearchParams({ + measurementMethod: "continuous", + }) + ); + expect(params.toSearchParams()).to.equal("measurementMethod=continuous"); + }); + it("should not contain default measurementMethod", () => { + const params = new Params( + new URLSearchParams({ + measurementMethod: "raf", + }) + ); + expect(params.toSearchParams()).to.equal(""); + }); }); describe("isDefault", () => { it("should return true for defaultParams", () => { @@ -126,6 +142,23 @@ describe("Params", () => { ); expect(params.suites).to.eql(["SuiteB", "Suite1", "SuiteA"]); }); + it("should parse measurementMethod=continuous", () => { + const params = new Params( + new URLSearchParams({ + measurementMethod: "continuous", + }) + ); + expect(params.measurementMethod).to.equal("continuous"); + }); + it("should reject invalid measurementMethod", () => { + expect(() => { + new Params( + new URLSearchParams({ + measurementMethod: "invalid", + }) + ); + }).to.throwError(); + }); it("should warn on unused params when warnUnused is true", () => { const consoleErrorStub = sinon.stub(console, "error"); try {