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

server-metrics-report.ts

1,069 lines43.4 KB

1// The pure half of scripts/server-metrics.ts: the JSON it writes, and how two of them compare.
2import * as Schema from "effect/Schema";
3​
4const Window = Schema.Struct({
5 cpuPct: Schema.Number,
6 wakeupsPerSec: Schema.NullOr(Schema.Number),
7 rssPeakMB: Schema.Number,
8 rssMB: Schema.Number,
9 heapAfterGcMB: Schema.Number,
10 // Files written before these were recorded still decode, and compare shows them as n/a.
11 /** Event-loop delay past the 10 ms sampling interval, from a histogram inside the server. */
12 loopDelayP50Ms: Schema.optional(Schema.Number),
13 loopDelayP99Ms: Schema.optional(Schema.Number),
14 loopDelayMaxMs: Schema.optional(Schema.Number),
15 /**
16 * Delay samples taken. Each can wake an idle loop, so they sit inside `wakeupsPerSec` (up to
17 * 100/s at rest, near none under load, when the loop is already awake); not compared.
18 */
19 loopSamples: Schema.optional(Schema.Number),
20 /** GC events and their summed pause in the window, from a `gc` PerformanceObserver. */
21 gcCount: Schema.optional(Schema.Number),
22 gcPauseMs: Schema.optional(Schema.Number),
23});
24export type Window = typeof Window.Type;
25const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number });
26const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread });
27export type FirstWord = typeof FirstWord.Type;
28const Scaling = Schema.Struct({
29 heapMBPerThread: Schema.Number,
30 rssMBPerThread: Schema.Number,
31 cpuPctPerThread: Schema.Number,
32 wakeupsPerThread: Schema.NullOr(Schema.Number),
33 /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */
34 points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))),
35});
36const Soak = Schema.Struct({
37 minutes: Schema.Number,
38 heapMBPerHour: Schema.Number,
39 rssMBPerHour: Schema.Number,
40 /** Processes below the server, so agent or git children that outlive their thread show. */
41 childProcessesPerHour: Schema.optional(Schema.Number),
42});
43​
44const MachineState = Schema.Struct({
45 /** The highest 1-minute load average read through the run; none on Windows. */
46 load1: Schema.NullOr(Schema.Number),
47 /** Cores other node, T3 and agent processes kept busy over the run; Linux only. */
48 otherCpuCores: Schema.NullOr(Schema.Number),
49 minutes: Schema.Number,
50});
51export type MachineState = typeof MachineState.Type;
52​
53const WorkingPoint = Schema.Struct({
54 ...Window.fields,
55 /** Turns finished inside the window, per minute; higher is better. */
56 turnsPerMin: Schema.Number,
57 /** Send to the agent's first API request. */
58 toRequestMs: Spread,
59 /** The turn's last reply byte to the client seeing the run end. */
60 turnEndMs: Spread,
61 /** Send to the client seeing the run end. */
62 turnMs: Spread,
63});
64export type WorkingPoint = typeof WorkingPoint.Type;
65​
66const Reconnect = Schema.Struct({
67 clients: Schema.Number,
68 threadsPerClient: Schema.optional(Schema.Number),
69 /** Drop to every subscription delivering its snapshot again. */
70 resubscribedMs: Schema.Number,
71 loopDelayP99Ms: Schema.Number,
72 loopDelayMaxMs: Schema.Number,
73});
74​
75/** One pass over the scenarios. */
76export const Measured = Schema.Struct({
77 /** What else the machine was doing during the pass; never compared, only warned about. */
78 machine: Schema.optional(MachineState),
79 startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })),
80 rest: Schema.optional(Window),
81 firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })),
82 quiet: Schema.optional(Window),
83 scaling: Schema.optional(Scaling),
84 streaming: Schema.optional(Window),
85 soak: Schema.optional(Soak),
86 /** One web-like client attached over the WebSocket RPC, with N threads subscribed. */
87 clients: Schema.optional(
88 Schema.Struct({
89 /** The quiet window by subscribed thread count. */
90 attached: Schema.Record(Schema.String, Window),
91 /** A user's few devices, each holding the shell, VCS status and threads, drop and reconnect. */
92 reconnect: Schema.optional(Reconnect),
93 /** With --stress: 20 clients holding one thread each drop and reconnect at once. */
94 storm: Schema.optional(Reconnect),
95 }),
96 ),
97 /**
98 * N threads in worktrees of their own run editing turns back to back, all at once, with one
99 * web-like client subscribed to all of them. The scenario to steer server performance by.
100 */
101 working: Schema.optional(
102 Schema.Struct({
103 /** Each window by the number of threads working in it. */
104 active: Schema.Record(Schema.String, WorkingPoint),
105 /** Fits over the windows: what each additional working thread costs. */
106 heapMBPerThread: Schema.Number,
107 rssMBPerThread: Schema.Number,
108 cpuPctPerThread: Schema.Number,
109 loopDelayP99MsPerThread: Schema.Number,
110 }),
111 ),
112 /** 50 short turns back to back on one thread. */
113 pipeline: Schema.optional(
114 Schema.Struct({
115 /** Send to the agent's API request. */
116 toRequestMs: Spread,
117 /** The reply's last byte to the CLI seeing a finished run: turn end and checkpoint. */
118 turnEndMs: Spread,
119 /** Wall time per turn, the CLI's own start included. */
120 msPerTurn: Schema.Number,
121 loopDelayP99Ms: Schema.Number,
122 loopDelayMaxMs: Schema.Number,
123 gcPauseMs: Schema.Number,
124 }),
125 ),
126 /** A server on a copy of the developer's real database, its projects backed by clones. */
127 busy: Schema.optional(
128 Schema.Struct({
129 readyMs: Schema.Number,
130 projects: Schema.Number,
131 /** Off-heap MB the server held so its RSS is a long-lived server's; not compared. */
132 ballastMB: Schema.Number,
133 rest: Window,
134 shellMs: Spread,
135 shellKB: Schema.Number,
136 /** The seeded thread with the most messages, opened through its bounded HTTP snapshot. */
137 largeThread: Schema.optional(
138 Schema.Struct({
139 messages: Schema.Number,
140 openMs: Spread,
141 KB: Schema.Number,
142 /** Heap after GC once it was opened, less before. */
143 heapMB: Schema.Number,
144 }),
145 ),
146 /** Back-to-back turns in a clone, each ending in a checkpoint. */
147 git: Window,
148 }),
149 ),
150});
151export type Measured = typeof Measured.Type;
152​
153const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number });
154export type Hotspot = typeof Hotspot.Type;
155const ProfileSummary = Schema.Struct({
156 cpuMs: Schema.Array(Hotspot),
157 allocatedMB: Schema.Array(Hotspot),
158});
159export type ProfileSummary = typeof ProfileSummary.Type;
160export const HeapGrowth = Schema.Struct({
161 constructor: Schema.String,
162 count: Schema.Number,
163 MB: Schema.Number,
164});
165​
166/** An object whose retained size grew at every soak snapshot, and how it is reached. */
167export const RetainerGrowth = Schema.Struct({
168 path: Schema.String,
169 MB: Schema.Number,
170 retainedMB: Schema.Number,
171});
172export type RetainerGrowth = typeof RetainerGrowth.Type;
173​
174export const ServerMetrics = Schema.Struct({
175 meta: Schema.Record(
176 Schema.String,
177 Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
178 ),
179 runs: Schema.Array(Measured),
180 /** Top CPU self time (ms) and allocated MB by function, from the last run. */
181 profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)),
182 soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)),
183 soakRetainerGrowth: Schema.optional(Schema.Array(RetainerGrowth)),
184});
185export type ServerMetrics = typeof ServerMetrics.Type;
186​
187export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits;
188​
189/** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */
190export function parsePsCpuTime(text: string) {
191 const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim());
192 if (match === null) return Number.NaN;
193 const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match;
194 return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
196​
197/**
198 * `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay
199 * open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else.
200 */
201export function parseRunSelection(input: {
202 readonly only: string;
203 readonly threads: string;
204 readonly soak: number;
205 readonly scenarios: ReadonlyArray<string>;
206}):
207 | { readonly only: ReadonlyArray<string>; readonly threads: ReadonlyArray<number> }
208 | { readonly error: string } {
209 const only = input.only.split(",").filter(Boolean);
210 const unknown = only.filter((name) => !input.scenarios.includes(name));
211 if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` };
212 const threads = input.threads
213 .split(",")
214 .map((count) => (count.trim() === "" ? Number.NaN : Number(count)));
215 if (
216 threads.some(
217 (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0),
218 )
219 ) {
220 return { error: "--threads takes ascending counts such as 0,5,10,20" };
221 }
222 if (!Number.isInteger(input.soak) || input.soak < 0)
223 return { error: "--soak takes minutes, 0 for none" };
224 return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads };
226​
227export function spread(values: ReadonlyArray<number>) {
228 const sorted = values.toSorted((a, b) => a - b);
229 const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)];
230 return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) };
232​
233/** Least-squares slope of y over x. */
234export function slope(points: ReadonlyArray<readonly [number, number]>) {
235 const n = points.length;
236 if (n < 2) return 0;
237 const mx = points.reduce((sum, [x]) => sum + x, 0) / n;
238 const my = points.reduce((sum, [, y]) => sum + y, 0) / n;
239 let numerator = 0;
240 let denominator = 0;
241 for (const [x, y] of points) {
242 numerator += (x - mx) * (y - my);
243 denominator += (x - mx) ** 2;
244 }
245 return denominator === 0 ? 0 : numerator / denominator;
247​
248/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */
249export function flatten(measured: Measured): Map<string, number> {
250 const values = new Map<string, number>();
251 const visit = (value: unknown, path: string) => {
252 if (typeof value === "number") values.set(path, value);
253 else if (value && typeof value === "object") {
254 for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key);
255 }
256 };
257 visit(measured, "");
258 return values;
260​
261/**
262 * How far a metric moves between runs of the same commit, and whether it moves little enough to
263 * gate on. First match wins. Re-derive from A/A files with `server-metrics noise`; see
264 * docs/internals/performance-regressions.md for the runs these came from.
265 */
266export interface NoiseRule {
267 readonly pattern: RegExp;
268 /** Absolute change a metric must clear on top of the relative threshold. */
269 readonly floor: number;
270 /** False for metrics an A/A run moves too far to gate on: shown, never counted. */
271 readonly gate: boolean;
273​
274/** Shown, never counted: these A/A intervals were wider than half the metric (see `noise`). */
275const informational = (pattern: RegExp): NoiseRule => ({ pattern, floor: 0, gate: false });
276​
277// Estimated from A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, with and without the
278// agent scope, rounded up and taking the larger of the two.
279// busy and soak had no A/A run and keep the earlier floors.
280export const NOISE_RULES: ReadonlyArray<NoiseRule> = [
281 informational(/loopDelayP50Ms$/),
282 informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/),
283 informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/),
284 informational(/^(streaming|pipeline)\.gcPauseMs$/),
285 informational(
286 /^(pipeline\.loopDelayMaxMs|clients\.(storm|reconnect)\.loopDelayP99Ms|quiet\.cpuPct)$/,
287 ),
288 informational(/^scaling\.(cpuPct|wakeups)PerThread$/),
289 informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/),
290 informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/),
291 { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true },
292 { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true },
293 { pattern: /^soak\./, floor: 20, gate: true },
294 informational(/^working\.(cpuPct|loopDelayP99Ms)PerThread$/),
295 informational(/^working\.active\.\d+\.(wakeupsPerSec|loopDelayMaxMs|gcPauseMs)$/),
296 { pattern: /^working\.heapMBPerThread$/, floor: 0.06, gate: true },
297 { pattern: /^working\.rssMBPerThread$/, floor: 0.2, gate: true },
298 { pattern: /^working\.active\.\d+\.turnsPerMin$/, floor: 4, gate: true },
299 { pattern: /^working\.active\.\d+\.toRequestMs\.median$/, floor: 1_100, gate: true },
300 { pattern: /^working\.active\.\d+\.turnEndMs\.median$/, floor: 1_700, gate: true },
301 {
302 pattern: /^working\.active\.\d+\.(toRequestMs\.p90|turnMs\.median)$/,
303 floor: 1_900,
304 gate: true,
305 },
306 { pattern: /^working\.active\.\d+\.turnEndMs\.p90$/, floor: 2_200, gate: true },
307 { pattern: /^working\.active\.\d+\.turnMs\.p90$/, floor: 2_800, gate: true },
308 // Peak RSS while 20 agents run swings by a checkpoint's git children; the settled RSS does not.
309 { pattern: /^working\.active\.\d+\.rssPeakMB$/, floor: 170, gate: true },
310 { pattern: /^working\.active\.\d+\.(cpuPct|loopDelayP99Ms)$/, floor: 5, gate: true },
311 { pattern: /^working\.active\.\d+\.gcCount$/, floor: 8, gate: true },
312 { pattern: /^startup\.readyMs$/, floor: 600, gate: true },
313 { pattern: /^firstWord\./, floor: 600, gate: true },
314 { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true },
315 { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true },
316 // The reconnect had no A/A run yet and takes the storm's floors.
317 { pattern: /^clients\.(storm|reconnect)\.resubscribedMs$/, floor: 200, gate: true },
318 { pattern: /^rest\.cpuPct$/, floor: 1, gate: true },
319 { pattern: /cpuPct$/, floor: 3.5, gate: true },
320 { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true },
321 { pattern: /wakeupsPerSec$/, floor: 110, gate: true },
322 { pattern: /rssPeakMB$/, floor: 16, gate: true },
323 { pattern: /rssMB$/, floor: 4, gate: true },
324 { pattern: /heapAfterGcMB$/, floor: 1, gate: true },
325 { pattern: /MB$/, floor: 15, gate: true },
326 { pattern: /KB$/, floor: 20, gate: true },
327 { pattern: /\.(shellMs|openMs)\./, floor: 50, gate: true },
328 { pattern: /loopDelayP99Ms$/, floor: 3, gate: true },
329 { pattern: /loopDelayMaxMs$/, floor: 22, gate: true },
330 { pattern: /gcPauseMs$/, floor: 55, gate: true },
331 { pattern: /gcCount$/, floor: 6, gate: true },
332 { pattern: /./, floor: 300, gate: true },
333];
334​
335// Estimated from one quick A/A run (3 rounds) on a 4-vCPU Azure Windows Server 2025 VM on
336// 2026-11-23, rounded up. Consulted before NOISE_RULES on that OS. macOS has no A/A run yet and
337// takes the defaults.
338const NOISE_RULE_OVERRIDES: Partial<Record<string, ReadonlyArray<NoiseRule>>> = {
339 win32: [
340 informational(/^working\.active\.20\.toRequestMs\.p90$/),
341 { pattern: /^working\.rssMBPerThread$/, floor: 0.6, gate: true },
342 { pattern: /^scaling\.rssMBPerThread$/, floor: 0.5, gate: true },
343 { pattern: /^working\.active\.\d+\.rssMB$/, floor: 10, gate: true },
344 { pattern: /^working\.active\.\d+\.loopDelayP99Ms$/, floor: 6, gate: true },
345 { pattern: /^pipeline\.loopDelayP99Ms$/, floor: 8, gate: true },
346 { pattern: /^streaming\.heapAfterGcMB$/, floor: 1.5, gate: true },
347 ],
348};
349​
350/**
351 * The rules for the platform (`meta.platform`, e.g. `win32-x64`) every file recorded. Files from
352 * different platforms get the defaults and a warning.
353 */
354export function noiseRulesFor(files: ReadonlyArray<ServerMetrics>) {
355 const platforms = [...new Set(files.map(({ meta }) => String(meta.platform ?? "")))];
356 if (platforms.length !== 1) {
357 return {
358 rules: NOISE_RULES,
359 warning: `the files come from ${platforms.join(" and ")}, so the default noise floors apply`,
360 };
361 }
362 const overrides = NOISE_RULE_OVERRIDES[platforms[0]!.split("-")[0]!] ?? [];
363 return { rules: [...overrides, ...NOISE_RULES], warning: undefined };
365​
366export function noiseRule(metric: string, rules: ReadonlyArray<NoiseRule> = NOISE_RULES) {
367 return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true };
369​
370/** An error and the errors it wraps as one line, outermost first, repeats left out. */
371export function describeFailure(error: unknown): string {
372 const parts: string[] = [];
373 const seen = new Set<unknown>();
374 for (let at = error; at !== undefined && at !== null && !seen.has(at);) {
375 seen.add(at);
376 if (typeof at !== "object") {
377 parts.push(String(at));
378 break;
379 }
380 const tag = "_tag" in at && typeof at._tag === "string" ? at._tag : undefined;
381 const message = "message" in at && typeof at.message === "string" ? at.message.trim() : "";
382 const text = message || tag || String(at);
383 if (!parts.some((part) => part.includes(text))) parts.push(text);
384 at = "cause" in at ? at.cause : undefined;
385 }
386 return parts.join(": ");
388​
389/** Why two files cannot be compared at all: a quick run measures shorter windows than a full one. */
390export function profileMismatch(before: ServerMetrics, after: ServerMetrics) {
391 const profile = (metrics: ServerMetrics) => metrics.meta.profile ?? "full";
392 return profile(before) === profile(after)
393 ? undefined
394 : `before is a ${profile(before)} run and after a ${profile(after)} one; compare quick runs only with quick runs`;
396​
397/** Throughput, where a drop is the regression. */
398export const higherIsBetter = (metric: string) => metric.endsWith("PerMin");
399​
400/** Fields that describe a run rather than measure it. */
401const isMetric = (metric: string) =>
402 !(
403 metric === "soak.minutes" ||
404 metric.startsWith("machine.") ||
405 metric.endsWith("loopSamples") ||
406 metric === "busy.projects" ||
407 metric === "busy.ballastMB" ||
408 metric.endsWith(".clients") ||
409 metric.endsWith(".threadsPerClient") ||
410 metric.endsWith(".threads") ||
411 metric === "busy.largeThread.messages" ||
412 metric.startsWith("scaling.points")
413 );
414​
415/**
416 * A run is loaded when other node, T3 and agent processes kept this share of the cores busy, or,
417 * where that is unknown, when the 1-minute load passed this much per CPU. The load counts the
418 * run's own agents too, so it is only the fallback.
419 */
420export const HEAVY_LOAD_PER_CPU = 0.75;
421export const HEAVY_OTHER_CPU_SHARE = 0.25;
422​
423/** One line per side whose runs shared the machine with heavy load, so its numbers are suspect. */
424export function loadWarnings(side: string, metrics: ServerMetrics) {
425 const cpus = typeof metrics.meta.cpus === "number" ? metrics.meta.cpus : null;
426 if (cpus === null) return [];
427 const loaded = metrics.runs.flatMap(({ machine }) =>
428 machine &&
429 (machine.otherCpuCores === null
430 ? (machine.load1 ?? 0) >= cpus * HEAVY_LOAD_PER_CPU
431 : machine.otherCpuCores >= cpus * HEAVY_OTHER_CPU_SHARE)
432 ? [machine]
433 : [],
434 );
435 if (loaded.length === 0) return [];
436 const worstLoad = Math.max(...loaded.map(({ load1 }) => load1 ?? 0));
437 const worstOther = Math.max(...loaded.map(({ otherCpuCores }) => otherCpuCores ?? 0));
438 return [
439 `${side} ran under heavy load in ${loaded.length} of ${metrics.runs.length} runs (load up to ${worstLoad} on ${cpus} CPUs, other node/T3/agent processes up to ${worstOther} cores); rerun on a quieter machine before trusting a change`,
440 ];
442​
443const median = (values: ReadonlyArray<number>) => {
444 const sorted = values.toSorted((a, b) => a - b);
445 const middle = Math.floor(sorted.length / 2);
446 return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
447};
448​
449/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */
450export function bootstrapMedianDifference(a: ReadonlyArray<number>, b: ReadonlyArray<number>) {
451 let seed = 0x5eed;
452 const random = () => {
453 seed = (seed + 0x6d2b79f5) | 0;
454 let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
455 t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
456 return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
457 };
458 const resample = (values: ReadonlyArray<number>) =>
459 median(Array.from(values, () => values[Math.floor(random() * values.length)]!));
460 const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted(
461 (x, y) => x - y,
462 );
463 return [differences[49]!, differences[1_949]!] as const;
465​
466/**
467 * False for a wakeup count where only one side had the delay sampler: wakeups include the
468 * sampler's only when `loopSamples` sits beside them, so the two measured different things. The
469 * per-thread fit comes from the quiet windows, so it follows their method.
470 */
471function sameWakeupMethod(
472 metric: string,
473 a: ReadonlyMap<string, unknown>,
474 b: ReadonlyMap<string, unknown>,
475) {
476 const window =
477 metric === "scaling.wakeupsPerThread"
478 ? "quiet."
479 : metric.endsWith("wakeupsPerSec")
480 ? metric.slice(0, -"wakeupsPerSec".length)
481 : "";
482 return !window || a.has(`${window}loopSamples`) === b.has(`${window}loopSamples`);
484​
485/** CPU seconds spent between two reads keyed by pid and start time; a process that exited is lost. */
486export function competingBetween(
487 before: ReadonlyMap<string, number>,
488 after: ReadonlyMap<string, number>,
489) {
490 return [...after].reduce((total, [key, seconds]) => total + seconds - (before.get(key) ?? 0), 0);
492​
493/** Why a directory is not an A/A pair: its files must record one and the same commit. */
494export function noisePairProblem(dir: string, a: ServerMetrics, b: ServerMetrics) {
495 const commits = [a.meta.commit, b.meta.commit];
496 if (commits.some((commit) => typeof commit !== "string" || commit === "")) {
497 return `${dir}: a.json or b.json records no commit, so it cannot be shown to be an A/A run`;
498 }
499 return commits[0] === commits[1]
500 ? undefined
501 : `${dir}: a.json is ${commits[0]} and b.json ${commits[1]}; noise floors need one commit against itself`;
503​
504/** Every metric's values across a file's runs. */
505const collect = (metrics: ServerMetrics) => {
506 const values = new Map<string, number[]>();
507 for (const run of metrics.runs) {
508 for (const [metric, value] of flatten(run)) {
509 values.set(metric, [...(values.get(metric) ?? []), value]);
510 }
511 }
512 return values;
513};
514​
515/** Two significant digits, rounded up, so a derived floor never sits under what was seen. */
516const ceilSignificant = (value: number) => {
517 if (value <= 0) return 0;
518 const step = 10 ** (Math.floor(Math.log10(value)) - 1);
519 return round(Math.ceil(value / step) * step, 6);
520};
521​
522/** An A/A interval wider than this share of a metric's median makes it informational. */
523export const NOISY_SHARE = 0.5;
524​
525export interface NoiseRow {
526 readonly metric: string;
527 readonly median: number;
528 /** The widest half-width of an A/A pair's 95% interval of the median difference. */
529 readonly halfWidth: number;
530 /** The largest |median(A) - median(B)| over the A/A pairs. */
531 readonly aaDifference: number;
532 readonly floor: number;
533 readonly suggestedFloor: number;
534 readonly gate: boolean;
535 readonly suggestedGate: boolean;
537​
538/**
539 * Each metric's A/A spread as `compare` sees it: the 95% interval of the median difference. The
540 * estimated floor (half the widest half-width, or the A/A median difference if larger) is how far
541 * an A/A interval must miss zero to flag. It is an estimate, not a bound.
542 */
543export function noiseReport(
544 pairs: ReadonlyArray<readonly [ServerMetrics, ServerMetrics]>,
545 rules: ReadonlyArray<NoiseRule> = noiseRulesFor(pairs.flat()).rules,
546) {
547 const found = new Map<string, { medians: number[]; halfWidth: number; aaDifference: number }>();
548 for (const [before, after] of pairs) {
549 const a = collect(before);
550 const b = collect(after);
551 for (const [metric, x] of a) {
552 const y = b.get(metric);
553 if (!y || !isMetric(metric) || !sameWakeupMethod(metric, a, b)) continue;
554 const [low, high] = bootstrapMedianDifference(x, y);
555 const entry = found.get(metric) ?? { medians: [], halfWidth: 0, aaDifference: 0 };
556 entry.medians.push(median([...x, ...y]));
557 entry.halfWidth = Math.max(entry.halfWidth, (high - low) / 2);
558 entry.aaDifference = Math.max(entry.aaDifference, Math.abs(median(y) - median(x)));
559 found.set(metric, entry);
560 }
561 }
562 const rows: NoiseRow[] = [...found].map(([metric, entry]) => {
563 const middle = median(entry.medians);
564 const rule = noiseRule(metric, rules);
565 return {
566 metric,
567 median: round(middle, 2),
568 halfWidth: round(entry.halfWidth, 2),
569 aaDifference: round(entry.aaDifference, 2),
570 floor: rule.floor,
571 suggestedFloor: ceilSignificant(Math.max(entry.halfWidth / 2, entry.aaDifference)),
572 gate: rule.gate,
573 suggestedGate: entry.halfWidth <= Math.abs(middle) * NOISY_SHARE,
574 };
575 });
576 const lines = [
577 "| metric | median | ± A/A interval | A/A diff | floor | estimated floor | gated | suggest gating |",
578 "| :-- | --: | --: | --: | --: | --: | :-: | :-: |",
579 ...rows.map(
580 (row) =>
581 `| ${row.metric} | ${row.median} | ${row.halfWidth} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`,
582 ),
583 ];
584 return { rows, table: lines.join("\n") };
586​
587export function compareMetrics(
588 before: ServerMetrics,
589 after: ServerMetrics,
590 threshold = 10,
591 rules?: ReadonlyArray<NoiseRule>,
592) {
593 const forPlatform = noiseRulesFor([before, after]);
594 const gating = rules ?? forPlatform.rules;
595 const a = collect(before);
596 const b = collect(after);
597 const lines = [
598 "### Server metrics (lower is better, except throughput per minute)",
599 "",
600 `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`,
601 "",
602 "| metric | before | after | change | 95% interval | |",
603 "| :-- | --: | --: | --: | --: | :-- |",
604 ];
605 const regressed: string[] = [];
606 const improved: string[] = [];
607 let compared = 0;
608 const informational: string[] = [];
609 for (const metric of new Set([...a.keys(), ...b.keys()])) {
610 if (!isMetric(metric)) continue;
611 const x = a.get(metric);
612 const y = b.get(metric);
613 if (!x || !y) {
614 lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`);
615 continue;
616 }
617 // Wakeups include the delay sampler's only when `loopSamples` sits beside them, so a file
618 // from before the sampler and one from after measured different things. The per-thread fit
619 // comes from the quiet windows.
620 if (!sameWakeupMethod(metric, a, b)) {
621 lines.push(`| ${metric} | ${median(x)} | ${median(y)} | not comparable | | |`);
622 continue;
623 }
624 compared++;
625 const mx = median(x);
626 const my = median(y);
627 // A change counts only past both the relative threshold and the absolute noise floor.
628 const rule = noiseRule(metric, gating);
629 const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100);
630 const repeated = x.length > 1 && y.length > 1;
631 const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx];
632 const up = low > limit ? "worse" : high < -limit ? "better" : "";
633 const moved = higherIsBetter(metric) ? { worse: "better", better: "worse", "": "" }[up] : up;
634 if (moved && !rule.gate) informational.push(metric);
635 else if (moved === "worse") regressed.push(metric);
636 else if (moved === "better") improved.push(metric);
637 const verdict = rule.gate ? moved : moved ? `${moved} (noisy, not gated)` : "noisy";
638 const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100;
639 const shown = Number.isFinite(percent)
640 ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%`
641 : "new";
642 const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : "";
643 lines.push(
644 `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`,
645 );
646 }
647 const warnings = [
648 ...(rules || !forPlatform.warning ? [] : [forPlatform.warning]),
649 ...loadWarnings("before", before),
650 ...loadWarnings("after", after),
651 ];
652 return { table: lines.join("\n"), regressed, improved, informational, compared, warnings };
654​
655const CallFrame = Schema.Struct({
656 functionName: Schema.String,
657 url: Schema.String,
658 lineNumber: Schema.Number,
659});
660type CallFrame = typeof CallFrame.Type;
661export const CpuProfile = Schema.Struct({
662 nodes: Schema.Array(
663 Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }),
664 ),
665 samples: Schema.optional(Schema.Array(Schema.Number)),
666 startTime: Schema.Number,
667 endTime: Schema.Number,
668});
669interface HeapProfileNode {
670 readonly callFrame: CallFrame;
671 readonly selfSize: number;
672 readonly children: ReadonlyArray<HeapProfileNode>;
674const HeapProfileNode: Schema.Codec<HeapProfileNode> = Schema.Struct({
675 callFrame: CallFrame,
676 selfSize: Schema.Number,
677 children: Schema.Array(Schema.suspend(() => HeapProfileNode)),
678});
679export const HeapProfile = Schema.Struct({ head: HeapProfileNode });
680​
681const shortUrl = (url: string) =>
682 url
683 .replace(/^file:\/\//, "")
684 .split(/[\\/]/)
685 .slice(-3)
686 .join("/");
687const frameName = (frame: CallFrame) =>
688 `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim();
689const top = (totals: Map<string, number>, digits: number): Hotspot[] =>
690 [...totals]
691 .toSorted((a, b) => b[1] - a[1])
692 .slice(0, 10)
693 .map(([frame, value]) => ({ frame, value: round(value, digits) }));
694​
695/** Top CPU self time in ms and allocated MB, by function. */
696export function summarizeProfiles(
697 cpu: typeof CpuProfile.Type,
698 heap: typeof HeapProfile.Type,
699): ProfileSummary {
700 const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1);
701 const cpuTotals = new Map<string, number>();
702 for (const node of cpu.nodes) {
703 if (!node.hitCount || node.callFrame.functionName === "(idle)") continue;
704 const name = frameName(node.callFrame);
705 cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs);
706 }
707 const allocations = new Map<string, number>();
708 const visit = (node: HeapProfileNode) => {
709 const name = frameName(node.callFrame);
710 allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6);
711 for (const child of node.children) visit(child);
712 };
713 visit(heap.head);
714 return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) };
716​
717const TypeNames = Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String]));
718export const HeapSnapshot = Schema.Struct({
719 snapshot: Schema.Struct({
720 meta: Schema.Struct({
721 node_fields: Schema.Array(Schema.String),
722 node_types: TypeNames,
723 edge_fields: Schema.Array(Schema.String),
724 edge_types: TypeNames,
725 }),
726 }),
727 nodes: Schema.Array(Schema.Number),
728 edges: Schema.Array(Schema.Number),
729 strings: Schema.Array(Schema.String),
730});
731type HeapSnapshot = typeof HeapSnapshot.Type;
732​
733/** Self size by constructor from a V8 heap snapshot. */
734export function heapByConstructor(snapshot: HeapSnapshot) {
735 const fields = snapshot.snapshot.meta.node_fields;
736 const typeNames = snapshot.snapshot.meta.node_types[0];
737 const types = Array.isArray(typeNames) ? typeNames : [];
738 const typeAt = fields.indexOf("type");
739 const nameAt = fields.indexOf("name");
740 const sizeAt = fields.indexOf("self_size");
741 const totals = new Map<string, { count: number; bytes: number }>();
742 for (let index = 0; index < snapshot.nodes.length; index += fields.length) {
743 const type = types[snapshot.nodes[index + typeAt]!] ?? "?";
744 const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? "";
745 const name =
746 type === "object"
747 ? label.slice(0, 80)
748 : type === "closure"
749 ? `(closure) ${label.slice(0, 60)}`
750 : `(${type.replace(/^(concatenated|sliced) /, "")})`;
751 const entry = totals.get(name) ?? { count: 0, bytes: 0 };
752 entry.count++;
753 entry.bytes += snapshot.nodes[index + sizeAt]!;
754 totals.set(name, entry);
755 }
756 return totals;
758​
759/** The constructors whose heap grew most from one snapshot to the next. */
760export function heapGrowth(
761 before: ReturnType<typeof heapByConstructor>,
762 after: ReturnType<typeof heapByConstructor>,
763) {
764 return [...after]
765 .map(([name, { count, bytes }]) => ({
766 constructor: name,
767 count: count - (before.get(name)?.count ?? 0),
768 bytes: bytes - (before.get(name)?.bytes ?? 0),
769 }))
770 .filter((entry) => entry.bytes > 0)
771 .toSorted((a, b) => b.bytes - a.bytes)
772 .slice(0, 25)
773 .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) }));
775​
776interface Retainer {
777 readonly retained: number;
778 /** The id of the node that dominates this one, none for the root. */
779 readonly dominator: number | undefined;
780 /** Empty below `pathBytes`: such a node is only kept to compare sizes across snapshots. */
781 readonly path: string;
783​
784const TEXT_NODES = new Set(["string", "concatenated string", "sliced string", "regexp", "number"]);
785const IDENTIFIER = /^[A-Za-z_$#][\w$]{0,48}$/;
786​
787/**
788 * Retained size by node id for every node retaining at least `minBytes`, and for those retaining
789 * `pathBytes` the shortest strong path from the root to it. Node ids are stable within one process, so snapshots of one
790 * server line up. Paths name only code: string contents and non-identifier keys are left out.
791 */
792export function heapRetainers(snapshot: HeapSnapshot, minBytes = 16_000, pathBytes = 256_000) {
793 const { meta } = snapshot.snapshot;
794 const nodeFields = meta.node_fields.length;
795 const edgeFields = meta.edge_fields.length;
796 const list = (names: typeof meta.node_types) => {
797 const first = names[0];
798 return Array.isArray(first) ? first : [];
799 };
800 const nodeTypes = list(meta.node_types);
801 const edgeTypes = list(meta.edge_types);
802 const [typeAt, nameAt, idAt, sizeAt, edgeCountAt] = [
803 "type",
804 "name",
805 "id",
806 "self_size",
807 "edge_count",
808 ].map((field) => meta.node_fields.indexOf(field)) as [number, number, number, number, number];
809 const [edgeTypeAt, edgeNameAt, toAt] = ["type", "name_or_index", "to_node"].map((field) =>
810 meta.edge_fields.indexOf(field),
811 ) as [number, number, number];
812 const { nodes, edges, strings } = snapshot;
813 const count = nodes.length / nodeFields;
814 const firstEdge = new Uint32Array(count + 1);
815 for (let node = 0, offset = 0; node < count; node++) {
816 firstEdge[node] = offset;
817 offset += nodes[node * nodeFields + edgeCountAt]! * edgeFields;
818 firstEdge[node + 1] = offset;
819 }
820 const weak = edgeTypes.indexOf("weak");
821 const shortcut = edgeTypes.indexOf("shortcut");
822 const strong = (edge: number) =>
823 edges[edge + edgeTypeAt] !== weak && edges[edge + edgeTypeAt] !== shortcut;
824 const target = (edge: number) => edges[edge + toAt]! / nodeFields;
825​
826 // Postorder from the root, then dominators by Cooper, Harvey and Kennedy's iteration.
827 const postorder = new Int32Array(count).fill(-1);
828 const order = new Int32Array(count);
829 const stack = new Int32Array(count);
830 const cursor = new Uint32Array(count);
831 const seen = new Uint8Array(count);
832 let depth = 0;
833 let visited = 0;
834 stack[depth++] = 0;
835 seen[0] = 1;
836 cursor[0] = firstEdge[0]!;
837 while (depth > 0) {
838 const node = stack[depth - 1]!;
839 if (cursor[node]! < firstEdge[node + 1]!) {
840 const edge = cursor[node]!;
841 cursor[node] = edge + edgeFields;
842 const next = target(edge);
843 if (strong(edge) && !seen[next]) {
844 seen[next] = 1;
845 cursor[next] = firstEdge[next]!;
846 stack[depth++] = next;
847 }
848 } else {
849 depth--;
850 postorder[node] = visited;
851 order[visited++] = node;
852 }
853 }
854 const predecessorStart = new Uint32Array(count + 1);
855 for (let node = 0; node < count; node++) {
856 if (!seen[node]) continue;
857 for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) {
858 if (strong(edge)) predecessorStart[target(edge) + 1]!++;
859 }
860 }
861 for (let node = 0; node < count; node++) predecessorStart[node + 1]! += predecessorStart[node]!;
862 const predecessors = new Int32Array(predecessorStart[count]!);
863 const fill = predecessorStart.slice(0, count);
864 for (let node = 0; node < count; node++) {
865 if (!seen[node]) continue;
866 for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) {
867 if (strong(edge)) predecessors[fill[target(edge)]!++] = node;
868 }
869 }
870 const dominator = new Int32Array(count).fill(-1);
871 dominator[0] = 0;
872 const intersect = (left: number, right: number) => {
873 while (left !== right) {
874 while (postorder[left]! < postorder[right]!) left = dominator[left]!;
875 while (postorder[right]! < postorder[left]!) right = dominator[right]!;
876 }
877 return left;
878 };
879 for (let changed = true; changed;) {
880 changed = false;
881 for (let index = visited - 2; index >= 0; index--) {
882 const node = order[index]!;
883 let found = -1;
884 for (let at = predecessorStart[node]!; at < predecessorStart[node + 1]!; at++) {
885 const predecessor = predecessors[at]!;
886 if (dominator[predecessor] === -1) continue;
887 found = found === -1 ? predecessor : intersect(predecessor, found);
888 }
889 if (found !== -1 && dominator[node] !== found) {
890 dominator[node] = found;
891 changed = true;
892 }
893 }
894 }
895 const retained = new Float64Array(count);
896 for (let node = 0; node < count; node++) retained[node] = nodes[node * nodeFields + sizeAt]!;
897 for (let index = 0; index < visited - 1; index++) {
898 const node = order[index]!;
899 retained[dominator[node]!]! += retained[node]!;
900 }
901​
902 const parent = new Int32Array(count).fill(-1);
903 const parentEdge = new Int32Array(count).fill(-1);
904 const queue = new Int32Array(count);
905 let head = 0;
906 let tail = 0;
907 queue[tail++] = 0;
908 parent[0] = 0;
909 while (head < tail) {
910 const node = queue[head++]!;
911 for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) {
912 const next = target(edge);
913 if (!strong(edge) || parent[next] !== -1) continue;
914 parent[next] = node;
915 parentEdge[next] = edge;
916 queue[tail++] = next;
917 }
918 }
919 const nodeType = (node: number) => nodeTypes[nodes[node * nodeFields + typeAt]!] ?? "?";
920 const label = (node: number) => {
921 const type = nodeType(node);
922 if (TEXT_NODES.has(type)) return `(${type})`;
923 const name = strings[nodes[node * nodeFields + nameAt]!] ?? "";
924 const shown = name.length > 60 || /["'`\n\\]|:\/\/|(^|\s)\/[\w.]/.test(name) ? "?" : name;
925 if (type === "object") return shown;
926 if (type === "closure") return `${shown || "(anonymous)"}()`;
927 return `(${type}${shown ? ` ${shown}` : ""})`;
928 };
929 const edgeName = (edge: number) => {
930 const type = edgeTypes[edges[edge + edgeTypeAt]!];
931 const value = edges[edge + edgeNameAt]!;
932 if (type === "element" || type === "hidden") return `[${value}]`;
933 const name = strings[value] ?? "";
934 return IDENTIFIER.test(name) ? name : "<key>";
935 };
936 const pathTo = (node: number) => {
937 const steps: string[] = [];
938 for (let at = node; at !== 0 && steps.length < 40; at = parent[at]!) {
939 if (parent[at] === -1) return "(unreachable)";
940 const from = parent[at]!;
941 steps.push(
942 from === 0 || nodeType(from) === "synthetic"
943 ? edgeName(parentEdge[at]!)
944 : `${label(from)}.${edgeName(parentEdge[at]!)}`,
945 );
946 if (nodeType(from) === "synthetic") break;
947 }
948 const shown = steps.reverse();
949 return [...(shown.length > 6 ? ["…", ...shown.slice(-6)] : shown), label(node)].join(" → ");
950 };
951 const result = new Map<number, Retainer>();
952 for (let node = 0; node < count; node++) {
953 if (!seen[node] || retained[node]! < minBytes) continue;
954 result.set(nodes[node * nodeFields + idAt]!, {
955 retained: retained[node]!,
956 dominator: node === 0 ? undefined : nodes[dominator[node]! * nodeFields + idAt]!,
957 path:
958 retained[node]! < pathBytes
959 ? ""
960 : nodeType(node) === "synthetic"
961 ? label(node)
962 : pathTo(node),
963 });
964 }
965 return result;
967​
968/**
969 * The objects whose retained size grew from each snapshot to the next, at least `minBytes` in all.
970 * An object is left out when a reported object it dominates holds at least 80% of its growth: of
971 * a chain that grew by about the same amount, only the deepest is kept, the container holding the
972 * growth. Nested objects whose growth differs are each reported.
973 */
974export function retainerGrowth(
975 snapshots: ReadonlyArray<ReadonlyMap<number, Retainer>>,
976 minBytes = 1_000_000,
977) {
978 const last = snapshots.at(-1);
979 if (last === undefined || snapshots.length < 2) return [];
980 const growth = new Map<number, number>();
981 for (const [id, { retained, path }] of last) {
982 if (path === "" || path.startsWith("(synthetic")) continue;
983 const sizes = [
984 ...snapshots.slice(0, -1).map((snapshot) => snapshot.get(id)?.retained ?? 0),
985 retained,
986 ];
987 const grewEachTime = sizes.every((size, index) => index === 0 || size > sizes[index - 1]!);
988 const grown = retained - sizes[0]!;
989 if (grewEachTime && grown >= minBytes) growth.set(id, grown);
990 }
991 const ancestors = (id: number) => {
992 const found: number[] = [];
993 for (let at = last.get(id)?.dominator; at !== undefined && found.length < 500;) {
994 found.push(at);
995 at = last.get(at)?.dominator;
996 }
997 return found;
998 };
999 // Deepest first, so every descendant is decided before its ancestors: a row is left out
1000 // only when a reported descendant holds at least 80% of its growth.
1001 const heldBelow = new Map<number, number>();
1002 const kept: Array<[number, number]> = [];
1003 const depth = new Map([...growth.keys()].map((id) => [id, ancestors(id).length]));
1004 const order = [...growth].toSorted((a, b) => depth.get(b[0])! - depth.get(a[0])!);
1005 for (const [id, grown] of order) {
1006 if ((heldBelow.get(id) ?? 0) >= grown * 0.8) continue;
1007 kept.push([id, grown]);
1008 for (const ancestor of ancestors(id)) {
1009 heldBelow.set(ancestor, Math.max(heldBelow.get(ancestor) ?? 0, grown));
1012 const rows: RetainerGrowth[] = kept
1013 .toSorted((a, b) => b[1] - a[1])
1014 .slice(0, 10)
1015 .map(([id, grown]) => ({
1016 path: last.get(id)!.path,
1017 MB: round(grown / 1e6, 2),
1018 retainedMB: round(last.get(id)!.retained / 1e6, 2),
1019 }));
1020 return rows;
1022​
1023const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.String));
1024const spellings: ReadonlyArray<(path: string) => string> = [
1025 (path) => path,
1026 // Inside a JSON string, with every escape JSON applies: backslashes, quotes, control characters.
1027 (path) => encodeJsonString(path).slice(1, -1),
1028 (path) => path.replaceAll("\\", "/"),
1030​
1031/** How a path can appear in a database's text: as written, JSON-escaped, with forward slashes. */
1032export function pathSpellings(path: string) {
1033 return [...new Set(spellings.map((spell) => spell(path)))];
1035​
1036/** Each spelling of `from` with the same spelling of `to`, for a textual rewrite. */
1037export function pathRewrites(from: string, to: string) {
1038 const pairs = new Map(spellings.map((spell) => [spell(from), spell(to)] as const));
1039 return [...pairs];
1041​
1042/**
1043 * When the next activity report goes out, `intervalMs` after the previous send, and whether it
1044 * starts too late to renew the lease that send took: past `latestMs`, a renewal can land after it
1045 * lapsed.
1046 */
1047export function nextActivityReport(
1048 lastSentAt: number,
1049 now: number,
1050 intervalMs = 25_000,
1051 latestMs = 40_000,
1052) {
1053 const due = lastSentAt + intervalMs;
1054 return { waitMs: Math.max(0, due - now), late: Math.max(due, now) - lastSentAt > latestMs };
1056​
1057/**
1058 * Whether a renewal let the previous send's lease lapse: it went out past `latestMs` after that
1059 * send (a stalled loop wakes late), or its answer came after the lease (`leaseMs`) ran out.
1060 */
1061export function activityRenewalMissed(
1062 previousSentAt: number,
1063 sentAt: number,
1064 repliedAt: number,
1065 latestMs = 40_000,
1066 leaseMs = 45_000,
1067) {
1068 return sentAt - previousSentAt > latestMs || repliedAt - previousSentAt > leaseMs;