Skip to content

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

Stall watch: record where the server's main thread is stuck, while it is stuck (#6858)

Milind Soni720198e5f0e7
diff --git a/scripts/bundle-server.mjs b/scripts/bundle-server.mjs
index a7e7c3a72d..6c8a6ec90a 100644
--- a/scripts/bundle-server.mjs
+++ b/scripts/bundle-server.mjs
@@ -37,6 +37,8 @@ const ENTRY_POINTS = [
"openmausbot.ts",
"pair-cli.ts",
"workspace-backup.worker.ts",
+ // the stall watch's thread (perf/stall-watch.ts)
+ "stall-watch.worker.ts",
// the OMB Cloud Pro home image's entry point
"cloud-home-start.ts",
// the container image's entry point
diff --git a/server/index.ts b/server/index.ts
index 62ae621196..1ff04380e0 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2764,7 +2764,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPers
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const refusedLending = createRefusedLending({ runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, lentDevice: () => { const lent = lentNow(); return lent ? deviceWord(lent.platform) : null; }, language: conversationLanguage }); const takeRefusedRun = (threadId: string) => refusedLending.ending(threadId, refusedHandoffs.take(threadId)); /** The computer the person lends My Cloud now, newest first: one source for the word every refusal names it by. */ function lentNow() { return sharedComputers.known(CLOUD_HOME_LENDER).find((one) => one.lent); } const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME), ...(DESKTOP_MANAGED ? { launches: { launchId: process.env.OMB_DESKTOP_LAUNCH_ID ?? null, server: launchServerPart, counts: () => ({ bots: store.bots.length, threads: store.bots.reduce((sum, bot) => sum + (bot.tasks?.length ?? 0), 0) }) } } : {}) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const refusedLending = createRefusedLending({ runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, lentDevice: () => { const lent = lentNow(); return lent ? deviceWord(lent.platform) : null; }, language: conversationLanguage }); const takeRefusedRun = (threadId: string) => refusedLending.ending(threadId, refusedHandoffs.take(threadId)); /** The computer the person lends My Cloud now, newest first: one source for the word every refusal names it by. */ function lentNow() { return sharedComputers.known(CLOUD_HOME_LENDER).find((one) => one.lent); } const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, watchStalls: !DESKTOP_MANAGED, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME), ...(DESKTOP_MANAGED ? { launches: { launchId: process.env.OMB_DESKTOP_LAUNCH_ID ?? null, server: launchServerPart, counts: () => ({ bots: store.bots.length, threads: store.bots.reduce((sum, bot) => sum + (bot.tasks?.length ?? 0), 0) }) } } : {}) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
index c61e3ae2d2..bfae3e85b6 100644
--- a/server/perf/perf-host.ts
+++ b/server/perf/perf-host.ts
@@ -15,6 +15,7 @@ import { createSetupClock, type SetupClock, type SetupMs } from "./setup-steps.t
import type { FailoverWhy } from "./turn-record.ts";
import { createTurnTimings, type Refusal, type SlowNote, type TurnTimings } from "./turn-timings.ts";
import { createLaunchTimings, LAUNCH_FILE, type LaunchTimings } from "./launch-timings.ts";
+import { startStallWatch, stallReportLines, type StallWatch } from "./stall-watch.ts";
export const PERF_FILE = "perf-timings.json";
/** One line per kind of slow event at most this often; the ones held back are counted on the next. */
@@ -46,6 +47,9 @@ export interface PerfHostDeps {
pruneOwners?: (rows: readonly ProcessRow[]) => void;
/** The memory one bot may use and how it is enforced (bot-memory-cap.ts). */
cap?: () => BotCapReport;
+ /** Watch for main-thread stalls (stall-watch.ts): on a Cloud home and a self-hosted server, not in the desktop app. Never
+ * without the sampler timer. */
+ watchStalls?: boolean;
/** The desktop app started this server: its launches are recorded (launch-timings.ts). */
launches?: Pick<NonNullable<Parameters<typeof createLaunchTimings>[0]>, "launchId" | "counts" | "server">;
}
@@ -113,6 +117,11 @@ export function createPerfHost(deps: PerfHostDeps) {
if (deps.timer !== false && !windows) sampler.start();
const stalls = deps.stalls ?? createLoopStalls({ resumed: (ms) => say("sleep", `the computer slept or the server was paused: the event loop waited through a ${duration(ms)} gap, not counted as a stall`) });
if (deps.timer !== false) stalls.start();
+ const watch: StallWatch | null = deps.timer !== false && deps.watchStalls === true
+ ? guarded("stall-watch", () => startStallWatch({ dataDir: deps.dataDir, ...(deps.log ? { log: deps.log } : {}) }), null) : null;
+ const caught = () => guarded("stall-watch", () => stallReportLines(watch?.recent() ?? []), []);
+ /** Stall records right under the heading: a @devs report keeps only the first lines of this part. */
+ const stallsFirst = (lines: string[]) => { const stalls = caught(); return lines[0]?.startsWith("## ") ? [lines[0], ...stalls, ...lines.slice(1)] : [...stalls, ...lines]; };
if (deps.timer !== false && linux) guarded("limits", () => (deps.log ?? ((line: string) => console.warn(line)))(processes.startLine()), undefined);
const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null), processes: processes.report(),
@@ -137,14 +146,14 @@ export function createPerfHost(deps: PerfHostDeps) {
health: (): PerfHealth | null => guarded("health", () => perfHealth(sources()), null),
/** For a @devs report: these conversations' and bots' latest turns, then everything else. */
lines(filter: { threadIds: readonly string[]; botIds: readonly string[] }): string[] {
- return guarded("lines", () => perfLines(sources(), timings.recent({ ...filter, limit: RECENT_IN_REPORT }), "Latest turns in this conversation or of its bots, newest last:"), PERF_UNAVAILABLE);
+ return stallsFirst(guarded("lines", () => perfLines(sources(), timings.recent({ ...filter, limit: RECENT_IN_REPORT }), "Latest turns in this conversation or of its bots, newest last:"), PERF_UNAVAILABLE));
},
/** For the desktop's diagnostics export: every bot's latest turns. */
text(): string {
- return guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE).join("\n");
+ return stallsFirst(guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE)).join("\n");
},
/** The graceful shutdown: no more samples, and the turns since the last save written now. */
- stop() { sampler.stop(); stalls.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },
+ stop() { sampler.stop(); stalls.stop(); watch?.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },
};
}
export type PerfHost = ReturnType<typeof createPerfHost>;
diff --git a/server/perf/stall-sample.test.ts b/server/perf/stall-sample.test.ts
new file mode 100644
index 0000000000..cc549e7a26
--- /dev/null
+++ b/server/perf/stall-sample.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from "vitest";
+
+import { availableMB, codeLocation, pressure10, stallLine, stealPercent, summarizeProfile, threadState, type CpuProfile, type StallRecord } from "./stall-sample.ts";
+
+const frame = (functionName: string, url = "", lineNumber = 0) => ({ functionName, url, lineNumber, columnNumber: 4 });
+
+describe("codeLocation", () => {
+ it("keeps the file's place in the app and drops the machine's paths", () => {
+ const root = "/home/ada/OpenMausBot";
+ expect(codeLocation(frame("redactSecretsInText", "file:///home/ada/OpenMausBot/shared/redact.ts", 92), root)).toBe("redactSecretsInText shared/redact.ts:93:5");
+ expect(codeLocation(frame("x", "file:///app/dist-server/index.js", 10), "/app")).toBe("x dist-server/index.js:11:5");
+ expect(codeLocation(frame("parse", "file:///Users/ada/app/node_modules/@scope/pkg/lib/a.js"), "/Users/ada/app")).toBe("parse @scope/pkg/lib/a.js:1:5");
+ expect(codeLocation(frame("readFileSync", "node:fs"), root)).toBe("readFileSync node:fs:1:5");
+ expect(codeLocation(frame("", "file:///secret/place/thing.js"), root)).toBe("(anonymous) thing.js:1:5");
+ expect(codeLocation(frame("(garbage collector)"))).toBe("(garbage collector)");
+ expect(codeLocation({ ...frame("inlined", "file:///app/dist-server/index.js"), lineNumber: -1 }, "/app")).toBe("inlined dist-server/index.js");
+ });
+
+ it("matches the app's own folder, not a `packages` or `server` folder above it", () => {
+ const root = "/srv/packages/server/OpenMausBot";
+ expect(codeLocation(frame("tick", `file://${root}/server/perf/x.ts`, 1), root)).toBe("tick server/perf/x.ts:2:5");
+ expect(codeLocation(frame("tick", "file:///srv/packages/other/y.ts", 1), root)).toBe("tick y.ts:2:5");
+ });
+
+ it("finds the app's own folder in a Windows path or file URL", () => {
+ const root = "C:\\a\\OpenMausBot";
+ expect(codeLocation(frame("tick", "file:///C:/a/OpenMausBot/server/perf/x.ts", 1), root)).toBe("tick server/perf/x.ts:2:5");
+ expect(codeLocation(frame("tick", "C:\\a\\OpenMausBot\\server\\perf\\x.ts", 1), root)).toBe("tick server/perf/x.ts:2:5");
+ expect(codeLocation(frame("tick", "file:///c:/a/OpenMausBot/server/perf/x.ts", 1), root)).toBe("tick server/perf/x.ts:2:5");
+ expect(codeLocation(frame("tick", "file:///D:/elsewhere/y.ts", 1), root)).toBe("tick y.ts:2:5");
+ });
+
+ it("never carries a function name that isn't an identifier", () => {
+ expect(codeLocation(frame("evil\nname with \"quotes\"", "file:///app/server/a.ts"), "/app")).toBe("(anonymous) server/a.ts:1:5");
+ });
+});
+
+describe("summarizeProfile", () => {
+ it("names the busiest frames and the stack to the busiest leaf", () => {
+ const profile: CpuProfile = {
+ nodes: [
+ { id: 1, callFrame: frame("(root)"), children: [2, 5] },
+ { id: 2, callFrame: frame("handle", "file:///app/server/index.ts", 9), children: [3] },
+ { id: 3, callFrame: frame("redact", "file:///app/shared/redact.ts", 99), children: [4] },
+ { id: 4, callFrame: frame("replace", "", 0) },
+ { id: 5, callFrame: frame("(idle)") },
+ ],
+ samples: [4, 4, 4, 3, 5, 5, 5, 5, 5],
+ };
+ const summary = summarizeProfile(profile, "/app");
+ expect(summary.top[0]).toEqual({ at: "(idle)", samples: 5 });
+ expect(summary.top[1]).toEqual({ at: "replace", samples: 3 });
+ expect(summary.stack).toEqual(["handle server/index.ts:10:5", "redact shared/redact.ts:100:5", "replace"]);
+ });
+
+ it("copes with an empty profile", () => {
+ expect(summarizeProfile({ nodes: [], samples: [] })).toEqual({ top: [], stack: [] });
+ });
+});
+
+describe("/proc readings", () => {
+ it("reads a thread's state and wait channel", () => {
+ expect(threadState("1234 (MainThread) D 1 1234 1234 0 -1", "folio_wait_bit_common")).toEqual({ state: "D", wchan: "folio_wait_bit_common" });
+ expect(threadState("1234 (node (x)) R 1", "0")).toEqual({ state: "R", wchan: null });
+ expect(threadState(null, null)).toEqual({ state: null, wchan: null });
+ });
+
+ it("reads memory, pressure and steal", () => {
+ expect(availableMB("MemTotal: 2000000 kB\nMemAvailable: 7168 kB\n")).toBe(7);
+ expect(pressure10("some avg10=12.50 avg60=1 avg300=0 total=1\nfull avg10=70.26 avg60=2 avg300=0 total=1\n", "full")).toBe(70.26);
+ expect(pressure10(null, "some")).toBeNull();
+ expect(stealPercent("cpu 100 0 100 700 0 0 0 100 0 0\n", "cpu 110 0 110 720 0 0 0 160 0 0\n")).toBe(60);
+ expect(stealPercent("cpu 1 2\n", null)).toBeNull();
+ });
+});
+
+describe("stallLine", () => {
+ const base: StallRecord = {
+ at: 0, blockedSinceMs: 12_400, kind: "js", top: [{ at: "redact shared/redact.ts:100:5", samples: 1800 }], stack: ["handle server/index.ts:10:5", "redact shared/redact.ts:100:5"],
+ thread: { state: "R", wchan: null }, machine: { availableMB: 2300, memoryFull10: 0, cpuSome10: 1, stealPct: 0 }, memory: [{ bucket: "server", rssMB: 520, procs: 1 }],
+ };
+
+ it("says where the thread is and what the machine looks like", () => {
+ expect(stallLine(base)).toBe("main thread blocked 12s, in JavaScript: redact shared/redact.ts:100:5 (1800); stack handle server/index.ts:10:5 > redact shared/redact.ts:100:5; "
+ + "memory available 2300 MB, memory stall 0%, cpu stall 1%, steal 0%; largest: server 520 MB");
+ });
+
+ it("says why there is no profile", () => {
+ const line = stallLine({ ...base, kind: "not-profiled", why: "memory", top: [], stack: [], thread: { state: "D", wchan: null } });
+ expect(line).toContain("main thread blocked 12s, not profiled, memory too short to profile (thread state D)");
+ expect(stallLine({ ...base, kind: "not-profiled", why: "no-inspector", top: [], stack: [] })).toContain("not profiled, no inspector here");
+ });
+
+ it("says when the thread was outside JavaScript", () => {
+ const line = stallLine({ ...base, kind: "outside-js", top: [], stack: [], thread: { state: "D", wchan: "folio_wait_bit_common" },
+ machine: { availableMB: 7, memoryFull10: 70.3, cpuSome10: null, stealPct: null }, memory: [{ bucket: "browser", rssMB: 2864, procs: 1 }] });
+ expect(line).toBe("main thread blocked 12s, outside JavaScript (thread state D, waiting in folio_wait_bit_common); memory available 7 MB, memory stall 70.3%, cpu stall ?, steal ?; largest: browser 2864 MB");
+ });
+});
diff --git a/server/perf/stall-sample.ts b/server/perf/stall-sample.ts
new file mode 100644
index 0000000000..f266b1fb7d
--- /dev/null
+++ b/server/perf/stall-sample.ts
@@ -0,0 +1,125 @@
+// What a stall record holds (stall-watch.ts), and the pure parts of taking one: code locations from a CPU profile of the
+// server's main thread, the main thread's state from /proc, the machine's memory and CPU pressure, and the memory each
+// kind of process holds. Numbers, kinds and code locations only: never a value, a path outside the app, a name or a word.
+import type { ProcessBucket } from "./process-buckets.ts";
+
+/** One frame of a V8 CPU profile node, as the inspector's Profiler domain gives it. */
+export interface ProfileFrame { functionName: string; url: string; lineNumber: number; columnNumber: number }
+export interface ProfileNode { id: number; callFrame: ProfileFrame; children?: number[] }
+export interface CpuProfile { nodes: ProfileNode[]; samples?: number[] }
+
+/** Where in the code the main thread was, and how many of the profile's samples were there. */
+export interface StallFrame { at: string; samples: number }
+
+export interface StallRecord {
+ /** When the record was taken, and since when the main thread had not run its heartbeat. */
+ at: number;
+ blockedSinceMs: number;
+ /** "js": the profile answered, and `top` and `stack` say where; "outside-js": it did not answer in time (a system call,
+ * a page fault, native code), and the thread's state and the machine's pressure are all there is; "not-profiled": no
+ * profile was tried (`why`). */
+ kind: "js" | "outside-js" | "not-profiled";
+ /** Why no profile: memory too short for one, the hour's profiles taken, no inspector in this Node, or still to come (the
+ * record saved before its profile). */
+ why?: "memory" | "hourly-cap" | "no-inspector" | "pending";
+ /** The frames with the most samples of their own, most first. */
+ top: StallFrame[];
+ /** The path from the outermost frame to the busiest leaf, outermost first. */
+ stack: string[];
+ /** The main thread's state letter (R running, D waiting on the disk or a page, S sleeping) and kernel wait channel. */
+ thread: { state: string | null; wchan: string | null };
+ /** MemAvailable and the memory stall (`full avg10`, percent), the CPU stall (`some avg10`) and steal over the last second. */
+ machine: { availableMB: number | null; memoryFull10: number | null; cpuSome10: number | null; stealPct: number | null };
+ /** Memory by kind of process, most first (perf/process-buckets.ts kinds). */
+ memory: Array<{ bucket: ProcessBucket; rssMB: number; procs: number }>;
+}
+
+const SAFE_NAME = /^[\w$.<>[\] -]{1,80}$/;
+
+/** A code location with nothing of the machine's paths: the file's place in the app (its path under `appRoot`, the
+ * app's own folder), a package's name and path, a Node built-in, or only its base name. */
+export function codeLocation(frame: ProfileFrame, appRoot = ""): string {
+ const pseudo = /^\([a-z ]{1,40}\)$/.test(frame.functionName);
+ const name = frame.functionName && (pseudo || SAFE_NAME.test(frame.functionName)) ? frame.functionName : "(anonymous)";
+ if (!frame.url) return name;
+ // `file:///C:/x` and `C:\x` alike: forward slashes, no slash before a drive letter, which compares in either case.
+ const normal = (text: string) => text.replace(/\\/g, "/").replace(/^\/([A-Za-z]:)/, "$1").replace(/^([A-Za-z]):/, (_m, drive: string) => `${drive.toUpperCase()}:`);
+ const raw = frame.url.replace(/^file:\/\//, "").split("?")[0]!;
+ let decoded = raw;
+ try { decoded = decodeURI(raw); } catch {}
+ const path = normal(decoded);
+ const root = normal(appRoot).replace(/\/?$/, "/");
+ const pkg = /node_modules\/((?:@[^/]+\/)?[^/]+\/.*)$/.exec(path)?.[1];
+ const app = !pkg && root !== "/" && path.startsWith(root) ? path.slice(root.length) : undefined;
+ const builtin = /^node:[\w/]+$/.test(path) ? path : null;
+ const file = (builtin ?? pkg ?? app ?? path.split("/").pop() ?? "?").replace(/[^\w@./:-]/g, "_").slice(0, 120);
+ return frame.lineNumber >= 0 ? `${name} ${file}:${frame.lineNumber + 1}:${frame.columnNumber + 1}` : `${name} ${file}`;
+}
+
+/** The busiest frames by own samples, and the stack to the busiest leaf. Idle and garbage-collection pseudo-frames count
+ * as themselves: a stall that is mostly `(garbage collector)` says so. */
+export function summarizeProfile(profile: CpuProfile, appRoot = "", topN = 8, depth = 24): { top: StallFrame[]; stack: string[] } {
+ const byId = new Map(profile.nodes.map((node) => [node.id, node]));
+ const parent = new Map<number, number>();
+ for (const node of profile.nodes) for (const child of node.children ?? []) parent.set(child, node.id);
+ const own = new Map<number, number>();
+ for (const id of profile.samples ?? []) own.set(id, (own.get(id) ?? 0) + 1);
+ const byLocation = new Map<string, number>();
+ for (const [id, count] of own) {
+ const node = byId.get(id);
+ if (!node) continue;
+ const at = codeLocation(node.callFrame, appRoot);
+ byLocation.set(at, (byLocation.get(at) ?? 0) + count);
+ }
+ const top = [...byLocation].sort((a, b) => b[1] - a[1]).slice(0, topN).map(([at, samples]) => ({ at, samples }));
+ const busiest = [...own].filter(([id]) => !/^\((idle|program|root)\)$/.test(byId.get(id)?.callFrame.functionName ?? "")).sort((a, b) => b[1] - a[1])[0]?.[0];
+ const stack: string[] = [];
+ for (let id: number | undefined = busiest; id !== undefined && stack.length < depth; id = parent.get(id)) {
+ const node = byId.get(id);
+ if (!node || node.callFrame.functionName === "(root)") break;
+ stack.push(codeLocation(node.callFrame, appRoot));
+ }
+ return { top, stack: stack.reverse() };
+}
+
+/** The state letter and wait channel of a thread from /proc/<pid>/task/<tid>/stat and .../wchan. */
+export function threadState(stat: string | null, wchan: string | null): { state: string | null; wchan: string | null } {
+ const state = stat ? /\)\s+([A-Za-z])\s/.exec(stat)?.[1] ?? null : null;
+ const channel = wchan && /^[\w.]{1,64}$/.test(wchan.trim()) && wchan.trim() !== "0" ? wchan.trim() : null;
+ return { state, wchan: channel };
+}
+
+/** MemAvailable from /proc/meminfo, MB. */
+export function availableMB(meminfo: string | null): number | null {
+ const found = meminfo ? /^MemAvailable:\s+(\d+) kB$/m.exec(meminfo) : null;
+ return found ? Math.round(Number(found[1]) / 1024) : null;
+}
+
+/** A pressure file's `some` or `full` avg10, percent. */
+export function pressure10(text: string | null, line: "some" | "full"): number | null {
+ const found = text ? new RegExp(`^${line} avg10=([\\d.]+)`, "m").exec(text) : null;
+ return found ? Number(found[1]) : null;
+}
+
+/** The share of all CPU time that was stolen between two reads of /proc/stat's first line, percent. */
+export function stealPercent(before: string | null, after: string | null): number | null {
+ const fields = (text: string | null) => text ? /^cpu\s+(.*)$/m.exec(text)?.[1]?.trim().split(/\s+/).map(Number) ?? null : null;
+ const a = fields(before), b = fields(after);
+ if (!a || !b || a.length < 8 || b.length < 8) return null;
+ const total = b.reduce((sum, value, index) => sum + value - (a[index] ?? 0), 0);
+ return total > 0 ? Math.round(((b[7]! - a[7]!) / total) * 1000) / 10 : null;
+}
+
+/** One line for the server log, and for a report. */
+export function stallLine(record: StallRecord): string {
+ const blocked = Math.round(record.blockedSinceMs / 1000);
+ const state = `thread state ${record.thread.state ?? "?"}${record.thread.wchan ? `, waiting in ${record.thread.wchan}` : ""}`;
+ const why = { memory: "memory too short to profile", "hourly-cap": "the hour's profiles taken", "no-inspector": "no inspector here", pending: "profile to follow" };
+ const where = record.kind === "js"
+ ? `in JavaScript: ${record.top.slice(0, 3).map((frame) => `${frame.at} (${frame.samples})`).join("; ") || "no samples"}${record.stack.length ? `; stack ${record.stack.slice(-8).join(" > ")}` : ""}`
+ : record.kind === "outside-js" ? `outside JavaScript (${state})` : `not profiled, ${why[record.why ?? "pending"]} (${state})`;
+ const m = record.machine, num = (value: number | null, unit = "") => value === null ? "?" : `${value}${unit}`;
+ const memory = record.memory.slice(0, 4).map((entry) => `${entry.bucket} ${entry.rssMB} MB`).join(", ");
+ return `main thread blocked ${blocked}s, ${where}; memory available ${num(m.availableMB, " MB")}, memory stall ${num(m.memoryFull10, "%")}, `
+ + `cpu stall ${num(m.cpuSome10, "%")}, steal ${num(m.stealPct, "%")}${memory ? `; largest: ${memory}` : ""}`;
+}
diff --git a/server/perf/stall-ticker.test.ts b/server/perf/stall-ticker.test.ts
new file mode 100644
index 0000000000..b1877baa2a
--- /dev/null
+++ b/server/perf/stall-ticker.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from "vitest";
+
+import { createStallTicker } from "./stall-ticker.ts";
+
+const options = { thresholdMs: 10_000, repeatMs: 60_000, perStall: 5, recordsPerHour: 30, profilesPerHour: 5 };
+
+/** Ticks once a second from `from` to `to` (ms), the heartbeat at `beat(now)`; the times a record was due. */
+function run(ticker: ReturnType<typeof createStallTicker>, from: number, to: number, beat: (now: number) => number): number[] {
+ const due: number[] = [];
+ for (let now = from; now <= to; now += 1_000) if (ticker.tick(now, beat(now))) due.push(now);
+ return due;
+}
+
+describe("stall ticker", () => {
+ it("records once the heartbeat is old enough, again each minute while it stays old, five times a stall at most", () => {
+ const ticker = createStallTicker(options);
+ expect(run(ticker, 0, 5_000, (now) => now)).toEqual([]);
+ // The main thread stops beating at 5 s.
+ const due = run(ticker, 6_000, 400_000, () => 5_000);
+ expect(due).toEqual([15_000, 75_000, 135_000, 195_000, 255_000]);
+ expect(ticker.age(15_000, 5_000)).toBe(10_000);
+ });
+
+ it("starts a new stall's count once the main thread has beaten again", () => {
+ const ticker = createStallTicker(options);
+ expect(run(ticker, 0, 20_000, () => 0)).toEqual([10_000]);
+ expect(run(ticker, 21_000, 25_000, (now) => now)).toEqual([]);
+ // A second stall: a new count, but records stay at least a minute apart whatever the stall.
+ expect(run(ticker, 26_000, 100_000, () => 25_000)).toEqual([70_000]);
+ });
+
+ it("takes no more than the hour's records across stalls", () => {
+ const ticker = createStallTicker({ ...options, recordsPerHour: 3, perStall: 1 });
+ let due: number[] = [];
+ for (let stall = 0; stall < 6; stall++) {
+ const start = stall * 120_000;
+ run(ticker, start, start + 5_000, (now) => now);
+ due = due.concat(run(ticker, start + 6_000, start + 100_000, () => start + 5_000));
+ }
+ expect(due).toHaveLength(3);
+ // An hour after the first, there is room again.
+ run(ticker, 3_700_000, 3_705_000, (now) => now);
+ expect(run(ticker, 3_706_000, 3_720_000, () => 3_705_000)).toEqual([3_715_000]);
+ });
+
+ it("takes no more than five profiles in any hour", () => {
+ const ticker = createStallTicker(options);
+ const allowed = [0, 1, 2, 3, 4, 5, 6].map((minute) => ticker.mayProfile(minute * 60_000));
+ expect(allowed).toEqual([true, true, true, true, true, false, false]);
+ expect(ticker.mayProfile(3_600_001)).toBe(true);
+ });
+
+ it("counts a pause of the whole process (a late tick of its own after a fresh heartbeat) as no stall", () => {
+ const ticker = createStallTicker(options);
+ expect(run(ticker, 0, 5_000, (now) => now)).toEqual([]);
+ // Stopped for 30 s: the next tick comes 31 s later and the heartbeat is as old; then the main thread beats again.
+ expect(ticker.tick(36_000, 5_000)).toBe(false);
+ expect(run(ticker, 37_000, 60_000, (now) => now)).toEqual([]);
+ // And measured from the resume: a main thread that is stuck after it is recorded 10 s on.
+ expect(run(ticker, 61_000, 75_000, () => 60_500)).toEqual([71_000]);
+ });
+
+ it("still records when its own ticks come late while the main thread is already stuck (a starved machine)", () => {
+ const ticker = createStallTicker(options);
+ run(ticker, 0, 5_000, (now) => now);
+ // The main thread stops at 5 s; ticks then come 3 s apart.
+ const due: number[] = [];
+ for (let now = 6_000; now <= 30_000; now += 3_000) if (ticker.tick(now, 5_000)) due.push(now);
+ expect(due.length).toBe(1);
+ });
+});
diff --git a/server/perf/stall-ticker.ts b/server/perf/stall-ticker.ts
new file mode 100644
index 0000000000..7a993afb85
--- /dev/null
+++ b/server/perf/stall-ticker.ts
@@ -0,0 +1,56 @@
+// When the stall watch's thread (stall-watch.worker.ts) takes a record, from its own once-a-second ticks and the main
+// thread's heartbeat, both on the monotonic clock. Pure, so every rule is tested without a thread:
+// - a record once the heartbeat is `thresholdMs` old, again every `repeatMs` while it stays old, `perStall` at most per
+// stall, and `recordsPerHour` at most across stalls;
+// - a profile (the costly part) `profilesPerHour` at most across stalls;
+// - a tick of its own that comes late while the heartbeat was fresh at the tick before means the whole process was
+// paused (a computer asleep, a stopped process), not its main thread stuck: the heartbeat's age counts from there on.
+// A late tick while the main thread was already stuck changes nothing, so a starved machine still records.
+
+const HOUR_MS = 3_600_000;
+
+export interface StallTickerOptions {
+ thresholdMs: number;
+ repeatMs: number;
+ perStall: number;
+ recordsPerHour: number;
+ profilesPerHour: number;
+ /** The tick's own interval, and how late one may come before the process counts as paused. */
+ intervalMs?: number;
+ lateMs?: number;
+}
+
+export function createStallTicker(options: StallTickerOptions) {
+ const intervalMs = options.intervalMs ?? 1_000, lateMs = options.lateMs ?? 1_500;
+ // `previousBeatAge`: the heartbeat's own age at the tick before, never counted from a resume.
+ let lastTick: number | null = null, resumedAt = -Infinity, previousBeatAge = 0, taken = 0, lastTakenAt = -Infinity;
+ let records: number[] = [], profiles: number[] = [];
+ const ageAt = (now: number, beat: number) => now - Math.max(beat, resumedAt);
+ return {
+ /** One tick at `now` with the heartbeat last at `beat`: whether to take a record now. */
+ tick(now: number, beat: number): boolean {
+ const late = lastTick === null ? 0 : now - lastTick - intervalMs;
+ lastTick = now;
+ const fresh = previousBeatAge < lateMs;
+ previousBeatAge = now - beat;
+ if (late > lateMs && fresh) { resumedAt = now; return false; }
+ const age = ageAt(now, beat);
+ if (age < options.thresholdMs) { taken = 0; return false; }
+ records = records.filter((at) => now - at < HOUR_MS);
+ if (taken >= options.perStall || records.length >= options.recordsPerHour || now - lastTakenAt < options.repeatMs) return false;
+ taken += 1;
+ lastTakenAt = now;
+ records.push(now);
+ return true;
+ },
+ /** How long the main thread has been stuck, as the last tick saw it. */
+ age: (now: number, beat: number) => ageAt(now, beat),
+ /** Whether a profile may be taken now; counted when it says yes. */
+ mayProfile(now: number): boolean {
+ profiles = profiles.filter((at) => now - at < HOUR_MS);
+ if (profiles.length >= options.profilesPerHour) return false;
+ profiles.push(now);
+ return true;
+ },
+ };
+}
diff --git a/server/perf/stall-watch.test.ts b/server/perf/stall-watch.test.ts
new file mode 100644
index 0000000000..b31314512d
--- /dev/null
+++ b/server/perf/stall-watch.test.ts
@@ -0,0 +1,130 @@
+// The watch's own thread, for real: the main thread is held in a loop well past the threshold, and the record it leaves in
+// the data folder names that loop's function, as a frozen Cloud home's would name the code that froze it.
+import { spawn } from "node:child_process";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { StallRecord } from "./stall-sample.ts";
+import { readStallRecords, STALL_FILE, startStallWatch, stallReportLines, type StallWatch } from "./stall-watch.ts";
+
+const dirs: string[] = [];
+const watches: StallWatch[] = [];
+afterEach(() => {
+ for (const watch of watches.splice(0)) watch.stop();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+const tempDir = () => { const dir = mkdtempSync(join(tmpdir(), "omb-stall-")); dirs.push(dir); return dir; };
+
+function heldMainThreadForStallWatchTest(ms: number): number {
+ const until = Date.now() + ms;
+ let spins = 0;
+ while (Date.now() < until) spins += Math.sqrt(spins + 1) > 0 ? 1 : 0;
+ return spins;
+}
+
+const waitFor = async (check: () => boolean, ms: number) => {
+ const until = Date.now() + ms;
+ while (!check() && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 100));
+};
+
+describe("stall watch", () => {
+ it("records where the main thread is stuck, in the data folder, while it is stuck", async () => {
+ const dir = tempDir();
+ const watch = startStallWatch({ dataDir: dir, thresholdMs: 2_000, profileMs: 1_000, profileFloorMB: 0, log: () => undefined });
+ expect(watch).not.toBeNull();
+ watches.push(watch!);
+ // Let the thread start before the main thread is held.
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ // Long enough for a slow, busy machine (a shared CI runner): the record needs the threshold, a tick, and the profile.
+ heldMainThreadForStallWatchTest(12_000);
+ // Done: a profile, or the reason there is none (never "pending").
+ const done = (record: StallRecord) => record.kind !== "not-profiled" || record.why !== "pending";
+ await waitFor(() => readStallRecords(join(dir, STALL_FILE)).some(done), 20_000);
+ const record = readStallRecords(join(dir, STALL_FILE)).find(done);
+ expect(record).toBeDefined();
+ expect(record!.blockedSinceMs).toBeGreaterThanOrEqual(2_000);
+ // On Linux (the Cloud's own platform) it must be profiled; elsewhere a runner short of memory may skip the profile,
+ // and then the record says so.
+ if (process.platform === "linux" || record!.kind !== "not-profiled") {
+ expect(record!.kind).toBe("js");
+ // The loop's own frame, or the test's where V8 inlined it: this file, by its place in the app, either way.
+ expect(record!.top.some((frame) => /server\/perf\/stall-watch\.test\.ts/.test(frame.at))).toBe(true);
+ expect(stallReportLines([record!])[1]).toMatch(/main thread blocked \d+s, in JavaScript: .*stall-watch\.test\.ts/);
+ } else {
+ expect(record!.why).toBe("memory");
+ }
+ // Nothing of this machine's paths.
+ expect(JSON.stringify(record)).not.toContain(dir);
+ expect(JSON.stringify(record)).not.toContain(process.cwd());
+ }, 60_000);
+
+ it("saves the record at once and takes no profile while memory is short", async () => {
+ const dir = tempDir();
+ // A floor no machine has: memory counts as short.
+ const watch = startStallWatch({ dataDir: dir, thresholdMs: 2_000, profileMs: 1_000, profileFloorMB: 10_000_000, log: () => undefined });
+ watches.push(watch!);
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ heldMainThreadForStallWatchTest(8_000);
+ await waitFor(() => readStallRecords(join(dir, STALL_FILE)).length > 0, 10_000);
+ const records = readStallRecords(join(dir, STALL_FILE));
+ expect(records).toHaveLength(1);
+ expect(records[0]).toMatchObject({ kind: "not-profiled", why: "memory", top: [], stack: [] });
+ expect(stallReportLines(records)[1]).toContain("not profiled, memory too short to profile");
+ }, 60_000);
+
+ it("records nothing while the main thread keeps running", async () => {
+ const dir = tempDir();
+ const watch = startStallWatch({ dataDir: dir, log: () => undefined });
+ watches.push(watch!);
+ await new Promise((resolve) => setTimeout(resolve, 4_000));
+ expect(readStallRecords(join(dir, STALL_FILE))).toEqual([]);
+ }, 30_000);
+
+ it.skipIf(process.platform === "win32")("records nothing for a process that was stopped and continued", async () => {
+ const dir = tempDir();
+ const script = join(dir, "child.mjs");
+ writeFileSync(script, `import { startStallWatch } from ${JSON.stringify(new URL("./stall-watch.ts", import.meta.url).href)};
+const watch = startStallWatch({ dataDir: ${JSON.stringify(dir)}, thresholdMs: 2_000, profileMs: 500, profileFloorMB: 0, log: () => undefined });
+process.stdout.write(watch ? "started\\n" : "none\\n");
+setTimeout(() => { watch?.stop(); process.exit(0); }, 12_000);
+`);
+ const child = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "ignore"] });
+ const said = await new Promise<string>((resolve) => child.stdout!.once("data", (chunk: Buffer) => resolve(chunk.toString())));
+ expect(said.trim()).toBe("started");
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ child.kill("SIGSTOP");
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
+ child.kill("SIGCONT");
+ await new Promise<void>((resolve) => child.once("exit", () => resolve()));
+ expect(readStallRecords(join(dir, STALL_FILE))).toEqual([]);
+ }, 40_000);
+
+ it("logs the records a restart cut off when it starts, none older than a day, and never throws on a broken one", () => {
+ const dir = tempDir(), now = 1_800_000_000_000;
+ const record = (at: number) => ({ at, blockedSinceMs: 30_000, kind: "outside-js", top: [], stack: [], thread: { state: "D", wchan: null },
+ machine: { availableMB: 5, memoryFull10: 80, cpuSome10: null, stealPct: null }, memory: [{ bucket: "browser", rssMB: 2800, procs: 3 }] });
+ writeFileSync(join(dir, STALL_FILE), JSON.stringify({ v: 1, records: [record(now - 2 * 86_400_000), { at: now - 900_000 }, "junk", record(now - 600_000)] }));
+ writeFileSync(join(dir, ".perf-stalls.99999.tmp"), "{");
+ const logged: string[] = [];
+ const watch = startStallWatch({ dataDir: dir, now: () => now, log: (line) => logged.push(line) });
+ if (watch) watches.push(watch);
+ expect(logged).toHaveLength(2);
+ expect(logged[0]).toContain("main thread blocked 0s, not profiled, profile to follow (thread state ?)");
+ expect(logged[1]).toContain("outside JavaScript (thread state D)");
+ expect(logged[1]).toContain("largest: browser 2800 MB");
+ });
+
+ it("reads a missing or broken file as no records, and its thread clears a temporary file left behind", async () => {
+ const dir = tempDir();
+ expect(readStallRecords(join(dir, STALL_FILE))).toEqual([]);
+ writeFileSync(join(dir, STALL_FILE), "{not json");
+ expect(readStallRecords(join(dir, STALL_FILE))).toEqual([]);
+ writeFileSync(join(dir, ".perf-stalls.99999.tmp"), "{");
+ const watch = startStallWatch({ dataDir: dir, log: () => undefined });
+ watches.push(watch!);
+ await waitFor(() => !existsSync(join(dir, ".perf-stalls.99999.tmp")), 5_000);
+ expect(existsSync(join(dir, ".perf-stalls.99999.tmp"))).toBe(false);
+ }, 20_000);
+});
diff --git a/server/perf/stall-watch.ts b/server/perf/stall-watch.ts
new file mode 100644
index 0000000000..283fb4cecc
--- /dev/null
+++ b/server/perf/stall-watch.ts
@@ -0,0 +1,129 @@
+// The stall watch: when the server's main thread has not run for STALL_RECORD_MS, a thread of its own records where it is
+// and what the machine looks like, while it is still stuck (stall-watch.worker.ts). A Cloud home that stops answering is
+// restarted, and its log keeps only its last lines, so each record is written to the data folder (STALL_FILE) at once and
+// read back here: the next start logs the last ones, and a @devs report shows them. The main thread's part is a heartbeat
+// twice a second, a store of the time in shared memory.
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { Worker } from "node:worker_threads";
+
+import { stallLine, type StallRecord } from "./stall-sample.ts";
+
+export const STALL_FILE = "perf-stalls.json";
+/** A main thread stuck this long is recorded: the Admin's health check gives up on a home after 10 s. */
+export const STALL_RECORD_MS = 10_000;
+/** While it stays stuck, recorded again this often, at most PER_STALL times; at most RECORDS_PER_HOUR records and
+ * PROFILES_PER_HOUR profiles in any hour, across stalls. */
+const REPEAT_MS = 60_000, PER_STALL = 5, KEEP = 20, RECORDS_PER_HOUR = 30, PROFILES_PER_HOUR = 5;
+/** A profile costs the main thread tens of MB while it runs: taken only with this much memory available and the memory
+ * stall (full avg10, percent) at most this; otherwise the record has no profile. */
+const PROFILE_FLOOR_MB = 150, PROFILE_STALL_MAX = 5;
+/** How long the profile runs, and how long the main thread has to answer each inspector call before it is taken as not
+ * running JavaScript. */
+const PROFILE_MS = 2_000, ANSWER_MS = 5_000;
+const HEARTBEAT_MS = 500;
+/** Records this recent are logged when the server starts: the ones a restart cut off. */
+const SHOW_AT_START_MS = 24 * 3_600_000;
+
+export interface StallWatch {
+ stop(): void;
+ /** The newest records, newest last. */
+ recent(limit?: number): StallRecord[];
+}
+
+const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null);
+const str = (value: unknown) => (typeof value === "string" ? value : null);
+/** A kept record with every field it should have, or null: a file from another version, or edited, never throws later. */
+function wellFormed(raw: unknown): StallRecord | null {
+ if (typeof raw !== "object" || raw === null) return null;
+ const record = raw as Record<string, unknown>, at = num(record.at);
+ if (at === null) return null;
+ const kind = record.kind === "js" || record.kind === "outside-js" ? record.kind : "not-profiled";
+ const thread = (record.thread ?? {}) as Record<string, unknown>, machine = (record.machine ?? {}) as Record<string, unknown>;
+ const why = ["memory", "hourly-cap", "no-inspector", "pending"].includes(record.why as string) ? record.why as StallRecord["why"] : undefined;
+ return {
+ at, blockedSinceMs: num(record.blockedSinceMs) ?? 0, kind, ...(kind === "not-profiled" ? { why: why ?? "pending" } : {}),
+ top: Array.isArray(record.top) ? record.top.flatMap((frame: { at?: unknown; samples?: unknown }) => str(frame?.at) !== null ? [{ at: frame.at as string, samples: num(frame.samples) ?? 0 }] : []) : [],
+ stack: Array.isArray(record.stack) ? record.stack.filter((frame): frame is string => typeof frame === "string") : [],
+ thread: { state: str(thread.state), wchan: str(thread.wchan) },
+ machine: { availableMB: num(machine.availableMB), memoryFull10: num(machine.memoryFull10), cpuSome10: num(machine.cpuSome10), stealPct: num(machine.stealPct) },
+ memory: Array.isArray(record.memory) ? record.memory.flatMap((entry: { bucket?: unknown; rssMB?: unknown; procs?: unknown }) =>
+ str(entry?.bucket) !== null ? [{ bucket: entry.bucket as StallRecord["memory"][number]["bucket"], rssMB: num(entry.rssMB) ?? 0, procs: num(entry.procs) ?? 0 }] : []) : [],
+ };
+}
+
+/** The records kept in the data folder, oldest first; none when the file is missing or unreadable. */
+export function readStallRecords(file: string): StallRecord[] {
+ try {
+ const kept = JSON.parse(readFileSync(file, "utf8")) as { records?: unknown };
+ return Array.isArray(kept.records) ? kept.records.flatMap((record) => wellFormed(record) ?? []) : [];
+ } catch {
+ return [];
+ }
+}
+
+/** The report's lines: the newest records, newest last. */
+export function stallReportLines(records: readonly StallRecord[]): string[] {
+ if (!records.length) return [];
+ return ["Main thread stalls caught (newest last):", ...records.map((record) => `${new Date(record.at).toISOString()} ${stallLine(record)}`)];
+}
+
+/** The app's own folder: the parent of `server/` from the source, of `dist-server/` from the bundle. */
+function appRoot(): string {
+ const here = dirname(fileURLToPath(import.meta.url));
+ return /[\\/]perf$/.test(here) ? dirname(dirname(here)) : dirname(here);
+}
+
+function workerUrl(): URL | null {
+ // From the source (server/perf/), the bundle (dist-server/index.js), or a compiled copy beside this file's folder.
+ for (const candidate of ["../stall-watch.worker.ts", "./stall-watch.worker.js", "../stall-watch.worker.js"]) {
+ const url = new URL(candidate, import.meta.url);
+ if (existsSync(url)) return url;
+ }
+ return null;
+}
+
+export interface StallWatchOptions {
+ dataDir: string;
+ log?: (line: string) => void;
+ /** Tests: a shorter threshold and profile, another memory floor for a profile. */
+ thresholdMs?: number;
+ profileMs?: number;
+ profileFloorMB?: number;
+ now?: () => number;
+}
+
+/** Starts the watch; null where its thread can't start (it never stops the server from starting). */
+export function startStallWatch(options: StallWatchOptions): StallWatch | null {
+ const file = join(options.dataDir, STALL_FILE), now = options.now ?? Date.now;
+ const log = options.log ?? ((line: string) => console.warn(line));
+ const earlier = readStallRecords(file).filter((record) => now() - record.at <= SHOW_AT_START_MS).slice(-3);
+ for (const record of earlier) { try { log(`[perf] stall before this start, ${new Date(record.at).toISOString()}: ${stallLine(record)}`); } catch {} }
+ const url = workerUrl();
+ if (!url) return null;
+ // The monotonic clock, the same in every thread of the process: a change of the wall clock is never a stall.
+ const shared = new SharedArrayBuffer(8), beat = new BigInt64Array(shared);
+ const pulse = () => Atomics.store(beat, 0, process.hrtime.bigint() / 1_000_000n);
+ pulse();
+ const heart = setInterval(pulse, HEARTBEAT_MS);
+ heart.unref?.();
+ let worker: Worker;
+ try {
+ worker = new Worker(url, {
+ workerData: { beat: shared, dataDir: options.dataDir, file, appRoot: appRoot(), thresholdMs: options.thresholdMs ?? STALL_RECORD_MS, repeatMs: REPEAT_MS,
+ profileMs: options.profileMs ?? PROFILE_MS, answerMs: ANSWER_MS, keep: KEEP, perStall: PER_STALL, recordsPerHour: RECORDS_PER_HOUR, profilesPerHour: PROFILES_PER_HOUR,
+ profileFloorMB: options.profileFloorMB ?? PROFILE_FLOOR_MB, profileStallMax: PROFILE_STALL_MAX },
+ // No test loaders or inspector ports of the parent; a small heap of its own.
+ execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 64 },
+ });
+ } catch {
+ clearInterval(heart);
+ return null;
+ }
+ worker.unref();
+ let stopped = false;
+ const stop = () => { if (stopped) return; stopped = true; clearInterval(heart); void worker.terminate().catch(() => undefined); };
+ worker.on("error", (error) => { log(`[perf] the stall watch stopped: ${error instanceof Error ? error.name : "error"}`); stop(); });
+ return { stop, recent: (limit = 5) => readStallRecords(file).slice(-limit) };
+}
diff --git a/server/stall-watch.worker.ts b/server/stall-watch.worker.ts
new file mode 100644
index 0000000000..7783a565f3
--- /dev/null
+++ b/server/stall-watch.worker.ts
@@ -0,0 +1,134 @@
+// The stall watch's own thread (perf/stall-watch.ts). It reads the main thread's heartbeat every second (perf/stall-ticker.ts
+// decides when to record). Once the main thread has not beaten for `thresholdMs` it records, while that thread is still
+// stuck, what costs nothing first: the thread's state and wait channel from /proc (a system call, a page fault), the
+// memory available to this server and the memory and CPU stall, the memory each kind of process holds; that record goes to
+// the data folder and to stderr at once. Only then, and only with memory to spare (a profile costs the main thread tens of
+// MB, which on a thrashing home could bring the OOM killer), a short CPU profile of the main thread through the inspector
+// (answered between two JavaScript instructions, so a loop or a long regex shows its code) completes the record.
+import { closeSync, fsyncSync, openSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
+import { join } from "node:path";
+import { workerData } from "node:worker_threads";
+
+import { classifyProcesses } from "./perf/process-buckets.ts";
+import { linuxProcessList } from "./perf/process-sampler.ts";
+import { availableMB, pressure10, stallLine, stealPercent, summarizeProfile, threadState, type CpuProfile, type StallRecord } from "./perf/stall-sample.ts";
+import { createStallTicker } from "./perf/stall-ticker.ts";
+
+interface WatchData {
+ beat: SharedArrayBuffer; dataDir: string; file: string; appRoot: string; thresholdMs: number; repeatMs: number; profileMs: number; answerMs: number; keep: number;
+ perStall: number; recordsPerHour: number; profilesPerHour: number; profileFloorMB: number; profileStallMax: number;
+}
+const data = workerData as WatchData;
+const beat = new BigInt64Array(data.beat);
+const read = (path: string): string | null => { try { return readFileSync(path, "utf8"); } catch { return null; } };
+const MB = 1_048_576;
+const monotonicMs = () => Number(process.hrtime.bigint() / 1_000_000n);
+const tmpPrefix = ".perf-stalls.";
+
+function within<T>(promise: Promise<T>, ms: number): Promise<T | "late"> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => resolve("late"), ms);
+ promise.then((value) => { clearTimeout(timer); resolve(value); }, () => { clearTimeout(timer); resolve("late"); });
+ });
+}
+
+/** A profile of the main thread for `profileMs`; "late" when it did not answer within `answerMs` (it is not running
+ * JavaScript), "unavailable" when this Node has no inspector. */
+async function profileMain(): Promise<CpuProfile | "late" | "unavailable"> {
+ type MainSession = { connectToMainThread(): void; post(method: string, params?: object): Promise<unknown>; disconnect(): void };
+ let opened: MainSession | null = null;
+ try {
+ let Session: new () => MainSession;
+ try { Session = (await import("node:inspector/promises")).Session as unknown as new () => MainSession; } catch { return "unavailable"; }
+ const session = new Session();
+ opened = session;
+ try { session.connectToMainThread(); } catch { return "unavailable"; }
+ if (await within(session.post("Profiler.enable"), data.answerMs) === "late") return "late";
+ await within(session.post("Profiler.setSamplingInterval", { interval: 1000 }), data.answerMs);
+ if (await within(session.post("Profiler.start"), data.answerMs) === "late") return "late";
+ await new Promise((resolve) => setTimeout(resolve, data.profileMs));
+ const stopped = await within(session.post("Profiler.stop") as Promise<{ profile: CpuProfile }>, data.answerMs);
+ return stopped === "late" ? "late" : stopped.profile;
+ } catch {
+ return "late";
+ } finally {
+ try { opened?.disconnect(); } catch {}
+ }
+}
+
+/** Memory available to this server: within its cgroup's limit where it has one (libuv), else the machine's. */
+function availableToServer(): number | null {
+ try { const bytes = process.availableMemory?.(); if (typeof bytes === "number" && bytes > 0) return Math.round(bytes / MB); } catch {}
+ return availableMB(read("/proc/meminfo"));
+}
+
+function memoryByKind(): StallRecord["memory"] {
+ if (process.platform !== "linux") return [];
+ try {
+ const { rows } = linuxProcessList();
+ const buckets = classifyProcesses(rows, process.pid, false);
+ const sums = new Map<string, { rss: number; procs: number }>();
+ for (const row of rows) {
+ const bucket = buckets.get(row.pid) ?? "other";
+ const sum = sums.get(bucket) ?? { rss: 0, procs: 0 };
+ sum.rss += row.rssBytes;
+ sum.procs += 1;
+ sums.set(bucket, sum);
+ }
+ return [...sums].map(([bucket, sum]) => ({ bucket: bucket as StallRecord["memory"][number]["bucket"], rssMB: Math.round(sum.rss / MB), procs: sum.procs }))
+ .sort((a, b) => b.rssMB - a.rssMB).slice(0, 8);
+ } catch {
+ return [];
+ }
+}
+
+/** Saved in place of an earlier record taken at the same moment (a record completed by its profile), else appended. */
+function save(record: StallRecord): void {
+ const tmp = join(data.dataDir, `${tmpPrefix}${process.pid}.tmp`);
+ try {
+ let records: StallRecord[] = [];
+ try { const kept = JSON.parse(readFileSync(data.file, "utf8")) as { records?: StallRecord[] }; records = Array.isArray(kept.records) ? kept.records : []; } catch {}
+ records = [...records.filter((kept) => kept?.at !== record.at), record].slice(-data.keep);
+ // Written and flushed through one descriptor (Windows flushes only a file open for writing); a flush that fails still
+ // leaves the record, as a crash before it would.
+ const fd = openSync(tmp, "w");
+ try { writeFileSync(fd, JSON.stringify({ v: 1, records })); try { fsyncSync(fd); } catch {} } finally { closeSync(fd); }
+ renameSync(tmp, data.file);
+ } catch {
+ try { unlinkSync(tmp); } catch {}
+ }
+ // Straight to the descriptor: a worker's console goes through the main thread, which is stuck.
+ try { writeSync(2, `[perf] ${stallLine(record)}\n`); } catch {}
+}
+
+async function take(blockedSinceMs: number, mayProfile: () => boolean): Promise<void> {
+ const statBefore = read("/proc/stat");
+ const self = `/proc/${process.pid}/task/${process.pid}`;
+ const machine: StallRecord["machine"] = { availableMB: availableToServer(), memoryFull10: pressure10(read("/proc/pressure/memory"), "full"),
+ cpuSome10: pressure10(read("/proc/pressure/cpu"), "some"), stealPct: null };
+ const light: StallRecord = { at: Date.now(), blockedSinceMs, kind: "not-profiled", why: "pending", top: [], stack: [], thread: threadState(read(`${self}/stat`), read(`${self}/wchan`)),
+ machine, memory: memoryByKind() };
+ const roomy = (machine.availableMB ?? 0) >= data.profileFloorMB && (machine.memoryFull10 ?? 0) <= data.profileStallMax;
+ const why: StallRecord["why"] = !roomy ? "memory" : mayProfile() ? undefined : "hourly-cap";
+ if (why) light.why = why;
+ save(light);
+ if (why) return;
+ const profile = await profileMain();
+ const summary = typeof profile === "object" ? summarizeProfile(profile, data.appRoot) : null;
+ const done: StallRecord = { ...light, ...(summary ? { kind: "js" as const, top: summary.top, stack: summary.stack } : profile === "late" ? { kind: "outside-js" as const } : { why: "no-inspector" as const }),
+ machine: { ...machine, stealPct: stealPercent(statBefore, read("/proc/stat")) } };
+ if (done.kind !== "not-profiled") delete done.why;
+ save(done);
+}
+
+// A temporary file a stopped process left behind.
+try { for (const name of readdirSync(data.dataDir)) if (name.startsWith(tmpPrefix) && name.endsWith(".tmp")) try { unlinkSync(join(data.dataDir, name)); } catch {} } catch {}
+
+const ticker = createStallTicker({ thresholdMs: data.thresholdMs, repeatMs: data.repeatMs, perStall: data.perStall, recordsPerHour: data.recordsPerHour, profilesPerHour: data.profilesPerHour });
+let busy = false;
+setInterval(() => {
+ const now = monotonicMs(), beatAt = Number(Atomics.load(beat, 0));
+ if (!ticker.tick(now, beatAt) || busy) return;
+ busy = true;
+ void take(ticker.age(now, beatAt), () => ticker.mayProfile(monotonicMs())).finally(() => { busy = false; });
+}, 1000);