import assert from 'node:assert/strict'; import {performance} from 'node:perf_hooks'; export const K2100_MIN_RUNNING_MS = 7_200_000; // Call pauseBeforeStop() BEFORE requesting QMP stop, and resumeAfterConfirmed() // AFTER QMP confirms running. This excludes both paused capture time and QMP // transition latency. Enable only at the native workload's initial GO barrier. // The default source is the real host monotonic clock. Injected sources are for // host tests; a source-bound guest runner must use the default constructor. export class RunningClock { #now; #phase = 'new'; #last = null; #origin = null; #started = null; #elapsed = 0; #segments = []; constructor(now = () => performance.now()) { this.#now = now; } #sample() { const now = this.#now(); assert.ok(Number.isFinite(now) && now >= 0, 'valid host monotonic clock'); assert.ok(this.#last === null || now >= this.#last, 'host clock cannot regress'); return now; } resumeAfterConfirmed(status) { assert.equal(status, 'running'); assert.ok(this.#phase === 'new' || this.#phase === 'paused', 'unpaired resume'); const now = this.#sample(); this.#origin ??= now; this.#last = now; this.#started = now; this.#phase = 'running'; } pauseBeforeStop() { assert.equal(this.#phase, 'running', 'unpaired stop'); const now = this.#sample(), milliseconds = now - this.#started; const total = this.#elapsed + milliseconds; assert.ok(Number.isFinite(total), 'host elapsed overflow'); this.#segments.push({start: this.#started, end: now, milliseconds}); this.#elapsed = total; this.#started = null; this.#last = now; this.#phase = 'paused'; } snapshot() { const now = this.#sample(); const runningMilliseconds = this.#elapsed + (this.#phase === 'running' ? now - this.#started : 0); const wallMilliseconds = this.#origin === null ? 0 : now - this.#origin; assert.ok(Number.isFinite(runningMilliseconds) && runningMilliseconds <= wallMilliseconds); this.#last = now; return {phase: this.#phase, wallMilliseconds, runningMilliseconds, excludedMilliseconds: wallMilliseconds - runningMilliseconds, minimumRunningMilliseconds: K2100_MIN_RUNNING_MS, durationMet: this.#origin !== null && runningMilliseconds >= K2100_MIN_RUNNING_MS, segments: this.#segments.map(segment => ({...segment}))}; } }