Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server-metrics.test.ts

718 lines25.8 KB

1import { it as effectIt } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { describe, expect, it } from "vite-plus/test";
5​
6import {
7 compareMetrics,
8 competingBetween,
9 activityRenewalMissed,
10 describeFailure,
11 heapGrowth,
12 heapRetainers,
13 loadWarnings,
14 nextActivityReport,
15 noiseReport,
16 noisePairProblem,
17 parsePsCpuTime,
18 profileMismatch,
19 parseRunSelection,
20 retainerGrowth,
21 pathRewrites,
22 pathSpellings,
23 ServerMetrics,
24 slope,
25} from "./server-metrics-report.ts";
26import { runAbRounds } from "./server-metrics.ts";
27​
28const decodeMetrics = Schema.decodeSync(ServerMetrics);
29​
30type Quiet = {
31 cpuPct: number;
32 wakeupsPerSec: number | null;
33 rssPeakMB: number;
34 loopDelayP99Ms?: number;
35 loopDelayMaxMs?: number;
36 gcPauseMs?: number;
37};
38const loopAtRest = {
39 loopDelayP50Ms: 0.1,
40 loopDelayP99Ms: 1.5,
41 loopDelayMaxMs: 8,
42 gcCount: 12,
43 gcPauseMs: 6,
44};
45const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true };
46const quietRuns = (...runs: Quiet[]) =>
47 ({
48 meta,
49 runs: runs.map((quiet) => ({
50 quiet: { ...loopAtRest, ...quiet, rssMB: 500, heapAfterGcMB: 200 },
51 })),
52 }) satisfies ServerMetrics;
53const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 };
54const cpuRuns = (...values: number[]) =>
55 quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct })));
56​
57// Fixed floors, so these cases test how compare gates rather than the calibrated table.
58const gatedRules = [
59 { pattern: /cpuPct$/, floor: 1, gate: true },
60 { pattern: /wakeupsPerSec$/, floor: 20, gate: true },
61 { pattern: /MB$/, floor: 15, gate: true },
62 { pattern: /loopDelayP99Ms$/, floor: 5, gate: true },
63 { pattern: /loopDelayMaxMs$/, floor: 20, gate: true },
64 { pattern: /gcPauseMs$/, floor: 10, gate: true },
65 { pattern: /./, floor: 300, gate: true },
66];
67​
68describe("compareMetrics", () => {
69 it.each([
70 ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []],
71 ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, [], []],
72 ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, [], []],
73 ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"], []],
74 ["a doubled p99 loop delay under the 5 ms floor", { loopDelayP99Ms: 3 }, [], []],
75 ["a p99 loop delay past it", { loopDelayP99Ms: 40 }, ["quiet.loopDelayP99Ms"], []],
76 ["one longer stall under the 20 ms max floor", { loopDelayMaxMs: 25 }, [], []],
77 ["GC pauses past the 10 ms floor", { gcPauseMs: 30 }, ["quiet.gcPauseMs"], []],
78 [
79 "an improvement past the floors",
80 { cpuPct: 0.1, wakeupsPerSec: 7, rssPeakMB: 400 },
81 [],
82 ["quiet.rssPeakMB"],
83 ],
84 ])("one run each: %s", (_name, change, regressed, improved) => {
85 const result = compareMetrics(
86 quietRuns(base),
87 quietRuns({ ...base, ...change }),
88 10,
89 gatedRules,
90 );
91 expect(result.regressed).toEqual(regressed);
92 expect(result.improved).toEqual(improved);
93 });
94​
95 it("shows a metric missing on one side as n/a, not as a change", () => {
96 const before = quietRuns({ ...base, wakeupsPerSec: null });
97 const result = compareMetrics(before, quietRuns({ ...base, wakeupsPerSec: 50 }));
98 expect(result.regressed).toEqual([]);
99 expect(result.table).toContain("| quiet.wakeupsPerSec | – | 50 | n/a | | |");
100 });
101​
102 it("flags repeated runs only when the whole interval clears the limit", () => {
103 const steady = cpuRuns(26.1, 27.4, 25.8);
104 const fixed = cpuRuns(2.2, 2.5, 2.1);
105 expect(compareMetrics(steady, fixed, 10, gatedRules).improved).toContain("quiet.cpuPct");
106 expect(compareMetrics(fixed, steady, 10, gatedRules).regressed).toContain("quiet.cpuPct");
107 // The medians differ by 2.8 points, past the floor, but a resampled median can match.
108 expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9), 10, gatedRules).regressed).toEqual([]);
109 });
110​
111 it("compares the unequal run counts an ab that stopped early leaves", () => {
112 const steady = cpuRuns(26.1, 27.4, 25.8);
113 const partial = compareMetrics(steady, cpuRuns(2.2, 2.5), 10, gatedRules);
114 expect(partial.improved).toContain("quiet.cpuPct");
115 expect(partial.table).toContain("(3 runs), after `abc` (2 runs)");
116 const single = compareMetrics(steady, cpuRuns(2.2), 10, gatedRules);
117 expect(single.improved).toContain("quiet.cpuPct");
118 expect(single.table).toContain("| quiet.cpuPct | 26.1 | 2.2 | -92% | | better |");
119 expect(compareMetrics(steady, cpuRuns(), 10, gatedRules).compared).toBe(0);
120 });
121​
122 it("reads a file written before loop delay and GC were recorded", () => {
123 const older = decodeMetrics({
124 meta,
125 runs: [
126 {
127 quiet: { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 },
128 },
129 ],
130 });
131 const result = compareMetrics(older, quietRuns(base));
132 expect(result.compared).toBe(5);
133 expect(result.table).toContain("| quiet.loopDelayP99Ms | – | 1.5 | n/a | | |");
134 });
135​
136 it("does not compare wakeups counted with and without the delay sampler", () => {
137 const sampled = quietRuns({ ...base, wakeupsPerSec: 160 });
138 const withSamples: ServerMetrics = {
139 meta,
140 runs: sampled.runs.map((run) => ({ quiet: { ...run.quiet, loopSamples: 2_900 } })),
141 };
142 const result = compareMetrics(quietRuns(base), withSamples);
143 expect(result.regressed).toEqual([]);
144 expect(result.table).toContain("| quiet.wakeupsPerSec | 7 | 160 | not comparable | | |");
145 // The per-thread fit comes from the quiet windows, so it follows their method.
146 const scaling = (wakeupsPerThread: number) => ({
147 heapMBPerThread: 1,
148 rssMBPerThread: 2,
149 cpuPctPerThread: 0.1,
150 wakeupsPerThread,
151 points: [],
152 });
153 const fitted = (metrics: ServerMetrics, wakeupsPerThread: number): ServerMetrics => ({
154 meta,
155 runs: metrics.runs.map((run) => ({ ...run, scaling: scaling(wakeupsPerThread) })),
156 });
157 const fit = compareMetrics(fitted(quietRuns(base), 0.5), fitted(withSamples, 6));
158 expect(fit.regressed).toEqual([]);
159 expect(fit.table).toContain("| scaling.wakeupsPerThread | 0.5 | 6 | not comparable | | |");
160 expect(compareMetrics(withSamples, withSamples).compared).toBe(10);
161 });
162​
163 it("counts how many metrics both sides share", () => {
164 const startupOnly: ServerMetrics = { meta, runs: [{ startup: { readyMs: 9_000 } }] };
165 expect(compareMetrics(startupOnly, quietRuns(base)).compared).toBe(0);
166 expect(compareMetrics(quietRuns(base), quietRuns(base)).compared).toBe(10);
167 });
168});
169​
170describe("compareMetrics with noise rules", () => {
171 const rules = [
172 { pattern: /cpuPct$/, floor: 1, gate: true },
173 { pattern: /loopDelayMaxMs$/, floor: 20, gate: false },
174 { pattern: /./, floor: 1_000, gate: true },
175 ];
176 it.each([
177 ["a gated metric past its floor", { cpuPct: 5 }, ["quiet.cpuPct"], []],
178 ["an ungated metric far past its floor", { loopDelayMaxMs: 300 }, [], ["quiet.loopDelayMaxMs"]],
179 ["an ungated metric under its floor", { loopDelayMaxMs: 20 }, [], []],
180 ])("%s", (_name, change, regressed, informational) => {
181 const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change }), 10, rules);
182 expect(result.regressed).toEqual(regressed);
183 expect(result.informational).toEqual(informational);
184 });
185​
186 it("marks an ungated metric in the table either way", () => {
187 const result = compareMetrics(quietRuns(base), quietRuns(base), 10, rules);
188 expect(result.table).toContain("| quiet.loopDelayMaxMs | 8 | 8 | 0% | | noisy |");
189 });
190});
191​
192describe("compareMetrics on each platform's noise floors", () => {
193 // The default floor for working.rssMBPerThread is 0.2 MB; Windows A/A runs needed 0.6.
194 const onPlatform = (platform: string, rssMBPerThread: number) => {
195 const working = {
196 active: {},
197 heapMBPerThread: 0.2,
198 rssMBPerThread,
199 cpuPctPerThread: 0,
200 loopDelayP99MsPerThread: 0,
201 };
202 return {
203 meta: { ...meta, platform },
204 runs: [{ working }, { working }],
205 } satisfies ServerMetrics;
206 };
207 const regressed = (before: ServerMetrics, after: ServerMetrics) =>
208 compareMetrics(before, after, 10).regressed;
209​
210 it("gates Linux files on the default floor", () => {
211 expect(regressed(onPlatform("linux-x64", 1), onPlatform("linux-x64", 1.4))).toEqual([
212 "working.rssMBPerThread",
213 ]);
214 });
215​
216 it("gates Windows files on the Windows floor", () => {
217 expect(regressed(onPlatform("win32-x64", 1), onPlatform("win32-x64", 1.4))).toEqual([]);
218 expect(regressed(onPlatform("win32-x64", 1), onPlatform("win32-x64", 1.8))).toEqual([
219 "working.rssMBPerThread",
220 ]);
221 });
222​
223 it("falls back to the default floor with a warning when the platforms differ", () => {
224 const result = compareMetrics(onPlatform("linux-x64", 1), onPlatform("win32-x64", 1.4));
225 expect(result.regressed).toEqual(["working.rssMBPerThread"]);
226 expect(result.warnings).toEqual([
227 "the files come from linux-x64 and win32-x64, so the default noise floors apply",
228 ]);
229 });
230​
231 it("marks the noise report against the platform's floor", () => {
232 const pair = (platform: string) => [onPlatform(platform, 1), onPlatform(platform, 1)] as const;
233 const floor = (platform: string) =>
234 noiseReport([pair(platform)]).rows.find(({ metric }) => metric === "working.rssMBPerThread")
235 ?.floor;
236 expect(floor("linux-x64")).toBe(0.2);
237 expect(floor("win32-x64")).toBe(0.6);
238 });
239});
240​
241describe("noisePairProblem", () => {
242 const at = (commit: string | null): ServerMetrics => ({ meta: { ...meta, commit }, runs: [] });
243 it.each([
244 ["one commit against itself", at("abc"), at("abc"), undefined],
245 [
246 "an A/B directory",
247 at("abc"),
248 at("def"),
249 "ab-out: a.json is abc and b.json def; noise floors need one commit against itself",
250 ],
251 [
252 "a file with no commit",
253 at(null),
254 at(null),
255 "ab-out: a.json or b.json records no commit, so it cannot be shown to be an A/A run",
256 ],
257 ])("%s", (_name, a, b, problem) => {
258 expect(noisePairProblem("ab-out", a, b)).toBe(problem);
259 });
260});
261​
262describe("competingBetween", () => {
263 it.each([
264 ["a process that kept running", [["10:500", 900]], [["10:500", 960]], 60],
265 ["a new process, counted whole", [], [["11:700", 30]], 30],
266 ["a reused pid is a new process", [["10:500", 900]], [["10:800", 300]], 300],
267 ["a process that exited is lost", [["10:500", 900]], [], 0],
268 ] as const)("%s", (_name, before, after, seconds) => {
269 expect(competingBetween(new Map(before), new Map(after))).toBe(seconds);
270 });
271});
272​
273describe("loadWarnings", () => {
274 const loaded = (cpus: number | null, ...machines: Array<[number | null, number | null]>) =>
275 ({
276 meta: { ...meta, cpus },
277 runs: machines.map(([load1, otherCpuCores]) => ({
278 machine: { load1, otherCpuCores, minutes: 10 },
279 })),
280 }) satisfies ServerMetrics;
281 it.each([
282 ["a quiet machine", loaded(16, [4, 1], [5, 2]), 0],
283 ["load past 0.75 per CPU with other processes unknown", loaded(16, [4, null], [12.5, null]), 1],
284 ["high load from the run's own agents", loaded(16, [21, 1]), 0],
285 ["other processes on a quarter of the cores", loaded(16, [4, 4.1]), 1],
286 ["no CPU count", loaded(null, [40, 40]), 0],
287 ["no machine state, as in older files", { meta: { ...meta, cpus: 16 }, runs: [{}] }, 0],
288 ])("%s", (_name, metrics, count) => {
289 expect(loadWarnings("before", metrics)).toHaveLength(count);
290 });
291​
292 it("names the worst run", () => {
293 expect(loadWarnings("after", loaded(16, [13, 4.5], [14.2, 5]))[0]).toContain(
294 "after ran under heavy load in 2 of 2 runs (load up to 14.2 on 16 CPUs, other node/T3/agent processes up to 5 cores)",
295 );
296 });
297​
298 it("is reported by compareMetrics", () => {
299 expect(compareMetrics(quietRuns(base), loaded(16, [20, null])).warnings).toHaveLength(1);
300 });
301});
302​
303describe("noiseReport", () => {
304 it.each([
305 // Resampled medians differ by -0.3 to 1.1: half-width 0.7, so the floor is 0.35.
306 ["the A/A interval", cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3), 0.7, 0.1, 0.35],
307 // Constant sides: no interval, and medians 2 and 3.25 differ by 1.25.
308 ["the A/A median difference", cpuRuns(2, 2), cpuRuns(3.25, 3.25), 0, 1.25, 1.3],
309 ])("estimates a floor from %s, rounded up", (_name, a, b, halfWidth, aaDifference, floor) => {
310 const [row] = noiseReport([[a, b]]).rows.filter(({ metric }) => metric === "quiet.cpuPct");
311 expect(row).toMatchObject({ halfWidth, aaDifference, suggestedFloor: floor });
312 });
313​
314 it("leaves out wakeups counted with the delay sampler on one side only", () => {
315 const sampled: ServerMetrics = {
316 meta,
317 runs: quietRuns({ ...base, wakeupsPerSec: 160 }).runs.map((run) => ({
318 quiet: { ...run.quiet, loopSamples: 2_900 },
319 })),
320 };
321 const metrics = noiseReport([[quietRuns(base), sampled]]).rows.map(({ metric }) => metric);
322 expect(metrics).not.toContain("quiet.wakeupsPerSec");
323 expect(metrics).toContain("quiet.cpuPct");
324 });
325​
326 it("takes the widest pair, and calls a metric noisy when its interval passes half its median", () => {
327 const quiet = [cpuRuns(2, 2.1), cpuRuns(2, 2.1)] as const;
328 const wild = [cpuRuns(1, 4), cpuRuns(2, 2)] as const;
329 const [row] = noiseReport([quiet, wild]).rows.filter(({ metric }) => metric === "quiet.cpuPct");
330 expect(row?.halfWidth).toBe(1.5);
331 expect(row?.suggestedGate).toBe(false);
332 });
333​
334 it("leaves out fields that describe a run", () => {
335 const withMachine = (metrics: ServerMetrics): ServerMetrics => ({
336 ...metrics,
337 runs: metrics.runs.map((run) => ({
338 ...run,
339 machine: { load1: 3, otherCpuCores: 1, minutes: 9 },
340 })),
341 });
342 const rows = noiseReport([[withMachine(cpuRuns(1)), withMachine(cpuRuns(1))]]).rows;
343 expect(rows.some(({ metric }) => metric.startsWith("machine."))).toBe(false);
344 });
345});
346​
347describe("compareMetrics on working throughput", () => {
348 const working = (turnsPerMin: number) =>
349 ({
350 meta,
351 runs: [
352 {
353 working: {
354 active: {
355 "20": {
356 ...loopAtRest,
357 cpuPct: 90,
358 wakeupsPerSec: 1_600,
359 rssPeakMB: 700,
360 rssMB: 560,
361 heapAfterGcMB: 218,
362 turnsPerMin,
363 toRequestMs: { median: 4_000, p90: 9_000 },
364 turnEndMs: { median: 16_000, p90: 25_000 },
365 turnMs: { median: 24_000, p90: 36_000 },
366 },
367 },
368 heapMBPerThread: 0.2,
369 rssMBPerThread: 0.8,
370 cpuPctPerThread: 0,
371 loopDelayP99MsPerThread: 0,
372 },
373 },
374 ],
375 }) satisfies ServerMetrics;
376 const rules = [{ pattern: /turnsPerMin$/, floor: 2, gate: true }];
377 it.each([
378 ["fewer turns a minute", 20, ["working.active.20.turnsPerMin"], []],
379 ["more turns a minute", 45, [], ["working.active.20.turnsPerMin"]],
380 ["a move under the floor", 34, [], []],
381 ])("%s", (_name, turnsPerMin, regressed, improved) => {
382 const result = compareMetrics(working(33), working(turnsPerMin), 5, rules);
383 expect(result.regressed).toEqual(regressed);
384 expect(result.improved).toEqual(improved);
385 });
386});
387​
388describe("compareMetrics on the busy shell snapshot", () => {
389 const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 };
390 const busyRun = (shellMs: number, shellKB: number) =>
391 ({
392 meta,
393 runs: [
394 {
395 busy: {
396 readyMs: 8_000,
397 projects: 9,
398 ballastMB: 768,
399 rest: window,
400 shellMs: { median: shellMs, p90: shellMs },
401 shellKB,
402 git: window,
403 },
404 },
405 ],
406 }) satisfies ServerMetrics;
407 it.each([
408 ["40 ms slower, under the 50 ms floor", busyRun(230, 100), []],
409 ["150 ms slower, past it", busyRun(340, 100), ["busy.shellMs.median", "busy.shellMs.p90"]],
410 ["15 KB larger, under the 20 KB floor", busyRun(190, 115), []],
411 ["40 KB larger, past it", busyRun(190, 140), ["busy.shellKB"]],
412 ])("%s", (_name, after, regressed) => {
413 expect(compareMetrics(busyRun(190, 100), after).regressed).toEqual(regressed);
414 });
415});
416​
417describe("describeFailure", () => {
418 it.each([
419 ["a plain error", new Error("boom"), "boom"],
420 [
421 "an RPC error wrapping the server's",
422 new Error("RpcClientError", { cause: new Error("Command x was already handled") }),
423 "RpcClientError: Command x was already handled",
424 ],
425 ["a tagged error with no message", { _tag: "TimeoutError" }, "TimeoutError"],
426 [
427 "a cause that repeats its wrapper",
428 new Error("lost: gone", { cause: new Error("gone") }),
429 "lost: gone",
430 ],
431 ["a string", "exit 1", "exit 1"],
432 ])("%s", (_name, error, expected) => {
433 expect(describeFailure(error)).toBe(expected);
434 });
435});
436​
437describe("profileMismatch", () => {
438 const withProfile = (profile?: string): ServerMetrics => ({
439 meta: profile === undefined ? meta : { ...meta, profile },
440 runs: [],
441 });
442 it.each([
443 ["two full runs", withProfile("full"), withProfile("full"), false],
444 ["a file from before profiles, against a full run", withProfile(), withProfile("full"), false],
445 ["two quick runs", withProfile("quick"), withProfile("quick"), false],
446 ["a full run against a quick one", withProfile(), withProfile("quick"), true],
447 ])("%s", (_name, before, after, refused) => {
448 expect(profileMismatch(before, after) !== undefined).toBe(refused);
449 });
450});
451​
452describe("heapGrowth", () => {
453 it("lists only constructors that grew, small growth included", () => {
454 const before = new Map([
455 ["Shrank", { count: 10, bytes: 5_000_000 }],
456 ["Flat", { count: 3, bytes: 1_000 }],
457 ["Grew", { count: 1, bytes: 1_000 }],
458 ]);
459 const after = new Map([
460 ["Shrank", { count: 5, bytes: 1_000_000 }],
461 ["Flat", { count: 3, bytes: 1_000 }],
462 ["Grew", { count: 2, bytes: 1_500 }],
463 ["New", { count: 4, bytes: 3_000_000 }],
464 ]);
465 expect(heapGrowth(before, after)).toEqual([
466 { constructor: "New", count: 4, MB: 3 },
467 { constructor: "Grew", count: 1, MB: 0 },
468 ]);
469 });
470});
471​
472describe("heapRetainers", () => {
473 it("sums what each object alone keeps alive and names only code on the way to it", () => {
474 // root → Holder.cache → Map → [0] array → [0] string; Holder also points at the string weakly.
475 const node = (type: number, name: number, id: number, size: number, edges: number) => [
476 type,
477 name,
478 id,
479 size,
480 edges,
481 ];
482 const retainers = heapRetainers(
483 {
484 snapshot: {
485 meta: {
486 node_fields: ["type", "name", "id", "self_size", "edge_count"],
487 node_types: [["synthetic", "object", "array", "string"]],
488 edge_fields: ["type", "name_or_index", "to_node"],
489 edge_types: [["property", "element", "weak", "hidden"]],
490 },
491 },
492 nodes: [
493 ...node(0, 4, 1, 0, 1),
494 ...node(1, 1, 3, 100, 2),
495 ...node(1, 2, 5, 50, 1),
496 ...node(2, 0, 7, 1_000, 1),
497 ...node(3, 5, 9, 500, 0),
498 ],
499 edges: [0, 6, 5, 0, 3, 10, 2, 0, 20, 3, 0, 15, 1, 0, 20],
500 strings: ["", "Holder", "Map", "cache", "(GC roots)", "a secret", "holder"],
501 },
502 0,
503 0,
504 );
505 expect(retainers.get(5)).toEqual({
506 retained: 1_550,
507 dominator: 3,
508 path: "holder → Holder.cache → Map",
509 });
510 expect(retainers.get(3)?.retained).toBe(1_650);
511 expect(retainers.get(9)?.path).toBe("holder → Holder.cache → Map.[0] → (array).[0] → (string)");
512 });
513});
514​
515describe("retainerGrowth", () => {
516 const at = (sizes: Record<number, number>) =>
517 new Map(
518 Object.entries(sizes).map(([id, retained]) => [
519 Number(id),
520 { retained, dominator: Number(id) === 3 ? undefined : 3, path: `node ${id}` },
521 ]),
522 );
523 it("reports the deepest object holding the growth, and only growth at every snapshot", () => {
524 const growth = retainerGrowth([
525 at({ 3: 1_000_000, 5: 900_000, 7: 2_000_000 }),
526 at({ 3: 3_000_000, 5: 2_900_000, 7: 4_000_000 }),
527 at({ 3: 5_000_000, 5: 4_900_000, 7: 3_500_000 }),
528 ]);
529 expect(growth).toEqual([{ path: "node 5", MB: 4, retainedMB: 4.9 }]);
530 });
531 it("keeps an ancestor its reported descendant does not account for", () => {
532 // A chain 1 → 2 → 3 growing by 7, 6 and 5 MB, and 4 under 1 growing by 2 MB.
533 const chain = (scale: number) =>
534 new Map(
535 [
536 [1, 7, undefined],
537 [2, 6, 1],
538 [3, 5, 2],
539 [4, 2, 1],
540 ].map(([id, mb, dominator]) => [
541 id!,
542 { retained: (10 + mb! * scale) * 1e6, dominator, path: `node ${id}` },
543 ]),
544 );
545 expect(retainerGrowth([chain(0), chain(0.5), chain(1)]).map(({ path }) => path)).toEqual([
546 "node 1",
547 "node 3",
548 "node 4",
549 ]);
550 });
551});
552​
553describe("slope", () => {
554 it("fits the cost per thread", () => {
555 const points: Array<readonly [number, number]> = [
556 [0, 175],
557 [5, 180],
558 [10, 185],
559 [20, 195],
560 ];
561 expect(slope(points)).toBeCloseTo(1);
562 });
563});
564​
565describe("parsePsCpuTime", () => {
566 it.each([
567 ["0:00.00", 0],
568 ["1:02.50", 62.5],
569 ["1:00:00.00", 3600],
570 ["2-01:00:00", 2 * 86_400 + 3600],
571 ["1-02:03", Number.NaN],
572 ["::", Number.NaN],
573 ["", Number.NaN],
574 ["1:2:3:4", Number.NaN],
575 ])("%s", (text, seconds) => {
576 expect(parsePsCpuTime(text)).toBe(seconds);
577 });
578});
579​
580describe("parseRunSelection", () => {
581 const scenarios = ["rest", "quiet", "streaming"];
582 it.each([
583 [
584 "the default thread counts",
585 { only: "", threads: "0,5,10,20", soak: 0 },
586 { only: [], threads: [0, 5, 10, 20] },
587 ],
588 [
589 "descending thread counts",
590 { only: "", threads: "5,20,10", soak: 0 },
591 { error: "--threads takes ascending counts such as 0,5,10,20" },
592 ],
593 [
594 "an empty thread count",
595 { only: "", threads: "0,,10", soak: 0 },
596 { error: "--threads takes ascending counts such as 0,5,10,20" },
597 ],
598 [
599 "named scenarios",
600 { only: "rest,quiet", threads: "0", soak: 0 },
601 { only: ["rest", "quiet"], threads: [0] },
602 ],
603 [
604 "an unknown scenario",
605 { only: "rest,idle", threads: "0", soak: 0 },
606 { error: "unknown scenario: idle" },
607 ],
608 ["a soak alone", { only: "", threads: "0", soak: 10 }, { only: ["none"], threads: [0] }],
609 [
610 "a soak with scenarios",
611 { only: "rest", threads: "0", soak: 10 },
612 { only: ["rest"], threads: [0] },
613 ],
614 [
615 "a negative soak",
616 { only: "", threads: "0", soak: -1 },
617 { error: "--soak takes minutes, 0 for none" },
618 ],
619 [
620 "an infinite soak",
621 { only: "", threads: "0", soak: Number.POSITIVE_INFINITY },
622 { error: "--soak takes minutes, 0 for none" },
623 ],
624 ])("%s", (_name, input, expected) => {
625 expect(parseRunSelection({ ...input, scenarios })).toEqual(expected);
626 });
627});
628​
629describe("pathSpellings", () => {
630 it.each([
631 ["a POSIX path, one spelling", "/home/dev/repo", ["/home/dev/repo"]],
632 [
633 "a Windows path as written, JSON-escaped, and with forward slashes",
634 "C:\\Users\\dev\\repo",
635 ["C:\\Users\\dev\\repo", "C:\\\\Users\\\\dev\\\\repo", "C:/Users/dev/repo"],
636 ],
637 [
638 "a path with a quote, escaped the way JSON stores it",
639 '/mnt/dev/quote"repo',
640 ['/mnt/dev/quote"repo', '/mnt/dev/quote\\"repo'],
641 ],
642 [
643 "a path with a control character, escaped the way JSON stores it",
644 "/mnt/dev/new\nline",
645 ["/mnt/dev/new\nline", "/mnt/dev/new\\nline"],
646 ],
647 ])("%s", (_name, path, spellings) => {
648 expect(pathSpellings(path)).toEqual(spellings);
649 });
650});
651​
652describe("pathRewrites", () => {
653 const rewrite = (text: string, from: string, to: string) =>
654 pathRewrites(from, to).reduce((value, [a, b]) => value.replaceAll(a, b), text);
655 it.each([
656 [
657 "a POSIX path in JSON",
658 '{"cwd":"/home/dev/repo/x"}',
659 "/home/dev/repo",
660 "/tmp/run/gone/root-0",
661 '{"cwd":"/tmp/run/gone/root-0/x"}',
662 ],
663 [
664 "a Windows path stored JSON-escaped",
665 '{"cwd":"C:\\\\Users\\\\dev\\\\repo\\\\x"}',
666 "C:\\Users\\dev\\repo",
667 "D:\\run\\gone\\root-0",
668 '{"cwd":"D:\\\\run\\\\gone\\\\root-0\\\\x"}',
669 ],
670 [
671 "a Windows path written with forward slashes",
672 "see C:/Users/dev/repo/x",
673 "C:\\Users\\dev\\repo",
674 "D:\\run\\gone\\root-0",
675 "see D:/run/gone/root-0/x",
676 ],
677 ])("%s", (_name, text, from, to, expected) => {
678 expect(rewrite(text, from, to)).toBe(expected);
679 });
680});
681​
682describe("nextActivityReport", () => {
683 it.each([
684 ["before it is due: wait out the interval", 1_000, 10_000, { waitMs: 16_000, late: false }],
685 ["a slow reply: send now, still inside the lease", 1_000, 31_000, { waitMs: 0, late: false }],
686 ["past the safe point: the lease would lapse", 1_000, 42_000, { waitMs: 0, late: true }],
687 ])("%s", (_name, lastSentAt, now, expected) => {
688 expect(nextActivityReport(lastSentAt, now)).toEqual(expected);
689 });
690});
691​
692describe("activityRenewalMissed", () => {
693 it.each([
694 ["sent on time, answered inside the lease", 25_000, 30_000, false],
695 ["a delayed wake: sent past the safe point", 41_000, 42_000, true],
696 ["sent on time, answered after the lease lapsed", 25_000, 46_000, true],
697 ])("%s", (_name, sentAt, repliedAt, missed) => {
698 expect(activityRenewalMissed(0, sentAt, repliedAt)).toBe(missed);
699 });
700});
701​
702describe("runAbRounds", () => {
703 effectIt.effect("keeps the runs that finished when a later run fails", () =>
704 Effect.gen(function* () {
705 const files: Record<0 | 1, ReadonlyArray<string>> = { 0: [], 1: [] };
706 const failure = yield* Effect.flip(
707 runAbRounds({
708 rounds: 3,
709 outDir: "out",
710 runSide: (side) => (side === 0 ? Effect.succeed("a1") : Effect.fail("b crashed")),
711 save: (side, runs) => Effect.sync(() => (files[side] = [...runs])),
712 }),
713 );
714 expect(failure).toBe("b crashed");
715 expect(files).toEqual({ 0: ["a1"], 1: [] });
716 }),
717 );
718});