Public: anyone can read this; the crew can change it.
After the 0.7.718 release the forge's event loop was blocked for 159.6 s #17711
Merged 11h 8m ago, live in production
torque/forge:torque/17708-after-the-0-7-718-release-the-forge-s-ev → main 0 commits fork 5 threads · 5 unresolved
11 files
changed +338
−8
src/crew/dispatch.ts +6 −2
| @@ -158,7 +158,7 @@ import { | ||
| 158 | 158 | type Pause, |
| 159 | 159 | } from "./runner.ts"; |
| 160 | 160 | import { steerRun } from "./steer.ts"; |
| 161 | import { STALE_AFTER_MS } from "../runs/lease.ts"; | |
| 161 | import { STALE_AFTER_MS, heldRuns } from "../runs/lease.ts"; | |
| 162 | 162 | import { stoppedMark } from "../spawn/stopped.ts"; |
| 163 | 163 | import { abortAgentRun } from "./running.ts"; |
| 164 | 164 | import { background, during } from "../perf/jobs.ts"; |
| @@ -1604,8 +1604,12 @@ export function interruptionBackoffMs(n: number): number { | ||
| 1604 | 1604 | * forge that fell and was back within the lease sees its runs lapse later. |
| 1605 | 1605 | */ |
| 1606 | 1606 | export function requeueInterrupted(app: App): void { |
| 1607 | // A run this process holds is alive here: its lease looks lapsed only when this process's own | |
| 1608 | // loop stalled (#17708, which made #17706 and #17707 for one issue). Its worker finishes or fails | |
| 1609 | // it. | |
| 1610 | const mine = heldRuns(app.db); | |
| 1607 | 1611 | for (const run of listActive(app.db, "agent")) { |
| 1608 | if (run.state !== "running" || !leaseLapsed(run, STALE_AFTER_MS)) continue; | |
| 1612 | if (run.state !== "running" || mine.has(run.id) || !leaseLapsed(run, STALE_AFTER_MS)) continue; | |
| 1609 | 1613 | if (stoppedForMemory(app, run)) { |
| 1610 | 1614 | // The host stopped this forge for memory: the run is queued again once; a run stopped that |
| 1611 | 1615 | // way twice would only stop it again, so it fails with the reason. |
src/kernel/census.ts +5 −1
| @@ -16,6 +16,8 @@ export interface ProcessRow { | ||
| 16 | 16 | readonly pgid: number; |
| 17 | 17 | /** The kernel's command name (`/proc/<pid>/stat`'s second field), at most 15 bytes. */ |
| 18 | 18 | readonly comm: string; |
| 19 | /** `num_threads`, field 20, when the line has it. */ | |
| 20 | readonly threads?: number; | |
| 19 | 21 | } |
| 20 | 22 | |
| 21 | 23 | /** Every process in `root` (default `/proc`); one that goes mid-read is skipped. */ |
| @@ -55,7 +57,9 @@ export function parseStat(stat: string): ProcessRow | undefined { | ||
| 55 | 57 | const ppid = Number(fields[1]); |
| 56 | 58 | const pgid = Number(fields[2]); |
| 57 | 59 | if (![pid, ppid, pgid].every(Number.isSafeInteger)) return undefined; |
| 58 | return { pid, ppid, pgid, comm: stat.slice(open + 1, close) }; | |
| 60 | const threads = Number(fields[17]); | |
| 61 | const comm = stat.slice(open + 1, close); | |
| 62 | return Number.isSafeInteger(threads) ? { pid, ppid, pgid, comm, threads } : { pid, ppid, pgid, comm }; | |
| 59 | 63 | } |
| 60 | 64 | |
| 61 | 65 | /** How many processes carry each command name, but this process itself. */ |
src/kernel/loop_watchdog.ts added +98
| @@ -0,0 +1,98 @@ | ||
| 1 | /** | |
| 2 | * A line written while the loop is blocked, by something outside the thread (#17708). | |
| 3 | * | |
| 4 | * The loop watch (`loop_lag.ts`) is a timer on the thread it watches: it can only say a stall | |
| 5 | * happened after it ends, so 159.6 s of 0.7.718 left no line until 23:12:15. This is a Worker | |
| 6 | * (`loop_watchdog_worker.ts`, started by file like the forge's other workers), a thread of its | |
| 7 | * own, that reads a heartbeat the main thread writes every `beatMs` into shared memory. When the | |
| 8 | * heartbeat is older than `afterMs` it writes `event loop still blocked` to stderr and to | |
| 9 | * `<data>/perf/loop-watchdog.log`, again each `repeatMs`, and one closing line when the beat | |
| 10 | * returns. The file is a kept log (`perf/kept_log.ts`), so its size is capped and rotated. | |
| 11 | * | |
| 12 | * When it speaks it also says the host's 1-minute load and the processes and threads in the | |
| 13 | * container, and under the forge by name (`proc_census.ts`), for the load of 318 to 1,629 that | |
| 14 | * followed the release: who the forge had started by then. | |
| 15 | * | |
| 16 | * What it decides is `watchStep`, a pure function of the heartbeat's age, tested without a thread. | |
| 17 | */ | |
| 18 | ||
| 19 | import type { WatchdogStart } from "./loop_watchdog_worker.ts"; | |
| 20 | ||
| 21 | export const WATCHDOG_AFTER_MS = 3_000; | |
| 22 | export const WATCHDOG_REPEAT_MS = 15_000; | |
| 23 | export const WATCHDOG_BEAT_MS = 250; | |
| 24 | /** | |
| 25 | * The watchdog's file under the data directory: a kept log of its own, so no two writers rotate one | |
| 26 | * file. | |
| 27 | */ | |
| 28 | export const WATCHDOG_FILE = "perf/loop-watchdog.log"; | |
| 29 | ||
| 30 | export interface WatchdogOptions { | |
| 31 | afterMs?: number; | |
| 32 | repeatMs?: number; | |
| 33 | beatMs?: number; | |
| 34 | /** The data directory the lines are kept under; none: stderr only. */ | |
| 35 | dataDir?: string | undefined; | |
| 36 | } | |
| 37 | ||
| 38 | /** What the watchdog remembers between looks. */ | |
| 39 | export interface WatchState { | |
| 40 | readonly blocked: boolean; | |
| 41 | /** The silence at the last line written, ms. */ | |
| 42 | readonly reportedAt: number; | |
| 43 | /** The longest silence seen in this block, ms. */ | |
| 44 | readonly peak: number; | |
| 45 | } | |
| 46 | ||
| 47 | export const CALM: WatchState = { blocked: false, reportedAt: 0, peak: 0 }; | |
| 48 | ||
| 49 | /** One look at a heartbeat `silentMs` old: the next state, and whether a line is due and which. */ | |
| 50 | export function watchStep( | |
| 51 | state: WatchState, | |
| 52 | silentMs: number, | |
| 53 | afterMs: number, | |
| 54 | repeatMs: number, | |
| 55 | ): { state: WatchState; say: "blocked" | "closing" | null; silentMs: number } { | |
| 56 | if (silentMs >= afterMs) { | |
| 57 | const due = !state.blocked || silentMs - state.reportedAt >= repeatMs; | |
| 58 | const next = { blocked: true, reportedAt: due ? silentMs : state.reportedAt, peak: silentMs }; | |
| 59 | return { state: next, say: due ? "blocked" : null, silentMs }; | |
| 60 | } | |
| 61 | if (state.blocked) return { state: CALM, say: "closing", silentMs: state.peak }; | |
| 62 | return { state, say: null, silentMs }; | |
| 63 | } | |
| 64 | ||
| 65 | /** The line a blocked loop gets; scope `loop`, the log's own shape. */ | |
| 66 | export function blockedLine(at: Date, silentMs: number, closing: boolean, extra = ""): string { | |
| 67 | const s = (Math.round(silentMs / 100) / 10).toFixed(1); | |
| 68 | return `${at.toISOString()} WARN [loop] ${ | |
| 69 | closing | |
| 70 | ? `event loop answered again after at least ${s} s without a heartbeat (seen from outside the thread)` | |
| 71 | : `event loop still blocked: no heartbeat for ${s} s (seen from outside the thread)${extra}` | |
| 72 | }`; | |
| 73 | } | |
| 74 | ||
| 75 | export interface Watchdog { | |
| 76 | stop(): void; | |
| 77 | } | |
| 78 | ||
| 79 | /** Start the watchdog; the beat is an unref'd timer on this thread. Returns the stop. */ | |
| 80 | export function startLoopWatchdog(o: WatchdogOptions = {}): Watchdog { | |
| 81 | const afterMs = o.afterMs ?? WATCHDOG_AFTER_MS; | |
| 82 | const repeatMs = o.repeatMs ?? WATCHDOG_REPEAT_MS; | |
| 83 | const beatMs = o.beatMs ?? WATCHDOG_BEAT_MS; | |
| 84 | const sab = new SharedArrayBuffer(8); | |
| 85 | const beat = new BigInt64Array(sab); | |
| 86 | Atomics.store(beat, 0, BigInt(Date.now())); | |
| 87 | const worker = new Worker(new URL("./loop_watchdog_worker.ts", import.meta.url).href); | |
| 88 | worker.unref(); | |
| 89 | worker.postMessage({ sab, afterMs, repeatMs, dataDir: o.dataDir, pid: process.pid } satisfies WatchdogStart); | |
| 90 | const timer = setInterval(() => Atomics.store(beat, 0, BigInt(Date.now())), beatMs); | |
| 91 | timer.unref(); | |
| 92 | return { | |
| 93 | stop() { | |
| 94 | clearInterval(timer); | |
| 95 | worker.terminate(); | |
| 96 | }, | |
| 97 | }; | |
| 98 | } |
src/kernel/loop_watchdog_worker.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | /** | |
| 2 | * The watchdog's own thread (`loop_watchdog.ts`): it reads the heartbeat the serving thread | |
| 3 | * writes and, while it is stale, writes a line the serving thread could not (#17708). | |
| 4 | */ | |
| 5 | ||
| 6 | import { loadavg } from "node:os"; | |
| 7 | import { processRows } from "./census.ts"; | |
| 8 | import { keptLog } from "../perf/kept_log.ts"; | |
| 9 | import { CALM, WATCHDOG_FILE, blockedLine, watchStep } from "./loop_watchdog.ts"; | |
| 10 | import { census, censusWords } from "./proc_census.ts"; | |
| 11 | ||
| 12 | /** What the watchdog is told. */ | |
| 13 | export interface WatchdogStart { | |
| 14 | readonly sab: SharedArrayBuffer; | |
| 15 | readonly afterMs: number; | |
| 16 | readonly repeatMs: number; | |
| 17 | readonly dataDir: string | undefined; | |
| 18 | /** The serving process, whose descendants are counted. */ | |
| 19 | readonly pid: number; | |
| 20 | } | |
| 21 | ||
| 22 | declare const self: Worker; | |
| 23 | ||
| 24 | /** Load and the process tree now, as a phrase; a host without `/proc` says only the load. */ | |
| 25 | function surroundings(pid: number): string { | |
| 26 | const load = `; load 1m ${loadavg()[0]!.toFixed(1)}`; | |
| 27 | try { | |
| 28 | return `${load}; ${censusWords(census(processRows(), pid))}`; | |
| 29 | } catch { | |
| 30 | return load; | |
| 31 | } | |
| 32 | } | |
| 33 | ||
| 34 | self.onmessage = (e: MessageEvent<WatchdogStart>) => { | |
| 35 | const { sab, afterMs, repeatMs, dataDir, pid } = e.data; | |
| 36 | const beat = new BigInt64Array(sab); | |
| 37 | // A kept log of its own: size capped and rotated; flushed at once, for the loop may stay blocked. | |
| 38 | const kept = dataDir === undefined ? undefined : keptLog(dataDir, { file: WATCHDOG_FILE }); | |
| 39 | const write = (text: string): void => { | |
| 40 | process.stderr.write(`${text}\n`); | |
| 41 | kept?.add(text); | |
| 42 | kept?.flush(); | |
| 43 | }; | |
| 44 | let state = CALM; | |
| 45 | setInterval(() => { | |
| 46 | const now = Date.now(); | |
| 47 | const step = watchStep(state, now - Number(Atomics.load(beat, 0)), afterMs, repeatMs); | |
| 48 | state = step.state; | |
| 49 | if (step.say === "blocked") write(blockedLine(new Date(now), step.silentMs, false, surroundings(pid))); | |
| 50 | else if (step.say === "closing") write(blockedLine(new Date(now), step.silentMs, true)); | |
| 51 | }, Math.max(250, Math.floor(afterMs / 3))); | |
| 52 | }; |
src/kernel/proc_census.ts added +56
| @@ -0,0 +1,56 @@ | ||
| 1 | /** | |
| 2 | * Who is running, counted by parent (#17708). After 0.7.718 the host's 1-minute load read 318 and, | |
| 3 | * second-hand, 1,629: more runnable threads than any one thread of the forge could make, so the | |
| 4 | * first thing to know is how many processes and threads the forge's own tree holds when the loop | |
| 5 | * stops answering. Rows come from `census.ts` (`processRows`), read by the watchdog's worker, never | |
| 6 | * by the serving thread. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { ProcessRow } from "./census.ts"; | |
| 10 | ||
| 11 | export interface Census { | |
| 12 | /** Every process the reader could see (its own container) and their threads. */ | |
| 13 | readonly processes: number; | |
| 14 | readonly threads: number; | |
| 15 | /** The descendants of `root`: how many, their threads, and the names most numerous. */ | |
| 16 | readonly below: { readonly processes: number; readonly threads: number; readonly top: readonly (readonly [string, number])[] }; | |
| 17 | } | |
| 18 | ||
| 19 | /** Count `rows` and, under `root`, the processes that descend from it. */ | |
| 20 | export function census(rows: readonly ProcessRow[], root: number, top = 4): Census { | |
| 21 | const kids = new Map<number, ProcessRow[]>(); | |
| 22 | for (const r of rows) { | |
| 23 | const list = kids.get(r.ppid); | |
| 24 | if (list === undefined) kids.set(r.ppid, [r]); | |
| 25 | else list.push(r); | |
| 26 | } | |
| 27 | const names = new Map<string, number>(); | |
| 28 | let processes = 0; | |
| 29 | let threads = 0; | |
| 30 | const seen = new Set<number>([root]); | |
| 31 | const queue = [root]; | |
| 32 | while (queue.length > 0) { | |
| 33 | for (const k of kids.get(queue.shift()!) ?? []) { | |
| 34 | if (seen.has(k.pid)) continue; | |
| 35 | seen.add(k.pid); | |
| 36 | queue.push(k.pid); | |
| 37 | processes++; | |
| 38 | threads += k.threads ?? 1; | |
| 39 | names.set(k.comm, (names.get(k.comm) ?? 0) + 1); | |
| 40 | } | |
| 41 | } | |
| 42 | const ranked = [...names].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, top); | |
| 43 | return { | |
| 44 | processes: rows.length, | |
| 45 | threads: rows.reduce((n, r) => n + (r.threads ?? 1), 0), | |
| 46 | below: { processes, threads, top: ranked }, | |
| 47 | }; | |
| 48 | } | |
| 49 | ||
| 50 | /** | |
| 51 | * The census as a log phrase: `procs 812, threads 1403; under pid: 640 procs (bun 400, git 120)`. | |
| 52 | */ | |
| 53 | export function censusWords(c: Census): string { | |
| 54 | const top = c.below.top.map(([n, k]) => `${n} ${k}`).join(", "); | |
| 55 | return `procs ${c.processes}, threads ${c.threads}; under pid: ${c.below.processes} procs, ${c.below.threads} threads${top === "" ? "" : ` (${top})`}`; | |
| 56 | } |
src/main.ts +6
| @@ -125,6 +125,7 @@ import { reapLeftoverBridges } from "./crew/leftovers.ts"; | ||
| 125 | 125 | import { crewRoot } from "./crew/workdir.ts"; |
| 126 | 126 | import { createLog, teeLines } from "./kernel/log.ts"; |
| 127 | 127 | import { keptLine, keptLog } from "./perf/kept_log.ts"; |
| 128 | import { startLoopWatchdog } from "./kernel/loop_watchdog.ts"; | |
| 128 | 129 | import { loadOrNone, startService } from "./kernel/start_service.ts"; |
| 129 | 130 | import { METER_EVERY_MS, newMeterWatch } from "./crew/meter_watch.ts"; |
| 130 | 131 | import { watchStalls } from "./kernel/loop_lag.ts"; |
| @@ -311,6 +312,11 @@ watchStalls(loopLog, undefined, undefined, undefined, (late, at) => { | ||
| 311 | 312 | stallRelay.note(late, at); |
| 312 | 313 | }); |
| 313 | 314 | |
| 315 | // A line from outside this thread while it is blocked: the watch above can only speak after | |
| 316 | // (#17708). | |
| 317 | const loopWatchdog = startLoopWatchdog({ dataDir: readOnly ? undefined : dataDir }); | |
| 318 | process.on("exit", () => loopWatchdog.stop()); | |
| 319 | ||
| 314 | 320 | const previewKey = previewIdentityKey(process.env); |
| 315 | 321 | |
| 316 | 322 | const engineShape = engineChoice(process.env, { hosted, readOnly, machine: readMachine() }); |
src/perf/kept_log.ts +4 −4
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | */ |
| 19 | 19 | |
| 20 | 20 | import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs"; |
| 21 | import { join } from "node:path"; | |
| 21 | import { dirname, join } from "node:path"; | |
| 22 | 22 | import { background } from "./jobs.ts"; |
| 23 | 23 | |
| 24 | 24 | /** The file the lines go to, under the data directory. */ |
| @@ -47,10 +47,10 @@ export interface KeptLog { | ||
| 47 | 47 | } |
| 48 | 48 | |
| 49 | 49 | /** The kept log of `dataDir`: buffered appends, rotated by size. */ |
| 50 | export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; flushMs?: number } = {}): KeptLog { | |
| 50 | export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; flushMs?: number; file?: string } = {}): KeptLog { | |
| 51 | 51 | const maxBytes = o.maxBytes ?? MAX_BYTES; |
| 52 | 52 | const keep = o.keep ?? KEEP; |
| 53 | const file = join(dataDir, KEPT_FILE); | |
| 53 | const file = join(dataDir, o.file ?? KEPT_FILE); | |
| 54 | 54 | let buffer: string[] = []; |
| 55 | 55 | let bytes = 0; |
| 56 | 56 | let size: number | undefined; |
| @@ -68,7 +68,7 @@ export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; | ||
| 68 | 68 | bytes = 0; |
| 69 | 69 | try { |
| 70 | 70 | if (size === undefined) { |
| 71 | mkdirSync(join(dataDir, "perf"), { recursive: true }); | |
| 71 | mkdirSync(dirname(file), { recursive: true }); | |
| 72 | 72 | size = existsSync(file) ? statSync(file).size : 0; |
| 73 | 73 | } |
| 74 | 74 | const add = Buffer.byteLength(text); |
test/crew-interrupted-out.test.ts +18 −1
| @@ -15,7 +15,7 @@ import { INTERRUPTED_OUT } from "../src/crew/give_up.ts"; | ||
| 15 | 15 | import { daySpent } from "../src/core/account_ceiling.ts"; |
| 16 | 16 | import { noteRunProgress } from "../src/core/runs.ts"; |
| 17 | 17 | import { recordUsage, usageTotals } from "../src/core/usage.ts"; |
| 18 | import { STALE_AFTER_MS } from "../src/runs/lease.ts"; | |
| 18 | import { STALE_AFTER_MS, holdLease } from "../src/runs/lease.ts"; | |
| 19 | 19 | import type { User } from "../src/core/users.ts"; |
| 20 | 20 | |
| 21 | 21 | /** Every queued run of one kind, those still waiting out a backoff included. */ |
| @@ -68,6 +68,23 @@ describe("a run a restart cuts off", () => { | ||
| 68 | 68 | }; |
| 69 | 69 | const forIssue = (issueId: string) => queuedIncludingWaiting(app.db, "agent").filter((r) => r.issueId === issueId); |
| 70 | 70 | |
| 71 | test("a run this process holds is not requeued when its lease only looks lapsed (#17708)", async () => { | |
| 72 | const { issue, run } = await setup(); | |
| 73 | claimRun(app.db, run.id); | |
| 74 | const release = holdLease(app.db, run.id); | |
| 75 | const backdate = () => app.db.query("UPDATE run SET heartbeat_at = '1970-01-01T00:00:00Z' WHERE id = ?").run(run.id); | |
| 76 | backdate(); | |
| 77 | requeueInterrupted(app); | |
| 78 | expect(getRun(app.db, run.id)?.state).toBe("running"); | |
| 79 | expect(forIssue(issue.id)).toHaveLength(0); | |
| 80 | // Let go of it, and a run nobody holds is recovered as before. | |
| 81 | release(); | |
| 82 | backdate(); | |
| 83 | requeueInterrupted(app); | |
| 84 | expect(getRun(app.db, run.id)?.state).not.toBe("running"); | |
| 85 | expect(forIssue(issue.id)).toHaveLength(1); | |
| 86 | }); | |
| 87 | ||
| 71 | 88 | test("once: cancelled and queued again", async () => { |
| 72 | 89 | const { issue, run } = await setup(); |
| 73 | 90 | lapse(run.id); |
test/kernel-boundary.test.ts +1
| @@ -22,6 +22,7 @@ const KERNEL = resolve(import.meta.dir, "..", "src", "kernel"); | ||
| 22 | 22 | /** Each import that leaves the kernel today, `file -> specifier`, and why it still does. */ |
| 23 | 23 | const CROSSINGS: Readonly<Record<string, string>> = { |
| 24 | 24 | "full_disk.ts -> ../perf/jobs.ts": "names the job running when the disk filled", |
| 25 | "loop_watchdog_worker.ts -> ../perf/kept_log.ts": "the watchdog worker writes its capped, rotated log", | |
| 25 | 26 | "guard.ts -> ../http/health.ts": "the guard answers with the health verdict", |
| 26 | 27 | "outbound.ts -> ../apps/egress.ts": "the cell proxy and its refusal words live with the apps' egress", |
| 27 | 28 | "preflight.ts -> ../settings/signup.ts": "preflight checks the signup setting read from the env", |
test/loop-watchdog.test.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | // #17708: a line is written while the loop is blocked, from outside the thread. | |
| 2 | import { expect, test } from "bun:test"; | |
| 3 | import { existsSync, mkdtempSync, readFileSync } from "node:fs"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { parseStat } from "../src/kernel/census.ts"; | |
| 7 | import { CALM, WATCHDOG_FILE, blockedLine, startLoopWatchdog, watchStep } from "../src/kernel/loop_watchdog.ts"; | |
| 8 | import { census, censusWords } from "../src/kernel/proc_census.ts"; | |
| 9 | import { keptLog } from "../src/perf/kept_log.ts"; | |
| 10 | import { waitFor } from "./helpers/poll.ts"; | |
| 11 | ||
| 12 | const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms)); // real-timer: the thread smoke test watches a real clock | |
| 13 | ||
| 14 | test("the decision: quiet, a block, its repeats, and its end are a function of the silence", () => { | |
| 15 | const look = (s: Parameters<typeof watchStep>[0], silent: number) => watchStep(s, silent, 3_000, 15_000); | |
| 16 | expect(look(CALM, 200).say).toBeNull(); | |
| 17 | const first = look(CALM, 3_100); | |
| 18 | expect(first.say).toBe("blocked"); | |
| 19 | expect(first.state).toEqual({ blocked: true, reportedAt: 3_100, peak: 3_100 }); | |
| 20 | const middle = look(first.state, 10_000); | |
| 21 | expect(middle.say).toBeNull(); | |
| 22 | expect(middle.state.peak).toBe(10_000); | |
| 23 | const again = look(middle.state, 18_200); | |
| 24 | expect(again.say).toBe("blocked"); | |
| 25 | expect(again.state.reportedAt).toBe(18_200); | |
| 26 | const end = look(again.state, 100); | |
| 27 | expect(end).toEqual({ state: CALM, say: "closing", silentMs: 18_200 }); | |
| 28 | }); | |
| 29 | ||
| 30 | test("the lines read as the log's own", () => { | |
| 31 | const at = new Date("2026-12-02T23:10:00.000Z"); | |
| 32 | expect(blockedLine(at, 12_345, false, "; load 1m 4.0")).toBe( | |
| 33 | "2026-12-02T23:10:00.000Z WARN [loop] event loop still blocked: no heartbeat for 12.3 s (seen from outside the thread); load 1m 4.0", | |
| 34 | ); | |
| 35 | expect(blockedLine(at, 12_345, true)).toContain("answered again after at least 12.3 s"); | |
| 36 | }); | |
| 37 | ||
| 38 | test("the census counts descendants by name and parses a name with parentheses", () => { | |
| 39 | expect(parseStat("42 (a (b) c) S 7 0 0 0 0 0 0 0 0 0 0 0 0 0 20 0 5 0 1 2 3")).toEqual({ pid: 42, ppid: 7, pgid: 0, comm: "a (b) c", threads: 5 }); | |
| 40 | expect(parseStat("junk")).toBeUndefined(); | |
| 41 | const row = (pid: number, ppid: number, comm: string, threads = 1) => ({ pid, ppid, pgid: 0, comm, threads }); | |
| 42 | const c = census([row(1, 0, "init"), row(10, 1, "bun", 8), row(11, 10, "git"), row(12, 10, "git"), row(13, 12, "sh", 2), row(99, 1, "other")], 10); | |
| 43 | expect(c.processes).toBe(6); | |
| 44 | expect(c.threads).toBe(14); | |
| 45 | expect(c.below).toEqual({ processes: 3, threads: 4, top: [["git", 2], ["sh", 1]] }); | |
| 46 | expect(censusWords(c)).toBe("procs 6, threads 14; under pid: 3 procs, 4 threads (git 2, sh 1)"); | |
| 47 | }); | |
| 48 | ||
| 49 | test("the census is linear on a wide tree", () => { | |
| 50 | const rows = [{ pid: 1, ppid: 0, pgid: 0, comm: "bun" }]; | |
| 51 | for (let i = 0; i < 20_000; i++) rows.push({ pid: 2 + i, ppid: 1, pgid: 0, comm: "git" }); | |
| 52 | const t = performance.now(); | |
| 53 | expect(census(rows, 1).below.processes).toBe(20_000); | |
| 54 | expect(performance.now() - t).toBeLessThan(2_000); // quadratic copying of 20,000 children takes minutes | |
| 55 | }); | |
| 56 | ||
| 57 | test("the watchdog's file is a kept log: capped and rotated", () => { | |
| 58 | const dir = mkdtempSync(join(tmpdir(), "watchdog-")); | |
| 59 | const log = keptLog(dir, { file: WATCHDOG_FILE, maxBytes: 200, keep: 1 }); | |
| 60 | for (let i = 0; i < 50; i++) { | |
| 61 | log.add(`line ${i} ${"x".repeat(40)}`); | |
| 62 | log.flush(); | |
| 63 | } | |
| 64 | log.stop(); | |
| 65 | expect(existsSync(join(dir, `${WATCHDOG_FILE}.1`))).toBe(true); | |
| 66 | expect(existsSync(join(dir, `${WATCHDOG_FILE}.2`))).toBe(false); | |
| 67 | expect(readFileSync(join(dir, WATCHDOG_FILE), "utf8").length).toBeLessThanOrEqual(400); | |
| 68 | }); | |
| 69 | ||
| 70 | test("a thread that is blocked outright gets a line before it ends", async () => { | |
| 71 | const dir = mkdtempSync(join(tmpdir(), "watchdog-")); | |
| 72 | const file = join(dir, WATCHDOG_FILE); | |
| 73 | const dog = startLoopWatchdog({ afterMs: 500, repeatMs: 60_000, beatMs: 50, dataDir: dir }); | |
| 74 | await sleep(1_000); // the worker is up and beating is seen | |
| 75 | // Nothing on this thread can run a timer or write now: only the worker can say anything. | |
| 76 | Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 4_000); | |
| 77 | const unblocked = Date.now(); | |
| 78 | expect(await waitFor(() => existsSync(file) && /still blocked/.test(readFileSync(file, "utf8")), { every: 100, within: 10_000 })).toBe(true); | |
| 79 | const line = readFileSync(file, "utf8").split("\n").find((l) => /still blocked/.test(l))!; | |
| 80 | // It was written while this thread was blocked, not after: the stamp is before the unblock. | |
| 81 | expect(Date.parse(line.slice(0, 24))).toBeLessThan(unblocked); | |
| 82 | expect(line).toMatch(/; load 1m \d+\.\d/); | |
| 83 | if (existsSync("/proc/self/stat")) expect(line).toMatch(/; procs \d+, threads \d+; under pid: \d+ procs/); | |
| 84 | expect(await waitFor(() => /answered again/.test(readFileSync(file, "utf8")), { every: 100, within: 10_000 })).toBe(true); | |
| 85 | dog.stop(); | |
| 86 | }, 30_000); |
test/timers-named.test.ts +6
| @@ -69,6 +69,12 @@ const ALLOWED: readonly Allowed[] = [ | ||
| 69 | 69 | ...allow("setInterval", "the cell supervisor's own tick: a separate process with no job ring, its one timer", [ |
| 70 | 70 | ["src/spawn/supervisor.ts", "() => { capFile(f.log"], |
| 71 | 71 | ]), |
| 72 | ...allow("setInterval", "the loop watchdog's own thread (#17708): a worker with no job ring, whose one timer reads a heartbeat", [ | |
| 73 | ["src/kernel/loop_watchdog_worker.ts", "() => { const now = Date.now();"], | |
| 74 | ]), | |
| 75 | ...allow("setInterval", "the loop's heartbeat (#17708): one atomic store four times a second; a span each would fill the 256-span ring in a minute", [ | |
| 76 | ["src/kernel/loop_watchdog.ts", "() => Atomics.store(beat, 0, BigInt(Date.now()))"], | |
| 77 | ]), | |
| 72 | 78 | ...allow("setInterval", "an adopted cell's identity check: one kill(0) and a pid-file read a second per cell, ended when the cell is gone", [ |
| 73 | 79 | ["src/spawn/cell.ts", "() => { if (isCell()) return;"], |
| 74 | 80 | ]), |
new above
offline
[...(kids.get(r.ppid) ?? []), r]copies the list per row: quadratic on a thousand-process tree. Push to the existing array.