Repository navigation
Expand file tree
/
Copy pathvitest.shared.ts
More file actions
352 lines (329 loc) · 13.7 KB
/
Copy pathvitest.shared.ts
File metadata and controls
352 lines (329 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/**
* Shared vitest runtime pieces for the root and bench configs (and the test
* files that need them) — declared once so the runners and tests cannot drift:
* happy-dom runs fully offline (parsed URLs are data, not network requests;
* the fixture corpus is offline), and its expected "disabled load" console
* noise is filtered from the gate signal instead of failing it.
*/
/** happy-dom environment settings: all resource loading disabled. */
export const HAPPY_DOM_SETTINGS = {
disableCSSFileLoading: true,
disableJavaScriptFileLoading: true,
disableIframePageLoading: true,
// Disabled (non-iframe) loads report success instead of erroring.
handleDisabledFileLoadingAsSuccess: true
} as const;
/**
* Filter happy-dom's own console reports for disabled loads — expected
* offline noise, never gate signal.
*
* @param log The console line.
* @param type The console stream it came from.
* @returns `false` to drop the line, `undefined` to keep default handling.
*/
export function filterDisabledLoadNoise(log: string, type: string): boolean | undefined {
if (
type === 'stderr' &&
/Iframe page loading is disabled|CSS file loading is disabled/.test(log)
) {
return false;
}
return undefined;
}
/*
* Timing policy for unit tests. Shared CI runners (2 vCPU, v8 coverage) run
* ~10× slower than a development machine and stall at random, so one run
* against an absolute millisecond ceiling either flakes there or, sized for
* there, waves regressions through here. Every timing assertion is
* therefore machine-relative, through the helpers below:
* - a scaling claim ("linear", "no backtracking blow-up") → {@link linearScaling}:
* the same input shape timed at two sizes;
* - a constant-factor tripwire ("as fast as X", "no costly per-value path")
* → {@link relativeCost}: the work against a same-machine baseline doing
* independent JavaScript work ({@link plainRead}: a baseline sharing the
* work's code lets a slowdown cancel out; coverage slows JavaScript, not
* native code such as `JSON.stringify`, so a native one drifts); memoized
* work gets a fresh input per round, or the memo is what gets timed;
* - a hang guard (correct: microseconds; regressed: seconds or never) →
* {@link timeRun} under an absolute backstop, allowed only when the
* backstop sits ≥ 10× above the work's cost under coverage on throttled
* cores (`taskpolicy -c background` on macOS), so no runner can reach it.
* Wall-clock reads outside these helpers are lint-banned (the `performance`
* global, aliases included, and `now()` on a global's `performance`). Not
* covered: `Date.now()` (tests use it for legitimate timestamps), computed
* reads like `globalThis['performance']` and cast reads like
* `(globalThis as X).performance.now()` — never time work with any of them.
* Comparisons take the best of interleaved rounds: noise (GC, scheduling, a
* loaded runner) only ever adds time, so the minimum estimates the work's own
* cost, and interleaving shows both sides the same machine state.
*/
/**
* Independent baseline work for {@link relativeCost}: `passes` plain
* JavaScript reads of `text` (char codes summed). It shares no code with
* anything under test, so a slowdown of that code cannot cancel out, while
* coverage and a slow or loaded machine weigh on both alike.
*
* @param text The text to read.
* @param passes How many times to read it (a non-negative integer).
* @returns The 32-bit sum (returned so the loop is not optimised away).
*/
export function plainRead(text: string, passes = 1): number {
let sum = 0;
for (let pass = 0; pass < passes; pass++) {
for (let index = 0; index < text.length; index++) sum = (sum + text.charCodeAt(index)) | 0;
}
return sum;
}
/**
* What {@link plainRead} costs per character on the development machine
* (Node 24, warm, no coverage), so a test can turn a rate declared on that
* machine into this machine's time. Measured 1.26–1.63 ns in plain Node;
* inside vitest 0.76–1.31 ns depending on the run. A faster read than this
* makes a bound derived from it stricter than nominal, never looser.
*/
export const PLAIN_READ_NS_PER_CHAR = 1.5;
/** A monotonic millisecond clock; injectable so the helpers are testable. */
export type Clock = () => number;
/** The real clock. */
const wallClock: Clock = () => performance.now();
/** One timed call. */
export interface TimedRun<R> {
/** Wall time (ms). */
readonly ms: number;
/** What the call returned. */
readonly output: R;
}
/**
* Time one call — for hang guards only (see the timing policy above).
*
* @param run The work under test.
* @param now The clock.
* @returns The duration and the call's output.
*/
export function timeRun<R>(run: () => R, now: Clock = wallClock): TimedRun<R> {
const started = now();
const output = run();
return { ms: now() - started, output };
}
/** What {@link interleavedBest} measured. */
export interface InterleavedBest<A, B> {
/** Best time (ms) of each call. */
readonly bestMs: readonly [number, number];
/** Each call's last output (`undefined` until it ran). */
readonly last: readonly [A | undefined, B | undefined];
/** The first run past the backstop, when one was. */
readonly overrun: { readonly ms: number } | undefined;
}
/**
* Time two calls alternately (ABBA) over `runs` rounds and keep each one's best.
* Stops at the first run past `backstopMs` (checked after it returns, never
* preempting it): a superlinear call would otherwise take minutes more.
*
* @param calls The two calls, run in this order each round.
* @param runs Rounds (a positive integer).
* @param backstopMs The absolute bound on any single run.
* @param now The clock.
* @returns The best times, last outputs and any overrun.
* @throws {@link RangeError} When `runs` is not a positive integer.
*/
export function interleavedBest<A, B>(
calls: readonly [() => A, () => B],
runs: number,
backstopMs: number,
now: Clock = wallClock
): InterleavedBest<A, B> {
if (!Number.isInteger(runs) || runs < 1) {
throw new RangeError(`interleavedBest: runs must be a positive integer, got ${String(runs)}`);
}
const bestMs: [number, number] = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
let lastFirst: A | undefined;
let lastSecond: B | undefined;
/** Time call `index` once; its duration. */
const step = (index: 0 | 1): number => {
let ms: number;
if (index === 0) {
const timed = timeRun(calls[0], now);
[lastFirst, ms] = [timed.output, timed.ms];
} else {
const timed = timeRun(calls[1], now);
[lastSecond, ms] = [timed.output, timed.ms];
}
bestMs[index] = Math.min(bestMs[index], ms);
return ms;
};
for (let round = 0; round < runs; round++) {
// ABBA order: the garbage one call leaves is collected during the next,
// so alternating who goes first spreads that cost over both.
for (const index of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) {
const ms = step(index);
if (ms > backstopMs) {
return { bestMs, last: [lastFirst, lastSecond], overrun: { ms } };
}
}
}
return { bestMs, last: [lastFirst, lastSecond], overrun: undefined };
}
/**
* The overrun message both comparisons report.
*
* @param ms The overrunning run's time.
* @param backstopMs The backstop.
* @returns The violation text.
*/
function overrunViolation(ms: number, backstopMs: number): string {
return `one run took ${ms.toFixed(0)} ms (backstop ${String(backstopMs)} ms)`;
}
/**
* Per-test timeout (ms) for a test whose comparison follows `policy`: two
* timed calls per round, each allowed up to `backstopMs`, plus a margin for
* untimed input builds and the test's own assertions (vitest's 5 s default
* is shorter than a passing measurement on a slow runner with coverage).
*
* @param policy The comparison's rounds and backstop.
* @returns The timeout to pass as the test's timeout argument.
*/
export function comparisonTimeoutMs(policy: {
readonly runs: number;
readonly backstopMs: number;
}): number {
return policy.runs * 2 * policy.backstopMs + 5_000;
}
/**
* How a scaling claim is proven without a wall-clock ceiling: the same input
* shape is timed at `size` and `factor × size` in one run, so machine speed
* cancels out. `size` is in the test's unit (bytes by default; elements or
* rows where the input is built by count). Linear work grows ~`factor`×,
* quadratic ~`factor²`× (16×), so `maxRatio` sits between with room for
* noise. `floorMs` keeps sub-millisecond baselines (timer and cache noise)
* from inflating the ratio — pick a `size` whose quadratic cost is far above
* it. `backstopMs` bounds any single run absolutely, which also stops a
* quadratic baseline before its slower run takes minutes; it is not a scaling
* signal — `maxRatio` is. Sized for CI: 4 MiB runs took ~4 s on a shared
* runner with coverage against a former 5 s backstop.
*/
export const LINEAR_SCALING = {
size: 1024 * 1024,
factor: 4,
runs: 3,
maxRatio: 10,
floorMs: 1,
backstopMs: 15_000
} as const;
/** Per-test timeout (ms) for a test that calls {@link linearScaling} with its default runs and backstop. */
export const LINEAR_SCALING_TIMEOUT_MS = comparisonTimeoutMs(LINEAR_SCALING);
/** The knobs of {@link linearScaling}; defaults to {@link LINEAR_SCALING}. */
export type LinearScalingPolicy = { readonly [K in keyof typeof LINEAR_SCALING]: number };
/** What {@link linearScaling} measured. */
export interface LinearScaling<R> {
/** Why the run is not linear, or `undefined` when it is. */
readonly violation: string | undefined;
/** Best time (ms) at `size`, then at `factor × size`. */
readonly smallMs: number;
readonly largeMs: number;
/** The last output on the large input, for correctness assertions. */
readonly output: R | undefined;
}
/**
* Time `run` on `build(size)` and `build(factor × size)`, best of `runs`
* each, interleaved.
*
* @param build Builds the input of about the given size (untimed).
* @param run The work under test.
* @param policy The scaling policy.
* @param now The clock.
* @returns The measurement, with a readable `violation` when the time grows
* faster than `maxRatio` or a run exceeds `backstopMs`.
*/
export function linearScaling<T, R>(
build: (size: number) => T,
run: (input: T) => R,
policy: LinearScalingPolicy = LINEAR_SCALING,
now: Clock = wallClock
): LinearScaling<R> {
const small = build(policy.size);
const large = build(policy.size * policy.factor);
const measured = interleavedBest(
[() => run(small), () => run(large)],
policy.runs,
policy.backstopMs,
now
);
const [smallMs, largeMs] = measured.bestMs;
const output = measured.last[1];
if (measured.overrun !== undefined) {
return {
violation: overrunViolation(measured.overrun.ms, policy.backstopMs),
smallMs,
largeMs,
output
};
}
const ratio = largeMs / Math.max(smallMs, policy.floorMs);
const violation =
ratio > policy.maxRatio
? `${String(policy.factor)}× the input took ${ratio.toFixed(1)}× the time ` +
`(${smallMs.toFixed(1)} → ${largeMs.toFixed(1)} ms; limit ${String(policy.maxRatio)}×)`
: undefined;
return { violation, smallMs, largeMs, output };
}
/**
* How a constant-factor tripwire is checked: the work and an independent
* baseline (code the work does not share, e.g. {@link plainRead}, so a
* slowdown of the work cannot cancel out) are timed alternately, best of
* `runs` each, and their ratio is bounded by the test's own `maxRatio` — so
* a slow or loaded machine slows both alike. `floorMs` and `backstopMs` as
* in {@link LINEAR_SCALING}.
*/
export const RELATIVE_COST = { runs: 5, floorMs: 1, backstopMs: 15_000 } as const;
/** Per-test timeout (ms) for a test that calls {@link relativeCost} with its default runs and backstop. */
export const RELATIVE_COST_TIMEOUT_MS = comparisonTimeoutMs(RELATIVE_COST);
/** The knobs of {@link relativeCost}; defaults to {@link RELATIVE_COST}. */
export type RelativeCostPolicy = { readonly [K in keyof typeof RELATIVE_COST]: number };
/** What {@link relativeCost} measured. */
export interface RelativeCost<R> {
/** Why the work is too costly, or `undefined` when it is not. */
readonly violation: string | undefined;
/** Best time (ms) of the work, then of the baseline. */
readonly ms: number;
readonly baselineMs: number;
/** The work's last output, for correctness assertions. */
readonly output: R | undefined;
}
/**
* Time `run` against `baseline`, best of `runs` each, interleaved in ABBA
* order (baseline first in even rounds, the work first in odd ones).
*
* @param run The work under test.
* @param baseline Comparable work on the same machine and input.
* @param maxRatio The largest allowed `run / max(baseline, floorMs)`.
* @param policy The comparison policy.
* @param now The clock.
* @returns The measurement, with a readable `violation` when the ratio
* exceeds `maxRatio` or a run exceeds `backstopMs`.
*/
export function relativeCost<R>(
run: () => R,
baseline: () => unknown,
maxRatio: number,
policy: RelativeCostPolicy = RELATIVE_COST,
now: Clock = wallClock
): RelativeCost<R> {
const measured = interleavedBest([baseline, run], policy.runs, policy.backstopMs, now);
const [baselineMs, ms] = measured.bestMs;
const output = measured.last[1];
if (measured.overrun !== undefined) {
return {
violation: overrunViolation(measured.overrun.ms, policy.backstopMs),
ms,
baselineMs,
output
};
}
const ratio = ms / Math.max(baselineMs, policy.floorMs);
const violation =
ratio > maxRatio
? `took ${ratio.toFixed(1)}× its baseline ` +
`(${baselineMs.toFixed(1)} → ${ms.toFixed(1)} ms; limit ${String(maxRatio)}×)`
: undefined;
return { violation, ms, baselineMs, output };
}