Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Server idle: event-loop stall timers fire every 100 ms and 500 ms, not every 20 ms (#6944)

Milind Sonib8f853437458
diff --git a/server/event-loop-stalls.test.ts b/server/event-loop-stalls.test.ts
index ab257886cc..bb146740a2 100644
--- a/server/event-loop-stalls.test.ts
+++ b/server/event-loop-stalls.test.ts
@@ -1,19 +1,117 @@
import { afterEach, describe, expect, it } from "vitest";
-import { createEventLoopStalls, type EventLoopStalls } from "./event-loop-stalls.ts";
+import { createEventLoopStalls, LOOP_TIMER_MS, SAMPLE_MS, STALL_MS, type EventLoopStalls } from "./event-loop-stalls.ts";
let watch: EventLoopStalls | null = null;
afterEach(() => { watch?.close(); watch = null; });
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
-describe("this process's event loop stalls", () => {
+/** Node's timers on one clock: each interval fires once it is due and is set again from when it ran; a stall moves the
+ * clock with nothing running, then the overdue timers run in the order asked (the sample's before the tick, or after). */
+function loop() {
+ let time = 1_000_000;
+ const timers: Array<{ ms: number; run: () => void; due: number; stopped: boolean; name: string }> = [];
+ const every = (ms: number, run: () => void) => {
+ const timer = { ms, run, due: time + ms, stopped: false, name: ms === LOOP_TIMER_MS ? "tick" : "sample" };
+ timers.push(timer);
+ return () => { timer.stopped = true; };
+ };
+ const fire = (timer: (typeof timers)[number]) => { timer.run(); timer.due = time + timer.ms; };
+ return {
+ every, clock: () => time, now: () => time,
+ /** Runs every timer due up to `until`, earliest first. */
+ runUntil(until: number) {
+ for (;;) {
+ const next = timers.filter((timer) => !timer.stopped && timer.due <= until).sort((a, b) => a.due - b.due)[0];
+ if (!next) break;
+ time = Math.max(time, next.due);
+ fire(next);
+ }
+ time = until;
+ },
+ /** The loop is held for `ms`; then the timers that came due run, the sample's first when `sampleFirst`. */
+ stall(ms: number, sampleFirst: boolean) {
+ const start = time;
+ time += ms;
+ const due = timers.filter((timer) => !timer.stopped && timer.due <= time)
+ .sort((a, b) => (a.name === b.name ? 0 : (a.name === "sample") === sampleFirst ? -1 : 1));
+ for (const timer of due) fire(timer);
+ return { start, end: time };
+ },
+ nextSampleDue: () => timers.find((timer) => timer.name === "sample")!.due,
+ get time() { return time; },
+ };
+}
+
+/** The production settings on a simulated clock: a stall `offset` ms after a sample. */
+function stallAfterSample(offset: number, length: number, sampleFirst: boolean) {
+ const sim = loop();
+ watch = createEventLoopStalls(sim.now, { clock: sim.clock, every: sim.every });
+ sim.runUntil(sim.time + 3 * SAMPLE_MS);
+ const lastSample = sim.nextSampleDue() - SAMPLE_MS;
+ sim.runUntil(lastSample + offset);
+ const { start, end } = sim.stall(length, sampleFirst);
+ sim.runUntil(end + 2 * SAMPLE_MS);
+ const seen = watch.stalledBetween(start, end);
+ watch.close();
+ watch = null;
+ return seen;
+}
+
+describe("this process's event loop stalls, at the production settings", () => {
+ it("sees a stall that starts just after a sample, whichever overdue timer runs first", () => {
+ for (const sampleFirst of [true, false]) {
+ for (const offset of [1, 10, 100, 250, 499, 500, 501]) {
+ expect(stallAfterSample(offset, STALL_MS, sampleFirst), `offset ${offset}, sample first ${sampleFirst}`).toBe(true);
+ expect(stallAfterSample(offset, 4_000, sampleFirst), `4 s at offset ${offset}, sample first ${sampleFirst}`).toBe(true);
+ }
+ }
+ });
+
+ it("sees a stall that straddles a sample, when the sample runs before the tick it held up and when after", () => {
+ for (const sampleFirst of [true, false]) {
+ for (const before of [1, 100, 1_000, 1_999]) {
+ expect(stallAfterSample(SAMPLE_MS - before, STALL_MS, sampleFirst), `${before} ms before the sample, sample first ${sampleFirst}`).toBe(true);
+ expect(stallAfterSample(SAMPLE_MS - before, 7_000, sampleFirst), `7 s from ${before} ms before, sample first ${sampleFirst}`).toBe(true);
+ }
+ }
+ });
+
+ it("sees a stall at any offset in the sample", () => {
+ for (let offset = 0; offset < SAMPLE_MS; offset += 37) {
+ for (const sampleFirst of [true, false]) expect(stallAfterSample(offset, STALL_MS, sampleFirst), `offset ${offset}`).toBe(true);
+ }
+ });
+
+ it("never takes a quiet loop, or a hold-up well under the stall, for a stall", () => {
+ for (let offset = 0; offset < SAMPLE_MS; offset += 251) {
+ for (const sampleFirst of [true, false]) expect(stallAfterSample(offset, STALL_MS - LOOP_TIMER_MS - 1, sampleFirst), `offset ${offset}`).toBe(false);
+ }
+ const sim = loop();
+ watch = createEventLoopStalls(sim.now, { clock: sim.clock, every: sim.every });
+ const from = sim.time;
+ sim.runUntil(from + 60 * SAMPLE_MS);
+ expect(watch.stalledBetween(from, sim.time)).toBe(false);
+ });
+
+ it("ticks a couple of times a second, well inside a stall and a sample", () => {
+ // Each tick wakes an idle server; a gap only reads as a stall past the threshold, so the tick must stay under it, and
+ // a sample must hold several ticks.
+ expect(LOOP_TIMER_MS).toBeGreaterThanOrEqual(250);
+ expect(STALL_MS / LOOP_TIMER_MS).toBeGreaterThanOrEqual(4);
+ expect(SAMPLE_MS / LOOP_TIMER_MS).toBeGreaterThanOrEqual(10);
+ });
+});
+
+describe("this process's event loop stalls, on real timers", () => {
it("are seen in the window they fall in, and not in one that ended before them", async () => {
- watch = createEventLoopStalls(Date.now, { sampleMs: 50, stallMs: 1_000 });
- await pause(200);
+ // The production ratios, scaled down: a sample holds ten ticks.
+ watch = createEventLoopStalls(Date.now, { tickMs: 100, sampleMs: 1_000, stallMs: 1_000 });
+ await pause(1_500);
const before = Date.now();
// Held for well over the threshold: a margin of more than a second.
for (const end = Date.now() + 2_500; Date.now() < end;) { /* the stall */ }
- await pause(200);
+ await pause(2_200);
expect(watch.stalledBetween(before, Date.now())).toBe(true);
expect(watch.stalledBetween(before - 10_000, before - 5_000)).toBe(false);
});
diff --git a/server/event-loop-stalls.ts b/server/event-loop-stalls.ts
index a30323c49a..d90f76089e 100644
--- a/server/event-loop-stalls.ts
+++ b/server/event-loop-stalls.ts
@@ -1,11 +1,16 @@
// When this process's event loop was held up. A probe timed out by a stalled loop says nothing about the computer it was
// sent to, so no cloud computer is set aside on probes taken while the loop stalled (server/boat-recovery.ts).
-import { monitorEventLoopDelay, performance } from "node:perf_hooks";
+import { performance } from "node:perf_hooks";
/** A delay this long, anywhere in a sample, counts as a stall. */
export const STALL_MS = 2_000;
-const SAMPLE_MS = 5_000;
+export const SAMPLE_MS = 5_000;
const KEEP_MS = 2 * 60 * 60_000;
+/** How often the loop's own clock ticks; each tick wakes an idle server, so it is far coarser than a stall. Every moment
+ * lies in exactly one gap between two looks at the clock (a tick, or a sample reading the gap still open), and nothing
+ * ever resets the clock, so a stall of D ms always reads as one gap of between D and D plus this: none is missed, and a
+ * hold-up of more than the stall less this (1.5 s) may count as one, which only keeps a computer from being set aside. */
+export const LOOP_TIMER_MS = 500;
export interface EventLoopStalls {
/** The loop stalled at some point between `from` and `to` (by `now`). */
@@ -13,27 +18,50 @@ export interface EventLoopStalls {
close(): void;
}
-export function createEventLoopStalls(now: () => number = Date.now, { sampleMs = SAMPLE_MS, stallMs = STALL_MS } = {}): EventLoopStalls {
- const histogram = monitorEventLoopDelay({ resolution: 20 });
- histogram.enable();
+export interface EventLoopStallsOptions {
+ sampleMs?: number;
+ stallMs?: number;
+ tickMs?: number;
+ /** Monotonic ms (tests). */
+ clock?: () => number;
+ /** Calls `run` every `ms` until the returned stop is called (tests); an unref'd setInterval otherwise. */
+ every?: (ms: number, run: () => void) => () => void;
+}
+
+const everyMs = (ms: number, run: () => void) => {
+ const timer = setInterval(run, ms);
+ timer.unref?.();
+ return () => clearInterval(timer);
+};
+
+export function createEventLoopStalls(now: () => number = Date.now, options: EventLoopStallsOptions = {}): EventLoopStalls {
+ const { sampleMs = SAMPLE_MS, stallMs = STALL_MS, tickMs = LOOP_TIMER_MS, clock = () => performance.now(), every = everyMs } = options;
/** The end of each sample whose longest delay was a stall, and that delay. */
const stalls: Array<{ at: number; delayMs: number }> = [];
- let last = performance.now();
- const timer = setInterval(() => {
- // The histogram's longest delay, or this timer's own lateness: the histogram was seen to miss a stall under the test
- // runner, and a late timer cannot.
- const tick = performance.now(), delayMs = Math.max(histogram.max / 1e6, tick - last - sampleMs);
- last = tick;
- histogram.reset();
+ /** The last look at the clock, never cleared, and the longest gap between two looks since the last sample. */
+ let lastLook = clock(), longest = 0;
+ const look = () => {
+ const at = clock();
+ longest = Math.max(longest, at - lastLook);
+ lastLook = at;
+ };
+ let lastSample = clock();
+ const stopTicks = every(tickMs, look);
+ const stopSamples = every(sampleMs, () => {
+ // The gap still open counts here (a sample can run before the tick a stall held up), and is closed by this look, so
+ // the tick that follows does not count it again. This timer's own lateness stands in for a stall the ticks could not see.
+ look();
+ const tick = clock(), delayMs = Math.max(longest, tick - lastSample - sampleMs);
+ lastSample = tick;
+ longest = 0;
const at = now();
if (delayMs >= stallMs) stalls.push({ at, delayMs });
while (stalls.length && at - stalls[0]!.at > KEEP_MS) stalls.shift();
- }, sampleMs);
- timer.unref?.();
+ });
return {
// A sample ending after `from` may hold a stall from up to one sample earlier; that is counted, to be safe.
stalledBetween: (from, to) => stalls.some((stall) => stall.at >= from && stall.at - stall.delayMs - sampleMs <= to),
- close: () => { clearInterval(timer); histogram.disable(); },
+ close: () => { stopTicks(); stopSamples(); },
};
}
diff --git a/server/perf/loop-stalls.test.ts b/server/perf/loop-stalls.test.ts
index 248b89b95d..824f6f90fc 100644
--- a/server/perf/loop-stalls.test.ts
+++ b/server/perf/loop-stalls.test.ts
@@ -32,13 +32,15 @@ describe("the loop stall recorder", () => {
const dir = mkdtempSync(join(tmpdir(), "loop-stalls-"));
stalls.start();
try {
- await delay(60);
+ // Several of the histogram's own firings on each side of the stall, so the stall is one sample among many.
+ await delay(5 * STALL_RESOLUTION_MS);
const before = stalls.report().saves.m1.n;
writeFileAtomic(join(dir, "a.json"), "{}");
timeBlocking("runtimeReads", () => { const until = Date.now() + 300; while (Date.now() < until) { /* the stall */ } });
- await delay(60);
+ await delay(5 * STALL_RESOLUTION_MS);
const report = stalls.report();
- expect(report.m1!.max).toBeGreaterThanOrEqual(250);
+ // A stall reads as its length less up to one firing interval, never less.
+ expect(report.m1!.max).toBeGreaterThanOrEqual(300 - STALL_RESOLUTION_MS);
expect(report.m1!.over100ms).toBeGreaterThanOrEqual(1);
// One stall does not set the median; the rest is timer slop, a few ms late on a busy runner (Windows ticks every 15.6 ms).
expect(report.m1!.p50).toBeLessThan(50);
@@ -57,12 +59,18 @@ describe("the loop stall recorder", () => {
}
});
+ it("fires its timer at most ten times a second, so an idle server is not woken fifty times a second", () => {
+ // At 20 ms the firings were most of an idle Cloud's CPU; a stall still reads within one interval of its length.
+ expect(STALL_RESOLUTION_MS).toBeGreaterThanOrEqual(100);
+ expect(STALL_RESOLUTION_MS).toBeLessThan(1_000);
+ });
+
it("counts a gap the loop only waited through as a sleep or a pause, and one it worked through as a stall", () => {
const delays: number[] = [];
const histogram = {
get count() { return delays.length; },
get max() { return delays.length ? (Math.max(...delays) + STALL_RESOLUTION_MS) * 1e6 : 0; },
- get percentiles() { return new Map(delays.length ? [[0, 20.1e6], [99, 20.1e6], [100, (Math.max(...delays) + STALL_RESOLUTION_MS) * 1e6]] : []); },
+ get percentiles() { return new Map(delays.length ? [[0, (STALL_RESOLUTION_MS + 0.1) * 1e6], [99, (STALL_RESOLUTION_MS + 0.1) * 1e6], [100, (Math.max(...delays) + STALL_RESOLUTION_MS) * 1e6]] : []); },
reset() { delays.length = 0; }, enable: () => true, disable: () => true,
} as unknown as IntervalHistogram;
let mono = 0, waited: number | null = 0;
diff --git a/server/perf/loop-stalls.ts b/server/perf/loop-stalls.ts
index aaab757f44..d565d8f749 100644
--- a/server/perf/loop-stalls.ts
+++ b/server/perf/loop-stalls.ts
@@ -98,7 +98,13 @@ export function stallStats(minutes: readonly Minute[]): StallStats | null {
const sum = (tallies: readonly Tally[]): Tally => tallies.reduce((all, tally) => ({ n: all.n + tally.n, ms: all.ms + tally.ms, maxMs: Math.max(all.maxMs, tally.maxMs) }), zero());
const rounded = (tally: Tally): Tally => ({ n: tally.n, ms: Math.round(tally.ms), maxMs: Math.round(tally.maxMs * 10) / 10 });
-export const STALL_RESOLUTION_MS = 20;
+/** How often the histogram's timer fires. Each firing wakes an idle server: at 20 ms that was most of an idle server's CPU
+ * (up to about 0.2% of a core on a Fly shared vCPU, 1% under gVisor), every hour of the day. A stall of D ms reads as
+ * between D minus this and D: the longest delay reads up to this much short, so a stall just over 1 s (or just over
+ * 100 ms) may land under that line in the counts, and a pause's gap reads up to this much short too. The histogram records
+ * nothing from a reset to its next firing, so a stall that starts in the first interval after the minute rolls can drop out
+ * of the figures. Diagnostics only: nothing acts on these. */
+export const STALL_RESOLUTION_MS = 100;
export const MINUTE_MS = 60_000;
const MINUTES_KEPT = 60;