Skip to content

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

Health report: event-loop stalls, counts since boot, engine-start failures by why (#7545)

Milind Soni026f5ca5cd80
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index bc5f4cbb4d..4a2b18acf9 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1781,7 +1781,7 @@ wait for the next read, `truncated: true`):
"cursor": "1790000000000.12", "truncated": false,
"incidents": [{ "kind": "turn", "code": "rpc_error", "engine": "codex", "count": 3, "firstAt": 1790000100000, "lastAt": 1790000290000,
"botId": "<uuid>", "threadId": "<uuid>", "seq": 12 }],
- "turns": { "started15m": 6, "failed15m": 3, "started24h": 40, "failed24h": 5 },
+ "turns": { "started15m": 6, "failed15m": 3, "started24h": 40, "failed24h": 5, "boot": 52 },
"routines": [{ "routineId": "<uuid>", "status": "failed", "at": 1790000200000, "consecutiveFailures": 2 }],
"schedule": { "v": 1, "seq": 4182, "unreadable": false, "nextDueAt": 1790086400000, "oldestUnconfirmed": null,
"lastConfirmed": { "dueAt": 1790000000000, "startedAt": 1790000001250, "state": "ran" },
@@ -1795,9 +1795,10 @@ wait for the next read, `truncated: true`):
"firstHour": { "startedAt": 1790000000000, "apps": ["gmail"], "look": "delivered",
"ms": { "seen": 41000, "firstMessage": 52000, "offered": 61000, "firstApp": 118000, "firstLook": 171000, "briefOn": 172000, "phoneOffered": 172000 } },
"value": { "sorted": 40, "drafted": 6, "prepped": 4, "routines": 0, "minutes": 110 },
- "room": { "waits": 3, "waitMs": 360000, "stopped": 1, "killed": 1, "stallMinutes": 2 },
+ "room": { "waits": 3, "waitMs": 360000, "stopped": 1, "killed": 1, "stallMinutes": 2,
+ "boot": { "waits": 5, "stopped": 1, "killed": 1, "stallMinutes": 4 } },
"speed": { "windowS": 300, "steal": 1.2, "psi": { "cpu": 3.4, "memory": 0, "io": 0.8 }, "bootMs": 5400, "wakeMs": null,
- "turnStarts": [12, 3, 1, 0, 0, 0] }
+ "turnStarts": [12, 3, 1, 0, 0, 0], "loop": { "n": 2, "worstMs": 1800 } }
}
```
@@ -1819,8 +1820,13 @@ Fly's own start before that, and a resume from a suspend, are not in it.
`turnStarts` counts people's messages since boot by how long each waited
from being stored to its engine's turn starting: up to 0.5, 1, 2, 5 and 15
seconds, and longer. A message sent while its thread runs a turn, a bot's, a
-routine's and a steer are not counted. Older homes don't send `speed`: the
-Admin reads that as unknown, never as zero.
+routine's and a steer are not counted. `loop` is the event loop's stalls
+(`server/perf/loop-stalls.ts`, read from the recorder's own minutes, nothing
+measured for it): `n`, delays of a second or more since this process started
+(finished minutes; it never falls), and `worstMs`, the longest delay in the
+last 15 minutes and the minute under way, so one read the Admin missed still
+shows; a sleep or pause is not a stall; `null` where no recorder runs. Older
+homes don't send `speed`: the Admin reads that as unknown, never as zero.
**`room`** is the last day's memory pressure where the home watches it (a Cloud
home on Linux, `server/engine-memory.ts`), else `null`: how many tasks had to
@@ -1828,7 +1834,9 @@ wait for memory and how long they waited in all (a wait still going counts its
time so far), how many turns were stopped for memory (`stopped`), how many
processes the kernel stopped (`killed`), and in how many minutes the machine
stalled on memory. Counted in memory since boot, so a restart starts them
-again.
+again. `boot` is the same counts (no wait time) since this process started:
+they never fall, so the Admin keeps each hour's increase (its Cloud history),
+which the rolling day can't give.
**`firstHour`** is there on a personal Cloud that began with its first hour
(`server/host/first-hour.ts`), else `null`: `startedAt` is the first boot,
@@ -1854,14 +1862,23 @@ thread ids, and a sequence number the cursor follows; at most 200 buckets,
the one quiet longest dropped first. The code is the first that applies: the
place's state (`shared/place-view.ts`); a cause the server words itself
(`stalled`, `restart`, `could_not_start`, `incident_undelivered`,
-`approval_undelivered`, `event_log`); the trial credit's refusal
+`approval_undelivered`, `event_log`); an engine that did not start, by why,
+instead of the provider-looking code its words would get (`server_error`,
+`rpc_error`, `spawn_error`): `start_overloaded` (the Cloud too busy to start
+it: the plain line `chat.notice.cloudBusyStart` or `cloudOutOfCpu`, or no room
+for another process), `start_not_installed` (its CLI missing), `start_provider`
+(the engine's or its provider's own transient refusal of the start, noted by
+the ACP start for its thread, `server/engine-start-failures.ts`); a sign-in
+refused at the start keeps `auth`/`auth_required`, which the Admin's
+engine-auth alert reads; the trial credit's refusal
(`trial_used_up`, …); the turn's stop reason when it says more than "failed"
(`auth_required`, `shutdown_timeout`, `provider_safety`, `update_required`,
`spawn_error`, `quota`, `tool_error`: a tool call that failed or wasn't allowed); the cause's class (`server/drivers/retry.ts`:
`auth`, `quota`, `rate_limited`, …); the generic stop reason (`rpc_error`);
else `unknown`. A turn that ends in `shutdown_timeout`, `auth_required`,
`update_required`, `spawn_error` or `rpc_error` without a failed row of its own
-counts once too. `turns` counts turns started and failed rows per minute;
+counts once too. `turns` counts turns started and failed rows per minute,
+and `boot` the turns started since boot (it never falls);
`routines` gives, for each routine that is on and each outside trigger, its last
outcome and its failures in a row, counted from the saved run rows at every read,
so a restart does not start the count again. A row that only counts occurrences
diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.ts
index 553b09920b..469099a8f9 100644
--- a/server/cloud-health.test.ts
+++ b/server/cloud-health.test.ts
@@ -8,7 +8,9 @@ import { failedTurnTool } from "../shared/failed-turn.ts";
import type { PlaceRow } from "../shared/place-view.ts";
import { TRIAL_CREDIT_REFUSED } from "../shared/trial-credit.ts";
import { CLOUD_HEALTH_PATH, CLOUD_PAIRING_PATH, CLOUD_PAIRING_SKEW_S, cloudPairingSignature, cloudRequestSignature } from "./cloud-home.ts";
-import { CLOUD_HEALTH_MAX_BYTES, HEALTH_BUCKET_CAP, createCloudHealth, createCloudHealthLedger, type CloudHealthDeps } from "./cloud-health.ts";
+import { CLOUD_HEALTH_MAX_BYTES, HEALTH_BUCKET_CAP, START_CODES, createCloudHealth, createCloudHealthLedger, type CloudHealthDeps } from "./cloud-health.ts";
+import { createCloudSpeed } from "./cloud-speed.ts";
+import { noteStartFailure } from "./engine-start-failures.ts";
import { DATA_DIR, EVENTS_DIR } from "./config.ts";
import { memoryStallText, memoryStopText } from "./engine-memory.ts";
import type { RuntimeEvent } from "./contracts.ts";
@@ -100,7 +102,7 @@ describe("a Cloud home's speed in its health report", () => {
w.emit(w.bot.threadId, { type: "turn.started" });
const { speed } = w.health.report(undefined);
expect(speed).toMatchObject({ bootMs: null, wakeMs: null, turnStarts: [0, 1, 0, 0, 0, 0] });
- expect(Object.keys(speed).sort()).toEqual(["bootMs", "psi", "steal", "turnStarts", "wakeMs", "windowS"]);
+ expect(Object.keys(speed).sort()).toEqual(["bootMs", "loop", "psi", "steal", "turnStarts", "wakeMs", "windowS"]);
expect(JSON.stringify(speed)).not.toMatch(/Tallyspoon|inbox/);
expect(JSON.stringify(speed).length).toBeLessThan(200);
});
@@ -240,9 +242,69 @@ describe("the ledger", () => {
w.advance(20 * 60_000);
w.emit(w.bot.threadId, { type: "turn.started" });
w.fail("no activity for 20 minutes — the turn was stopped");
- expect(w.health.report(null).turns).toEqual({ started15m: 1, failed15m: 1, started24h: 5, failed24h: 2 });
+ expect(w.health.report(null).turns).toEqual({ started15m: 1, failed15m: 1, started24h: 5, failed24h: 2, boot: 5 });
w.advance(24 * 3600_000);
- expect(w.health.report(null).turns).toEqual({ started15m: 0, failed15m: 0, started24h: 0, failed24h: 0 });
+ // The rolling windows empty out; the count since boot never falls (the Admin keeps each hour's increase).
+ expect(w.health.report(null).turns).toEqual({ started15m: 0, failed15m: 0, started24h: 0, failed24h: 0, boot: 5 });
+ });
+
+ it("files an engine that did not start under why, not as the provider-looking code its words would get; a sign-in keeps its auth code", () => {
+ const w = world(), thread = (name: string) => w.store.createBot({ name }).threadId;
+ const opencode = "Internal error: Internal service failure (session/new, ServiceUnavailableError)";
+ // Too busy: the plain line busy-start.ts shows (its notice key), and the process limit's.
+ const busy = thread("busy"), cpu = thread("cpu"), processes = thread("processes"), missing = thread("missing"), provider = thread("provider"), signedOut = thread("signed-out"), other = thread("other");
+ for (const id of [busy, cpu, processes, missing, provider, signedOut, other]) w.emit(id, { type: "turn.started" }, "opencodeGo");
+ w.fail(opencode, { text: { key: "chat.notice.cloudBusyStart" } }, busy);
+ w.fail(opencode, { text: { key: "chat.notice.cloudOutOfCpu" } }, cpu);
+ w.fail("There is no room to start another program (EAGAIN)", { text: { key: "chat.notice.outOfProcesses", params: { code: "EAGAIN" } } }, processes);
+ w.fail("`opencode` isn't installed, or isn't on this app's PATH", { setup: true }, missing);
+ // The engine's or its provider's own refusal of session/new, noted by the start (busy-start.ts) for this thread.
+ noteStartFailure(provider, "provider", w.now());
+ w.fail("500 internal server error", {}, provider);
+ w.fail("Authentication required: not logged in", { setup: true }, signedOut);
+ w.fail("500 internal server error", {}, other);
+ w.emit(signedOut, { type: "turn.completed", ok: false, stopReason: "auth_required" }, "opencodeGo");
+ w.emit(other, { type: "turn.completed", ok: false, stopReason: "rpc_error" }, "opencodeGo");
+ expect(incidents(w).map(({ code, count }) => [code, count]).sort()).toEqual([["auth_required", 1], ["server_error", 1], ["start_not_installed", 1], ["start_overloaded", 3], ["start_provider", 1]]);
+ // A note is the next row's only: a later failure on the thread is filed by its words again.
+ w.emit(provider, { type: "turn.started" }, "opencodeGo");
+ w.fail("500 internal server error", {}, provider);
+ w.emit(provider, { type: "turn.completed", ok: false, stopReason: "rpc_error" }, "opencodeGo");
+ expect(incidents(w).find((incident) => incident.code === "server_error")).toMatchObject({ count: 2 });
+ // A start that failed without a row of its own (its turn just ended) leaves nothing for the thread's next turn.
+ noteStartFailure(provider, "provider", w.now());
+ w.emit(provider, { type: "turn.completed", ok: false, stopReason: "rpc_error" }, "opencodeGo");
+ w.emit(provider, { type: "turn.started" }, "opencodeGo");
+ w.fail("500 internal server error", {}, provider);
+ w.emit(provider, { type: "turn.completed", ok: false, stopReason: "rpc_error" }, "opencodeGo");
+ expect(incidents(w).find((incident) => incident.code === "server_error")).toMatchObject({ count: 3 });
+ // Too busy, noted by the start, though the row came without the plain line (startup recovery words it as the engine did).
+ const recovered = thread("recovered");
+ w.emit(recovered, { type: "turn.started" }, "opencodeGo");
+ noteStartFailure(recovered, "overloaded", w.now());
+ w.fail(opencode, {}, recovered);
+ expect(incidents(w).find((incident) => incident.code === "start_overloaded")).toMatchObject({ count: 4 });
+ // A provider refusal noted, then the backup AI's start on the same thread refused for sign-in: the row stays an auth failure.
+ const backup = thread("backup");
+ w.emit(backup, { type: "turn.started" }, "opencodeGo");
+ noteStartFailure(backup, "provider", w.now());
+ w.fail("Authentication required: not logged in", { setup: true }, backup);
+ w.emit(backup, { type: "turn.completed", ok: false, stopReason: "auth_required" }, "opencodeGo");
+ expect(incidents(w).find((incident) => incident.code === "auth_required")).toMatchObject({ count: 2 });
+ expect(incidents(w).find((incident) => incident.code === "start_provider")).toMatchObject({ count: 1 });
+ expect(Object.values(START_CODES).every((code) => /^[a-z0-9][a-z0-9_-]{0,47}$/.test(code))).toBe(true);
+ });
+
+ it("carries the event loop's stalls and the counts since boot in a few dozen bytes, codes and counts only", () => {
+ const room = { waits: 3, waitMs: 360_000, stopped: 1, killed: 2, stallMinutes: 4 };
+ const plain = world({ room: () => room, speed: createCloudSpeed({ read: () => null, loop: () => null }) }).health.report(null);
+ const report = world({ room: () => ({ ...room, boot: { waits: 7, stopped: 2, killed: 2, stallMinutes: 9 } }),
+ speed: createCloudSpeed({ read: () => null, loop: () => ({ n: 12, worstMs: 11_234 }) }) }).health.report(null);
+ expect(report.speed.loop).toEqual({ n: 12, worstMs: 11_234 });
+ expect(report.room).toMatchObject({ boot: { waits: 7, stopped: 2, killed: 2, stallMinutes: 9 } });
+ expect(report.turns.boot).toBe(0);
+ const added = JSON.stringify(report).length - JSON.stringify(plain).length;
+ expect(added).toBeLessThanOrEqual(100);
});
it("reports each routine's last outcome and failures in a row as the saved run rows give them, so a restart hides none", () => {
diff --git a/server/cloud-health.ts b/server/cloud-health.ts
index 264eb3616b..72dd73844c 100644
--- a/server/cloud-health.ts
+++ b/server/cloud-health.ts
@@ -12,6 +12,7 @@ import type { FirstHourReport } from "./host/first-hour.ts";
import type { ValueReport } from "./host/value-ledger.ts";
import type { ProviderSnapshot, RuntimeEvent } from "./contracts.ts";
import { createCloudSpeed, type CloudSpeed } from "./cloud-speed.ts";
+import { takeStartFailure } from "./engine-start-failures.ts";
import { doctorSummary } from "./doctor/start.ts";
import { classifyError } from "./drivers/retry.ts";
import { storageHealth, type StorageReport } from "./perf/disk-usage.ts";
@@ -45,8 +46,18 @@ const STOP_CODES = new Set(["auth_required", "rpc_error", "shutdown_timeout", "p
const GENERIC_STOPS = new Set(["rpc_error", "error", "failed", "error_during_execution", "exit_before_result"]);
/** Engine stops that count as a failure even when no failed row was written for them. */
const ROWLESS_STOPS = new Set(["shutdown_timeout", "auth_required", "update_required", "spawn_error", "rpc_error"]);
+/**
+ * An engine that did not start, by why, instead of the provider-looking code its words would get (`server_error`, `rpc_error`,
+ * `spawn_error`): the Cloud too busy to start it (the plain line busy-start.ts or procs.ts shows), its CLI missing, or the
+ * engine's or its provider's own refusal of the start (engine-start-failures.ts). A sign-in keeps `auth`/`auth_required`,
+ * which the Admin's engine-auth alert reads.
+ */
+export const START_CODES = { overloaded: "start_overloaded", notInstalled: "start_not_installed", provider: "start_provider" } as const;
+const START_NOTICES: ReadonlyMap<string, string> = new Map([["chat.notice.cloudOutOfCpu", START_CODES.overloaded], ["chat.notice.cloudBusyStart", START_CODES.overloaded],
+ ["chat.notice.outOfProcesses", START_CODES.overloaded]]);
/** Causes the server writes itself, by fixed code. */
const FIXED_CAUSES: ReadonlyArray<[RegExp, string]> = [
+ [/^`[^`\n]{1,200}` isn't installed, or isn't on this app's PATH$/, START_CODES.notInstalled],
[/ran out of memory while \d+ tasks? ran at once/, "out_of_memory"],
[/^Ran out of room, so I (closed the browser|stopped this task) to keep everything else running\./, "out_of_memory"],
[/^no activity for \d+ minutes — the turn was stopped$/, "stalled"],
@@ -64,7 +75,7 @@ export interface HealthIncident {
count: number; firstAt: number; lastAt: number; botId: string | null; threadId: string | null; seq: number;
}
export type { RoutineHealth };
-export interface TurnRates { started15m: number; failed15m: number; started24h: number; failed24h: number }
+export interface TurnRates { started15m: number; failed15m: number; started24h: number; failed24h: number; boot: number }
interface Pending { at: number; botId: string | null; engine: string | null; fallback: string }
/** A cause the server words itself, or the trial credit's refusal: its code needs no stop reason. */
@@ -102,8 +113,11 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>
const lastRowAt = new Map<string, number>();
const engines = new Map<string, string>();
const minutes = new Map<number, { started: number; failed: number }>();
+ /** Turns started since boot: never falls, so the Admin keeps each hour's increase. */
+ let startedSinceBoot = 0;
const tally = (at: number, field: "started" | "failed") => {
+ if (field === "started") startedSinceBoot += 1;
const minute = Math.floor(at / MINUTE);
const slot = minutes.get(minute) ?? { started: 0, failed: 0 };
slot[field] += 1;
@@ -143,7 +157,7 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>
return {
bootedAt,
/** Every message the store appends; only failed-turn rows count. */
- noteMessage(threadId: string, message: Pick<Message, "at" | "tool" | "from">) {
+ noteMessage(threadId: string, message: Pick<Message, "at" | "from"> & { tool?: Pick<NonNullable<Message["tool"]>, "name" | "ok" | "place" | "nameCode"> }) {
const cause = message.tool?.ok === false ? failedTurnCause(message.tool.name) : null;
if (cause === null) return;
settle(threadId);
@@ -151,6 +165,11 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>
remember(lastRowAt, threadId, message.at, THREAD_CAP);
const place = message.tool?.place?.state;
if (place && PLACES.has(place)) return record("place", place, engine, message.at, botId, threadId);
+ const started = takeStartFailure(threadId, message.at), notice = message.tool?.nameCode ? START_NOTICES.get(message.tool.nameCode) : undefined;
+ if (notice) return record("turn", notice, engine, message.at, botId, threadId);
+ // A refused sign-in keeps its auth code whatever a start noted (the Admin's engine-auth alert reads it).
+ const signIn = message.tool?.nameCode === "chat.notice.engineSignedOut" || classifiedCode(cause) === "auth";
+ if (started && !signIn) return record("turn", started === "overloaded" ? START_CODES.overloaded : START_CODES.provider, engine, message.at, botId, threadId);
const fixed = fixedCode(cause);
if (fixed) return record("turn", fixed, engine, message.at, botId, threadId);
if (pending.size >= PENDING_CAP) settle(pending.keys().next().value as string);
@@ -163,6 +182,9 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>
if (kind) remember(engines, event.threadId, kind, THREAD_CAP);
tally(now(), "started");
} else if (event.type === "turn.completed") {
+ // A start failure belongs to its own turn's failed row (written before this, on its runtime error): a turn that ended
+ // without one leaves nothing for a later turn's row.
+ takeStartFailure(event.threadId);
if (pending.has(event.threadId)) return settle(event.threadId, event.stopReason);
if (event.ok || !event.stopReason || !ROWLESS_STOPS.has(event.stopReason)) return;
const at = now();
@@ -178,7 +200,7 @@ export function createCloudHealthLedger(options: { botOf?: (threadId: string) =>
const since = cursor && Number(cursor[1]) === bootedAt && Number(cursor[2]) <= seq ? Number(cursor[2]) : 0;
const incidents = [...buckets.values()].filter((bucket) => bucket.seq > since).sort((a, b) => a.seq - b.seq).map((bucket) => ({ ...bucket }));
const current = Math.floor(now() / MINUTE);
- const turns: TurnRates = { started15m: 0, failed15m: 0, started24h: 0, failed24h: 0 };
+ const turns: TurnRates = { started15m: 0, failed15m: 0, started24h: 0, failed24h: 0, boot: startedSinceBoot };
for (const [minute, slot] of minutes) {
if (minute <= current - WINDOW_24H) continue;
turns.started24h += slot.started; turns.failed24h += slot.failed;
diff --git a/server/cloud-speed.test.ts b/server/cloud-speed.test.ts
index c12b0ba8b3..94143a01bb 100644
--- a/server/cloud-speed.test.ts
+++ b/server/cloud-speed.test.ts
@@ -158,6 +158,9 @@ describe("turn starts", () => {
m.pass(1_500);
m.speed.noteEvent(started("a"));
expect(m.speed.report().turnStarts).toEqual(buckets({ 2: 1 }));
+ // The event loop's stalls come from its recorder (perf/loop-stalls.ts): none runs here.
+ expect(m.speed.report().loop).toBeNull();
+ expect(createCloudSpeed({ read: () => null, loop: () => ({ n: 2, worstMs: 1_500 }) }).report().loop).toEqual({ n: 2, worstMs: 1_500 });
});
it("drops a message whose turn never started", () => {
diff --git a/server/cloud-speed.ts b/server/cloud-speed.ts
index 3bd8bded1c..30307a0fd1 100644
--- a/server/cloud-speed.ts
+++ b/server/cloud-speed.ts
@@ -4,6 +4,7 @@
import { readFileSync } from "node:fs";
import { uptime } from "node:os";
import type { RuntimeEvent } from "./contracts.ts";
+import { loopStallCounts, type LoopStallCounts } from "./perf/loop-stalls.ts";
import type { Message } from "./store.ts";
/** Upper bounds of the turn-start buckets (ms); one more bucket counts everything slower. The Admin reads the same edges. */
@@ -39,6 +40,9 @@ export interface SpeedReport {
/** People's messages since this boot by how long they waited from being stored to their engine's turn starting, in
* TURN_START_BUCKETS_MS order. */
turnStarts: number[];
+ /** Event-loop stalls of a second or more since this process started, and the worst delay of the last 15 minutes, ms
+ * (perf/loop-stalls.ts); null where no recorder runs. Read from the recorder's own minutes: nothing is measured here. */
+ loop: LoopStallCounts | null;
}
/** `/proc/stat`'s first line: all CPU time and the stolen part, in USER_HZ ticks. Guest time is inside user time already. */
@@ -81,6 +85,8 @@ export function createCloudSpeed(options: {
/** Seconds since the kernel booted, and since this process started. */
machineUptime?: () => number;
processUptime?: () => number;
+ /** The event loop's stalls (perf/loop-stalls.ts `loopStallCounts`). */
+ loop?: () => LoopStallCounts | null;
} = {}) {
const read = options.read ?? readText, now = options.now ?? Date.now, monotonic = options.monotonic ?? (() => performance.now());
const machineUptime = options.machineUptime ?? uptime, processUptime = options.processUptime ?? (() => process.uptime());
@@ -148,7 +154,7 @@ export function createCloudSpeed(options: {
turnStarts[bucket === -1 ? TURN_START_BUCKETS_MS.length : bucket]! += 1;
},
report(): SpeedReport {
- return { ...cpuFigures(), bootMs, wakeMs, turnStarts: [...turnStarts] };
+ return { ...cpuFigures(), bootMs, wakeMs, turnStarts: [...turnStarts], loop: (options.loop ?? loopStallCounts)() };
},
};
}
diff --git a/server/drivers/acp/busy-start.test.ts b/server/drivers/acp/busy-start.test.ts
index 5a8deab8ac..dade56f3e8 100644
--- a/server/drivers/acp/busy-start.test.ts
+++ b/server/drivers/acp/busy-start.test.ts
@@ -4,7 +4,8 @@ import { classifyError } from "../retry.ts";
import { runtimeErrorText } from "../runtime-notice-error.ts";
import { startupFailureRecoverable } from "./startup-recovery.ts";
import { acpRpcError } from "./rpc-error.ts";
-import { BUSY_RETRY_PAUSE_MS, busyStartFailure, sessionNewRetried, SLOW_FIRST_ANSWER_MS, type BusyStartDeps } from "./busy-start.ts";
+import { BUSY_RETRY_PAUSE_MS, busyStartFailure, sessionNewRetried, SLOW_FIRST_ANSWER_MS, startFailureClass, type BusyStartDeps } from "./busy-start.ts";
+import { takeStartFailure } from "../../engine-start-failures.ts";
import { acpRuntimeFailure } from "./failure-words.ts";
import { classifyOpenCodeError } from "./opencode-go.ts";
@@ -97,3 +98,25 @@ describe("session/new on a busy Cloud", () => {
}
});
});
+
+describe("why a start failed, for the health report", () => {
+ it("notes the thread's start failure as too busy or the engine's own refusal; a sign-in or a request problem is not noted", async () => {
+ const pressed = deps({ pressure: () => "cpu pressure 80%" });
+ await sessionNewRetried(() => Promise.reject(refusal()), () => true, pressed.deps, "busy-thread").catch(() => {});
+ expect(takeStartFailure("busy-thread", 0)).toBe("overloaded");
+ // Taken once: a later failed row on the thread is filed by its words.
+ expect(takeStartFailure("busy-thread", 0)).toBeNull();
+ await sessionNewRetried(() => Promise.reject(outage()), () => true, deps().deps, "outage-thread").catch(() => {});
+ expect(takeStartFailure("outage-thread", 0)).toBe("provider");
+ const signIn = Object.assign(new Error("Authentication required"), { acpSignInRequired: true });
+ expect(startFailureClass(signIn)).toBeNull();
+ expect(startFailureClass(new Error("400 invalid request"))).toBeNull();
+ // A later start on the thread refused for sign-in takes the earlier note back: its row keeps its auth code.
+ await sessionNewRetried(() => Promise.reject(outage()), () => true, deps().deps, "backup-thread").catch(() => {});
+ await sessionNewRetried(() => Promise.reject(signIn), () => true, deps().deps, "backup-thread").catch(() => {});
+ expect(takeStartFailure("backup-thread", 0)).toBeNull();
+ // Without a thread nothing is noted (and nothing else changes).
+ await sessionNewRetried(() => Promise.reject(outage()), () => true, deps().deps).catch(() => {});
+ expect(takeStartFailure("outage-thread", 0)).toBeNull();
+ });
+});
diff --git a/server/drivers/acp/busy-start.ts b/server/drivers/acp/busy-start.ts
index 794f223446..4a6707d64f 100644
--- a/server/drivers/acp/busy-start.ts
+++ b/server/drivers/acp/busy-start.ts
@@ -7,10 +7,11 @@
// before: a provider outage (a 429, "503 overloaded") keeps its own words, and a backup AI still starts where one may.
// Our own limits stay as they are (session/new may take NEW_SESSION_TIMEOUT); a timeout is never asked again, which would
// double the wait.
+import { clearStartFailure, noteStartFailure } from "../../engine-start-failures.ts";
import { engineMemory } from "../../engine-memory.ts";
import { machinePressure } from "../../machine-pressure.ts";
import { classifyError } from "../retry.ts";
-import { RuntimeNoticeError } from "../runtime-notice-error.ts";
+import { RuntimeNoticeError, runtimeErrorText } from "../runtime-notice-error.ts";
/** Before asking again while the machine is pressed: room for what holds it to ease. */
export const BUSY_RETRY_PAUSE_MS = 10_000;
@@ -58,23 +59,42 @@ export function busyStartFailure(error: unknown, why: string | null, slow: boole
});
}
-/** session/new, asked once more after a transient refusal while its process lives. */
-export async function sessionNewRetried<T>(send: () => Promise<T>, alive: () => boolean, deps: BusyStartDeps = defaults): Promise<T> {
+/** Why this start failed, for the health report's code (engine-start-failures.ts): the machine too busy (the plain line
+ * above), or the engine's or its provider's own transient refusal (a 5xx, an overload, a timeout); a sign-in or anything
+ * else keeps its code as before. */
+export function startFailureClass(error: unknown): "overloaded" | "provider" | null {
+ const key = runtimeErrorText(error)?.key;
+ if (key === "chat.notice.cloudOutOfCpu" || key === "chat.notice.cloudBusyStart") return "overloaded";
+ if (!(error instanceof Error) || (error as { acpSignInRequired?: unknown }).acpSignInRequired === true) return null;
+ return classifyError({ text: error.message }).transient ? "provider" : null;
+}
+
+/** session/new, asked once more after a transient refusal while its process lives. `threadId`: the turn's thread, whose
+ * failed row the health report codes by why the start failed (`startFailureClass`); one map write on a failed start only. */
+export async function sessionNewRetried<T>(send: () => Promise<T>, alive: () => boolean, deps: BusyStartDeps = defaults, threadId?: string): Promise<T> {
const atStart = deps.pressure(), startedAt = deps.now();
/** The pressure read at the start, else now: a Cloud pressed at any point of the start. */
const during = () => atStart ?? deps.pressure();
+ const failed = (error: unknown) => {
+ if (threadId === undefined) return error;
+ // A start that failed for another reason (a sign-in, a request problem) takes back an earlier start's note on the thread
+ // (the backup AI's start after a provider refusal): its row keeps its own code.
+ const why = startFailureClass(error);
+ if (why) noteStartFailure(threadId, why, deps.now()); else clearStartFailure(threadId);
+ return error;
+ };
try {
return await send();
} catch (first) {
const slow = deps.now() - startedAt >= SLOW_FIRST_ANSWER_MS;
- if (!askAgain(first) || !alive()) throw busyStartFailure(first, during(), slow, deps);
+ if (!askAgain(first) || !alive()) throw failed(busyStartFailure(first, during(), slow, deps));
const afterFirst = during();
if (afterFirst !== null) await deps.pause(BUSY_RETRY_PAUSE_MS);
- if (!alive()) throw busyStartFailure(first, afterFirst ?? deps.pressure(), slow, deps);
+ if (!alive()) throw failed(busyStartFailure(first, afterFirst ?? deps.pressure(), slow, deps));
try {
return await send();
} catch (second) {
- throw busyStartFailure(second, afterFirst ?? deps.pressure(), slow, deps);
+ throw failed(busyStartFailure(second, afterFirst ?? deps.pressure(), slow, deps));
}
}
}
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index 9fc44e07ba..cd8c043693 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -1183,7 +1183,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
session.sessionId = typeof result?.sessionId === "string" ? result.sessionId : null;
session.sessionKey = liveSessionKey(sessionKey, heldSystem());
receiveModelVariants(result, true);
- }), () => session.child.exitCode === null && !session.closing && !session.dead); // a busy machine: once more, then plain words
+ }), () => session.child.exitCode === null && !session.closing && !session.dead, undefined, threadId); // a busy machine: once more, then plain words
break;
}
const sessionId = session.sessionId;
diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.ts
index c4677d99a0..efe86bd09a 100644
--- a/server/engine-memory.test.ts
+++ b/server/engine-memory.test.ts
@@ -1115,6 +1115,16 @@ describe("the day's memory pressure, for the Admin", () => {
expect(ledger.read(start + 60_000, [start])).toEqual({ waits: 2, waitMs: 150_000, stopped: 1, killed: 3, stallMinutes: 1 });
expect(ledger.read(start + 24 * 60 * 60_000 + 60_000)).toEqual({ waits: 0, waitMs: 0, stopped: 0, killed: 0, stallMinutes: 0 });
});
+
+ it("counts since start beside the rolling day: a stalled minute once, and never falling as the day forgets", () => {
+ const ledger = new PressureLedger(), start = 1_800_000_000_000;
+ ledger.note(start, "waits"); ledger.note(start, "waitMs", 90_000); ledger.note(start, "killed", 3); ledger.note(start, "stopped");
+ ledger.note(start, "stalled"); ledger.note(start + 20_000, "stalled"); ledger.note(start + 60_000, "stalled");
+ expect(ledger.boot()).toEqual({ waits: 1, stopped: 1, killed: 3, stallMinutes: 2 });
+ ledger.note(start + 25 * 60 * 60_000, "waits");
+ expect(ledger.read(start + 25 * 60 * 60_000)).toMatchObject({ waits: 1, stallMinutes: 0 });
+ expect(ledger.boot()).toEqual({ waits: 2, stopped: 1, killed: 3, stallMinutes: 2 });
+ });
});
describe("a lane of its own", () => {
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index cdc84f1aa2..0304ad4153 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -153,15 +153,21 @@ export const memoryStallText = (cause: string, count: number) => `${cause}. This
/** The last day's memory pressure on a Cloud home: tasks that had to wait for memory and how long they waited in all (a wait
* still going included), turns stopped for memory, processes the kernel stopped, and minutes the machine stalled on it. */
export interface RoomReport { waits: number; waitMs: number; stopped: number; killed: number; stallMinutes: number }
+/** The same counts since this process started (no wait time): the Admin keeps each hour's increase (its Cloud history), which
+ * the rolling day can't give. A restart starts them again; the Admin tells by the report's `bootedAt`. */
+export type BootPressure = Omit<RoomReport, "waitMs">;
type PressureKind = "waits" | "waitMs" | "stopped" | "killed" | "stalled";
-/** Counts by minute over the last day. */
+/** Counts by minute over the last day, and since start. */
export class PressureLedger {
private readonly minutes = new Map<number, Record<PressureKind, number>>();
+ private readonly sinceStart: BootPressure = { waits: 0, stopped: 0, killed: 0, stallMinutes: 0 };
note(at: number, kind: PressureKind, amount = 1): void {
const minute = Math.floor(at / MINUTE_MS);
const slot = this.minutes.get(minute) ?? { waits: 0, waitMs: 0, stopped: 0, killed: 0, stalled: 0 };
+ if (kind === "stalled") { if (!slot.stalled) this.sinceStart.stallMinutes += 1; }
+ else if (kind !== "waitMs") this.sinceStart[kind] += amount;
slot[kind] = kind === "stalled" ? 1 : slot[kind] + amount;
this.minutes.set(minute, slot);
for (const key of this.minutes.keys()) if (key <= minute - DAY_MINUTES) this.minutes.delete(key);
@@ -178,6 +184,9 @@ export class PressureLedger {
for (const start of waiting) report.waitMs += Math.max(0, at - start);
return report;
}
+
+ /** Counts since start: never fall, so the Admin can take each read's increase. */
+ boot(): BootPressure { return { ...this.sinceStart }; }
}
/** The bots' browsers, which start during a turn rather than with its engine. */
@@ -602,6 +611,8 @@ export class EngineMemory {
/** The last day's memory pressure, for the Admin's health check (cloud-health.ts): times only, never what ran. */
dayPressure(): RoomReport { return this.ledger.read(this.now(), this.waitingSince.values()); }
+ /** The last day's pressure and the counts since start (`boot`), as the health report carries them. */
+ roomReport(): RoomReport & { boot: BootPressure } { return { ...this.dayPressure(), boot: this.ledger.boot() }; }
/** Every couple of seconds while an engine or a bot's browser runs: notes short memory against the running turns, and
* makes room before the machine runs out: an idle engine first (and, thrashing, the unused browsers with it), then the
diff --git a/server/engine-start-failures.ts b/server/engine-start-failures.ts
new file mode 100644
index 0000000000..9b4948de49
--- /dev/null
+++ b/server/engine-start-failures.ts
@@ -0,0 +1,26 @@
+// Why an engine did not start, per thread, for the health report's failure code (cloud-health.ts): the start (ACP
+// session/new, drivers/acp/busy-start.ts) notes it as it throws, and the failed row that follows takes it. Written only on
+// a failed start and read only on a failed row: nothing on a turn that starts. Codes only, never the engine's words.
+export type StartFailureClass = "overloaded" | "provider";
+
+/** A note older than this belongs to no row: the failed row is written within seconds of the start failing. */
+export const START_FAILURE_KEEP_MS = 120_000;
+const CAP = 200;
+const noted = new Map<string, { at: number; why: StartFailureClass }>();
+
+export function noteStartFailure(threadId: string, why: StartFailureClass, at = Date.now()): void {
+ noted.delete(threadId);
+ noted.set(threadId, { at, why });
+ if (noted.size > CAP) noted.delete(noted.keys().next().value as string);
+}
+
+/** A start on this thread failed for a reason that keeps its own code (a sign-in): any earlier note goes. */
+export function clearStartFailure(threadId: string): void { noted.delete(threadId); }
+
+/** This thread's start failure noted within START_FAILURE_KEEP_MS of `at`, taken (a second row doesn't get it). */
+export function takeStartFailure(threadId: string, at = Date.now()): StartFailureClass | null {
+ const found = noted.get(threadId);
+ if (!found) return null;
+ noted.delete(threadId);
+ return Math.abs(at - found.at) <= START_FAILURE_KEEP_MS ? found.why : null;
+}
diff --git a/server/index.ts b/server/index.ts
index ebf51c02bb..de467aa139 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2783,7 +2783,7 @@ const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolea
const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, storage: () => withCacheCounters(perf.storage(), cacheSweeper), dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,
engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),
connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),
- browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });
+ browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.roomReport() } : {}) } });
const teamComputers = new TeamComputers(join(DATA_DIR, "team-computers.json"), ENVIRONMENT_ID);
let followupsReady = false;
const sendSequencer = new SendSequencer();
diff --git a/server/perf/loop-stalls.test.ts b/server/perf/loop-stalls.test.ts
index 824f6f90fc..78628ce13c 100644
--- a/server/perf/loop-stalls.test.ts
+++ b/server/perf/loop-stalls.test.ts
@@ -1,12 +1,12 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import type { IntervalHistogram } from "node:perf_hooks";
+import { createHistogram, type IntervalHistogram } from "node:perf_hooks";
import { setTimeout as delay } from "node:timers/promises";
import { describe, expect, it } from "vitest";
import { writeFileAtomic } from "../atomic.ts";
-import { createLoopStalls, markRequestArrival, requestArrivedBefore, STALL_RESOLUTION_MS, stallStats, timeBlocking } from "./loop-stalls.ts";
+import { countAtLeast, createLoopStalls, loopStallCounts, markRequestArrival, REPORTED_WORST_MINUTES, requestArrivedBefore, STALL_RESOLUTION_MS, stallStats, timeBlocking } from "./loop-stalls.ts";
import { PERF_HEALTH_MAX_BYTES, perfHealth, stallLines } from "./perf-report.ts";
const tally = { n: 0, ms: 0, maxMs: 0 };
@@ -110,6 +110,64 @@ describe("the loop stall recorder", () => {
expect(stalls.report().h1).toMatchObject({ max: hour });
});
+ it("counts stalls of a second or more since start for the health report, and the worst of the last 15 minutes; never a pause", () => {
+ // A histogram as Node fills it: 600 firings a minute at 100 ms, a stall being one late firing.
+ let count = 0, samples: Array<[number, number]> = [];
+ const histogram = {
+ get count() { return count; },
+ get max() { return count ? (Math.max(...samples.map(([, ms]) => ms)) + STALL_RESOLUTION_MS) * 1e6 : 0; },
+ get percentiles() { return new Map(samples.map(([percentile, ms]) => [percentile, (ms + STALL_RESOLUTION_MS) * 1e6])); },
+ reset() { count = 0; samples = []; }, enable: () => true, disable: () => true,
+ } as unknown as IntervalHistogram;
+ let mono = 0, waited = 0;
+ const stalls = createLoopStalls({ histogram, monotonic: () => mono, idle: () => waited });
+ /** A minute whose loop worked most of the time, with these late firings among 600. */
+ const minute = (late: number[]) => {
+ count = 600;
+ const sorted = [...late].sort((a, b) => a - b);
+ samples = [[0, 0.1], [100 * (1 - late.length / 600), 0.1], ...sorted.map((ms, index) => [100 * (1 - (late.length - 1 - index) / 600), ms] as [number, number])];
+ mono += 60_000; waited += 5_000;
+ stalls.roll();
+ };
+ minute([5_000]); minute([]); minute([1_500, 2_500, 700]);
+ expect(stalls.counts()).toEqual({ n: 3, worstMs: 5_000 });
+ for (let quiet = 0; quiet < REPORTED_WORST_MINUTES; quiet++) minute([]);
+ // The worst ages out of its 15 minutes; the count since start stays (the Admin takes each read's increase).
+ expect(stalls.counts()).toEqual({ n: 3, worstMs: 0 });
+ // A computer that slept (the loop waited through the gap) is no stall.
+ count = 3; samples = [[0, 0.1], [99, 0.1], [100, 3_600_000]];
+ mono += 60_000 + 3_600_000; waited += 60_000 + 3_600_000 - 50;
+ stalls.roll();
+ expect(stalls.counts()).toEqual({ n: 3, worstMs: 0 });
+ // The started recorder answers the health report's read; none before start or after stop.
+ expect(loopStallCounts()).toBeNull();
+ stalls.start();
+ expect(loopStallCounts()).toEqual({ n: 3, worstMs: 0 });
+ stalls.stop();
+ expect(loopStallCounts()).toBeNull();
+ });
+
+ it("counts a real histogram's stalls exactly, not from its sparse percentile ranks, and lets the worst age by time through a long pause", () => {
+ const ms = (value: number) => Math.round((value + STALL_RESOLUTION_MS) * 1e6);
+ const real = createHistogram();
+ for (let i = 0; i < 495; i++) real.record(ms(0.2));
+ for (let i = 0; i < 5; i++) real.record(ms(1_500));
+ // Node's sparse ranks put the last short delay at 98.4375%, which read as eight stalls; the histogram itself says five.
+ expect(countAtLeast(real, ms(1_000))).toBe(5);
+ expect(countAtLeast(real, ms(2_000))).toBe(0);
+ const histogram = Object.assign(real, { enable: () => true, disable: () => true }) as unknown as IntervalHistogram;
+ let mono = 0, waited = 0;
+ const stalls = createLoopStalls({ histogram, monotonic: () => mono, idle: () => waited });
+ mono += 60_000; waited += 5_000;
+ stalls.roll();
+ expect(stalls.counts()).toEqual({ n: 5, worstMs: 1_500 });
+ // The process sleeps an hour: one roll, but the stall is an hour old and out of the last 15 minutes.
+ real.record(ms(0.2));
+ mono += 3_600_000; waited += 3_600_000;
+ stalls.roll();
+ expect(stalls.counts()).toEqual({ n: 5, worstMs: 0 });
+ });
+
it("starts a message's wait when its request arrived, only for that request and only if recent", async () => {
expect(requestArrivedBefore(Date.now())).toBeUndefined();
await (async () => {
diff --git a/server/perf/loop-stalls.ts b/server/perf/loop-stalls.ts
index ae55df5ae5..9d580b777b 100644
--- a/server/perf/loop-stalls.ts
+++ b/server/perf/loop-stalls.ts
@@ -123,6 +123,30 @@ export interface LoopStallsOptions {
let longestRecent: (() => number) | null = null;
export const recentLoopDelayMs = (): number | null => longestRecent?.() ?? null;
+/** A stall the health report counts: the loop could not answer for this long (one delay of 1 s or more). */
+export const REPORTED_STALL_MS = 1_000;
+/** The health report's worst stall looks back this far: three of the Admin's 5-minute reads, so one it missed still shows. */
+export const REPORTED_WORST_MINUTES = 15;
+/** For the Admin's health read (cloud-speed.ts `loop`): `n`, stalls of REPORTED_STALL_MS or more in the minutes finished since this
+ * process started (it never falls, so the Admin keeps each hour's increase); `worstMs`, the longest delay in the last
+ * REPORTED_WORST_MINUTES and the minute under way. A sleep or pause is not a stall. Null when no recorder runs. */
+export interface LoopStallCounts { n: number; worstMs: number }
+
+/** How many of a histogram's recorded intervals are `ns` or longer, exactly: the smallest rank whose value reaches `ns`, found by
+ * asking the histogram itself (about ten `percentile` calls). Its `percentiles` map holds sparse ranks only, which over-count. */
+export function countAtLeast(histogram: Pick<IntervalHistogram, "count" | "max" | "percentile">, ns: number): number {
+ const total = histogram.count;
+ if (!total || histogram.max < ns) return 0;
+ let low = 1, high = total;
+ while (low < high) {
+ const mid = (low + high) >> 1;
+ if (histogram.percentile((100 * (mid - 0.5)) / total) >= ns) high = mid; else low = mid + 1;
+ }
+ return total - low + 1;
+}
+let reportedCounts: (() => LoopStallCounts) | null = null;
+export const loopStallCounts = (): LoopStallCounts | null => reportedCounts?.() ?? null;
+
export function createLoopStalls(options: LoopStallsOptions = {}) {
const resolutionMs = options.resolutionMs ?? STALL_RESOLUTION_MS;
const histogram = options.histogram ?? monitorEventLoopDelay({ resolution: resolutionMs });
@@ -130,7 +154,9 @@ export function createLoopStalls(options: LoopStallsOptions = {}) {
const monotonic = options.monotonic ?? (() => performance.now());
const idle = options.idle ?? (options.monotonic ? () => null : loopIdleMs);
const minutes: Minute[] = [];
- let timer: ReturnType<typeof setInterval> | undefined;
+ /** When each kept minute ended (`monotonic`), so the reported worst stall ages by time, not by rolls: a sleep is one roll. */
+ const endedAt: number[] = [];
+ let timer: ReturnType<typeof setInterval> | undefined, stalls = 0;
let since = monotonic(), idleSince = idle(), lastSince = since, lastIdleSince = idleSince;
/** The minute under way's longest delay when the loop worked less than half of it over this minute and the one before:
* the delay is recorded on a timer of its own, so a stall the last minute worked through can land in this one. */
@@ -141,8 +167,12 @@ export function createLoopStalls(options: LoopStallsOptions = {}) {
};
const roll = () => {
const paused = pausedMs();
- minutes.push(minuteOf(histogram, current, resolutionMs, paused));
- if (minutes.length > MINUTES_KEPT) minutes.shift();
+ const finished = minuteOf(histogram, current, resolutionMs, paused);
+ if (paused === null && finished.count) stalls += typeof histogram.percentile === "function"
+ ? countAtLeast(histogram, (REPORTED_STALL_MS + resolutionMs) * 1e6) : Math.round(finished.count * (1 - shareAtOrUnder(finished, REPORTED_STALL_MS)));
+ minutes.push(finished);
+ endedAt.push(monotonic());
+ if (minutes.length > MINUTES_KEPT) { minutes.shift(); endedAt.shift(); }
histogram.reset();
current = { saves: zero(), runtimeReads: zero() };
[lastSince, lastIdleSince] = [since, idleSince];
@@ -151,6 +181,11 @@ export function createLoopStalls(options: LoopStallsOptions = {}) {
if (paused !== null) options.resumed?.(Math.round(paused));
};
const longest = () => Math.max(minutes.at(-1)?.maxMs ?? 0, histogram.count ? lateMs(histogram.max, resolutionMs) : 0);
+ const counts = (): LoopStallCounts => {
+ const from = monotonic() - REPORTED_WORST_MINUTES * minuteMs;
+ const recent = minutes.filter((_, index) => endedAt[index]! > from).map((minute) => minute.maxMs);
+ return { n: stalls, worstMs: Math.round(Math.max(0, ...recent, histogram.count && pausedMs() === null ? lateMs(histogram.max, resolutionMs) : 0)) };
+ };
return {
start() {
if (timer) return;
@@ -160,13 +195,17 @@ export function createLoopStalls(options: LoopStallsOptions = {}) {
timer = setInterval(roll, minuteMs);
timer.unref?.();
longestRecent = longest;
+ reportedCounts = counts;
},
stop() {
if (timer) clearInterval(timer);
timer = undefined;
histogram.disable();
if (longestRecent === longest) longestRecent = null;
+ if (reportedCounts === counts) reportedCounts = null;
},
+ /** What the health report carries (`loopStallCounts`). */
+ counts,
/** Rolls the minute now (tests). */
roll,
/** The last full minute (or the one under way, before the first ends) and the last hour including the minute under way. */