Public: anyone can read this; the crew can change it.

A `[loop]` stall line names what the serving thread was doing: the route or duty in flight #17982

opened this

Merged 16h 19m ago, live in production

scout/forge:scout/17974-a-loop-stall-line-names-what-the-serving → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/17974-a-loop-stall-line-names-what-the-serving was merged into main as bb47d9a.

Review

Sign in to review this change.
8 files changed +257 −12
src/http/router.ts +6 −2
@@ -6,6 +6,7 @@
66 */
77
88 import { defect } from "../kernel/error.ts";
9 import { stepId } from "../kernel/loop_step.ts";
910
1011 export type Params = Record<string, string>;
1112
@@ -19,11 +20,14 @@ export interface Match<H> {
1920 params: Params;
2021 /** The pattern string given to `add`, so callers can name the route. */
2122 pattern: string;
23 /** `route METHOD pattern` interned for the loop watchdog (`loop_step.ts`): never the path. */
24 step: number;
2225 }
2326
2427 interface CompiledRoute<H> {
2528 method: string;
2629 pattern: string;
30 step: number;
2731 segments: Segment[];
2832 handler: H;
2933 }
@@ -84,7 +88,7 @@ export class Router<H> {
8488 }
8589
8690 add(method: string, pattern: string, handler: H): this {
87 this.routes_.push({ method, pattern, segments: compile(pattern), handler });
91 this.routes_.push({ method, pattern, step: stepId(`route ${method} ${pattern}`), segments: compile(pattern), handler });
8892 return this;
8993 }
9094
@@ -93,7 +97,7 @@ export class Router<H> {
9397 for (const route of this.routes_) {
9498 if (route.method !== method) continue;
9599 const params = matchSegments(route, parts);
96 if (params) return { handler: route.handler, params, pattern: route.pattern };
100 if (params) return { handler: route.handler, params, pattern: route.pattern, step: route.step };
97101 }
98102 return undefined;
99103 }
src/http/server.ts +6 −3
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { inStep } from "../kernel/loop_step.ts";
89 import { lazyRoutes, loadFamilies } from "./lazy_routes.ts";
910 import { boundedSignal } from "../kernel/fetch_timeout.ts";
1011 import { forgesRoutes } from "./routes/forges.ts";
@@ -1501,8 +1502,10 @@ async function answerRoute(
15011502 // Named for its route before the wait for who is asking (a password hash, a session read), so a
15021503 // stall it waits through is not blamed on a route-less request; the role follows once known.
15031504 noteUsage(request, { pattern: matched.pattern, role: "anon" });
1505 // What the thread is doing, for the loop watchdog's stall line (#17974): the pattern, never the
1506 // path, for the synchronous part of the auth read and of the handler (`loop_step.ts`).
15041507 const authStart = performance.now();
1505 const auth = await resolveAuth(app, request);
1508 const auth = await inStep(matched.step, () => resolveAuth(app, request));
15061509 noteSessionTime(request, performance.now() - authStart);
15071510 if (auth.retryAfter !== undefined) return tooManyAttempts(auth.retryAfter);
15081511 noteUsage(request, { pattern: matched.pattern, role: roleOf(auth) });
@@ -1636,7 +1639,7 @@ async function answerRoute(
16361639 // A page under an archived repository is not indexed (`archived_noindex.ts`).
16371640 const noindex = !isApiPath && routeMethod === "GET" && archivedRepoAt(app.db, matched.params, auth.user, url);
16381641 const invoke = (into: Request): Response | Promise<Response> =>
1639 matched.handler({
1642 inStep(matched.step, () => matched.handler({
16401643 app,
16411644 request: into,
16421645 url,
@@ -1644,7 +1647,7 @@ async function answerRoute(
16441647 auth,
16451648 theme: isThemeName(themeCookie) ? themeCookie : undefined,
16461649 ...(noindex ? { noindex } : {}),
1647 });
1650 }));
16481651
16491652 // A signed-in browser's outbox replays by key too (web/outbox.ts): the
16501653 // key is scoped to the person, like a token's is to the token.
src/kernel/loop_step.ts added +97
@@ -0,0 +1,97 @@
1 /**
2 * What the serving thread is doing now, in one cell the loop watchdog reads from its own thread
3 * (#17974): `route GET /:owner/:repo/info/refs` for a request, `duty <name>` for a background job.
4 *
5 * A step is a name from code (a route pattern, a job's name), never a raw URL or a person's text.
6 * Each name is interned once into a table in shared memory and gets a number; marking a step is
7 * then one `Atomics.exchange` of that number, no allocation on the hot path. The table is
8 * open-addressed by the name's hash, so interning is O(1) and the thread keeps no Map of its own.
9 *
10 * Only what is reliably known is named: a step holds the cell for the synchronous stretch of `fn`
11 * in `inStep` and no longer, so the cell is empty again before the thread can turn to anything
12 * else. An async handler's or duty's continuation after an await is not covered: a stall there
13 * reads with no ` in:` at all, never another request's name.
14 */
15
16 /** Bytes a slot holds: a length byte and the name. A longer name gets no step, not a cut one. */
17 const SLOT = 128;
18 /** Names the table holds (a power of two); 0 is "nothing". */
19 const SLOTS = 4096;
20
21 /** The cell (`[0]`) and the table after it, shared with the watchdog. */
22 const shared = new SharedArrayBuffer(8 + SLOT * SLOTS);
23 const cell = new Int32Array(shared, 0, 1);
24 const table = new Uint8Array(shared, 8);
25
26 /** The memory to hand the watchdog's thread. */
27 export function stepMemory(): SharedArrayBuffer {
28 return shared;
29 }
30
31 /**
32 * The number for step `name`, interned on first sight. 0, which names nothing, when the name is
33 * longer than a slot or the table is full: the longest route is 82 bytes and there are some 1,600
34 * of them, so neither happens to a name from code today.
35 */
36 export function stepId(name: string): number {
37 const n = name.length;
38 if (n === 0 || n >= SLOT) return 0;
39 let h = 0x811c9dc5;
40 for (let i = 0; i < n; i++) h = Math.imul(h ^ byteOf(name, i), 0x01000193);
41 for (let probe = 0; probe < SLOTS; probe++) {
42 const id = (h + probe) & (SLOTS - 1);
43 if (id === 0) continue;
44 const at = id * SLOT;
45 const len = Atomics.load(table, at);
46 if (len === 0) {
47 for (let i = 0; i < n; i++) table[at + 1 + i] = byteOf(name, i);
48 Atomics.store(table, at, n);
49 return id;
50 }
51 if (len === n && sameAt(at, name, n)) return id;
52 }
53 return 0;
54 }
55
56 /** Printable ASCII only: anything else is written `?`. */
57 function byteOf(name: string, i: number): number {
58 const c = name.charCodeAt(i);
59 return c >= 0x20 && c < 0x7f ? c : 0x3f;
60 }
61
62 function sameAt(at: number, name: string, n: number): boolean {
63 for (let i = 0; i < n; i++) if (table[at + 1 + i] !== byteOf(name, i)) return false;
64 return true;
65 }
66
67 /**
68 * Run `fn` as step `id` (0: as nothing new) for its synchronous part, which is what can hold the
69 * thread; the cell goes back to what it held before, by compare-exchange, as `fn` returns or
70 * throws.
71 */
72 export function inStep<T>(id: number, fn: () => T): T {
73 if (id === 0) return fn();
74 const was = Atomics.exchange(cell, 0, id);
75 try {
76 return fn();
77 } finally {
78 Atomics.compareExchange(cell, 0, id, was);
outdated

inStep restores the cell as soon as the sync part returns, so an async handler's continuation is unnamed or blamed on another request. Re-enter the step at resume points, or document and narrow the claim.

79 }
80 }
81
82 /** The step in the cell of `memory` (`stepMemory()`, read from any thread); "" when none. */
83 export function readStep(memory: SharedArrayBuffer): string {
84 const id = Atomics.load(new Int32Array(memory, 0, 1), 0);
85 if (id <= 0 || id >= SLOTS) return "";
86 const names = new Uint8Array(memory, 8);
87 const at = id * SLOT;
88 const len = Atomics.load(names, at);
89 let s = "";
90 for (let i = 0; i < len; i++) s += String.fromCharCode(names[at + 1 + i]!);
91 return s;
92 }
93
94 /** The step as the stall line carries it: ` in: <step>`, or nothing. */
95 export function stepWords(step: string): string {
96 return step === "" ? "" : ` in: ${step}`;
97 }
src/kernel/loop_watchdog.ts +5 −1
@@ -13,10 +13,14 @@
1313 * container, and under the forge by name (`proc_census.ts`), for the load of 318 to 1,629 that
1414 * followed the release: who the forge had started by then.
1515 *
16 * The line also names what the thread was doing (`loop_step.ts`, #17974): ` in: route GET
17 * /:owner/:repo/info/refs` or ` in: duty maintain`, a pattern or a job's name and nothing else.
18 *
1619 * What it decides is `watchStep`, a pure function of the heartbeat's age, tested without a thread.
1720 */
1821
1922 import type { WatchdogStart } from "./loop_watchdog_worker.ts";
23 import { stepMemory } from "./loop_step.ts";
2024
2125 export const WATCHDOG_AFTER_MS = 3_000;
2226 export const WATCHDOG_REPEAT_MS = 15_000;
@@ -99,7 +103,7 @@ export function startLoopWatchdog(o: WatchdogOptions = {}): Watchdog {
99103 Atomics.store(beat, 0, BigInt(Date.now()));
100104 const worker = new Worker(new URL("./loop_watchdog_worker.ts", import.meta.url).href);
101105 worker.unref();
102 worker.postMessage({ sab, afterMs, repeatMs, dataDir: o.dataDir, pid: process.pid } satisfies WatchdogStart);
106 worker.postMessage({ sab, steps: stepMemory(), afterMs, repeatMs, dataDir: o.dataDir, pid: process.pid } satisfies WatchdogStart);
103107 const timer = setInterval(() => Atomics.store(beat, 0, BigInt(Date.now())), beatMs);
104108 timer.unref();
105109 return {
src/kernel/loop_watchdog_worker.ts +5 −2
@@ -7,12 +7,15 @@ import { readFileSync } from "node:fs";
77 import { loadavg } from "node:os";
88 import { processRows } from "./census.ts";
99 import { keptLog } from "../perf/kept_log.ts";
10 import { readStep, stepWords } from "./loop_step.ts";
1011 import { CALM, WATCHDOG_FILE, blockedLine, sitsWords, watchStep } from "./loop_watchdog.ts";
1112 import { census, censusWords } from "./proc_census.ts";
1213
1314 /** What the watchdog is told. */
1415 export interface WatchdogStart {
1516 readonly sab: SharedArrayBuffer;
17 /** The serving thread's step cell (`loop_step.ts`): what it is doing now. */
18 readonly steps: SharedArrayBuffer;
1619 readonly afterMs: number;
1720 readonly repeatMs: number;
1821 readonly dataDir: string | undefined;
@@ -45,7 +48,7 @@ function surroundings(pid: number): string {
4548 }
4649
4750 self.onmessage = (e: MessageEvent<WatchdogStart>) => {
48 const { sab, afterMs, repeatMs, dataDir, pid } = e.data;
51 const { sab, steps, afterMs, repeatMs, dataDir, pid } = e.data;
4952 const beat = new BigInt64Array(sab);
5053 // A kept log of its own: size capped and rotated; flushed at once, for the loop may stay blocked.
5154 const kept = dataDir === undefined ? undefined : keptLog(dataDir, { file: WATCHDOG_FILE });
@@ -59,7 +62,7 @@ self.onmessage = (e: MessageEvent<WatchdogStart>) => {
5962 const now = Date.now();
6063 const step = watchStep(state, now - Number(Atomics.load(beat, 0)), afterMs, repeatMs);
6164 state = step.state;
62 if (step.say === "blocked") write(blockedLine(new Date(now), step.silentMs, false, surroundings(pid)));
65 if (step.say === "blocked") write(blockedLine(new Date(now), step.silentMs, false, stepWords(readStep(steps)) + surroundings(pid)));
6366 else if (step.say === "closing") write(blockedLine(new Date(now), step.silentMs, true));
6467 }, Math.max(250, Math.floor(afterMs / 3)));
6568 };
src/perf/jobs.ts +13 −2
@@ -15,6 +15,7 @@
1515 import { hostOf, noteChildJob } from "./child_time.ts";
1616 import { createTally, type Allocation, type Taken } from "./job_alloc.ts";
1717 import { isFullError } from "../kernel/full_error.ts";
18 import { inStep, stepId } from "../kernel/loop_step.ts";
1819
1920 /** Finished slices kept to match a stall against: a tick a second fills it in about two minutes. */
2021 const KEPT = 256;
@@ -62,6 +63,8 @@ export interface JobWatch {
6263 * settles, and no heap tally sees it (#17083).
6364 */
6465 running(): Running[];
66 /** `duty <name>` interned for the loop watchdog (`loop_step.ts`), once per name on this watch. */
67 stepOf(name: string): number;
6568 }
6669
6770 /** One job name open now: how many of it, and when the oldest began. */
@@ -71,6 +74,7 @@ export function createJobWatch(now: () => number = () => performance.now()): Job
7174 const tally = createTally();
7275 const awaiting = new Map<number, { name: string; start: number }>();
7376 const failed = new Map<string, number>();
77 const steps = new Map<string, number>();
7478 const ring: (JobSpan | undefined)[] = new Array(KEPT);
7579 let next = 0;
7680 let id = 0;
@@ -95,6 +99,11 @@ export function createJobWatch(now: () => number = () => performance.now()): Job
9599 },
96100 failures: () => [...failed].map(([name, n]) => ({ name, n })).sort((a, b) => b.n - a.n),
97101 allocated: () => tally.take(),
102 stepOf(name) {
103 let step = steps.get(name);
104 if (step === undefined) steps.set(name, (step = stepId(`duty ${name}`)));
105 return step;
106 },
98107 running() {
99108 const by = new Map<string, Running>();
100109 for (const r of awaiting.values()) {
@@ -222,10 +231,12 @@ export function jobFailuresOf(app: object): { name: string; n: number }[] {
222231 export const during = <T>(name: string, fn: () => T, owner?: string, app?: object): T => {
223232 const forge = app === undefined ? undefined : (hostOf(app) ?? app);
224233 const watch = forge === undefined ? unowned : jobWatchOf(forge);
225 if (owner === undefined) return watch.during(name, fn);
234 // The stall line names the duty by its name only, not the hosted child it ran for (#17974).
235 const step = watch.stepOf(name);
236 if (owner === undefined) return inStep(step, () => watch.during(name, fn));
226237 const start = performance.now();
227238 try {
228 return watch.during(`${owner}:${name}`, fn);
239 return inStep(step, () => watch.during(`${owner}:${name}`, fn));
229240 } finally {
230241 if (forge !== undefined) noteChildJob(forge, owner, performance.now() - start);
231242 }
test/loop-step-server.test.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * The serving side of the stall line's step (#17974): a request through the forge's own answer is
3 * named for its route while its auth read and handler run on the thread, and leaves nothing behind.
4 */
5 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { buildRouter, forgeHttp, type ForgeHttp } from "../src/http/server.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { readStep, stepMemory } from "../src/kernel/loop_step.ts";
13 import { seedAdmin } from "./helpers/admin.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 let dir = "";
19 let app: App;
20 let http: ForgeHttp;
21 let cookie = "";
22
23 beforeAll(async () => {
24 dir = await mkdtemp(join(tmpdir(), "forge-loop-step-"));
25 app = createApp({ dataDir: dir, port: 0 });
26 http = forgeHttp(app);
27 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
28 if (!admin.ok) throw new Error(admin.error);
29 cookie = `forge_session=${createSession(app.db, admin.value.id).token}`;
30 });
31 afterAll(async () => {
32 http.close();
33 app.close();
34 await rm(dir, { recursive: true, force: true });
35 });
36
37 test("a request is named for its route through its auth read and its handler, and leaves the cell empty", async () => {
38 const pattern = buildRouter().match("GET", "/alice")!.pattern;
39 const seen: string[] = [];
40 const query = app.db.query.bind(app.db);
41 const spy = spyOn(app.db, "query").mockImplementation(((sql: string) => {
42 seen.push(readStep(stepMemory()));
43 return query(sql);
44 }) as typeof app.db.query);
45 try {
46 const res = await http.handle(new Request("http://forge.test/alice?token=s3cret", { headers: { cookie } }));
47 expect(res.status).toBe(200);
48 } finally {
49 spy.mockRestore();
50 }
51 expect(seen).toContain(`route GET ${pattern}`);
52 expect(seen.join("\n")).not.toContain("s3cret");
53 expect(readStep(stepMemory())).toBe("");
54 });
test/loop-watchdog.test.ts +71 −2
@@ -5,6 +5,9 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { parseStat } from "../src/kernel/census.ts";
77 import { CALM, WATCHDOG_FILE, blockedLine, sitsWords, startLoopWatchdog, watchStep } from "../src/kernel/loop_watchdog.ts";
8 import { inStep, readStep, stepId, stepMemory, stepWords } from "../src/kernel/loop_step.ts";
9 import { Router } from "../src/http/router.ts";
10 import { createJobWatch, during } from "../src/perf/jobs.ts";
811 import { census, censusWords } from "../src/kernel/proc_census.ts";
912 import { keptLog } from "../src/perf/kept_log.ts";
1013 import { waitFor } from "./helpers/poll.ts";
@@ -79,17 +82,83 @@ test("a thread that is blocked outright gets a line before it ends", async () =>
7982 const file = join(dir, WATCHDOG_FILE);
8083 const dog = startLoopWatchdog({ afterMs: 500, repeatMs: 60_000, beatMs: 50, dataDir: dir });
8184 await sleep(1_000); // the worker is up and beating is seen
82 // Nothing on this thread can run a timer or write now: only the worker can say anything.
83 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 4_000);
85 // Nothing on this thread can run a timer or write now: only the worker can say anything. It is
86 // blocked inside a duty, which the line names from the worker's side (#17974).
87 during("watchdog-block", () => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 4_000));
8488 const unblocked = Date.now();
8589 expect(await waitFor(() => existsSync(file) && /still blocked/.test(readFileSync(file, "utf8")), { every: 100, within: 10_000 })).toBe(true);
8690 const line = readFileSync(file, "utf8").split("\n").find((l) => /still blocked/.test(l))!;
8791 // It was written while this thread was blocked, not after: the stamp is before the unblock.
8892 expect(Date.parse(line.slice(0, 24))).toBeLessThan(unblocked);
8993 expect(line).toMatch(/; load 1m \d+\.\d/);
94 expect(line).toContain(" in: duty watchdog-block;");
9095 // `Atomics.wait` sleeps: the state says so; the kernel may keep the function's name to itself.
9196 if (existsSync("/proc/self/stat")) expect(line).toMatch(/; main thread S( in \w+)?; load/);
9297 if (existsSync("/proc/self/stat")) expect(line).toMatch(/; procs \d+, threads \d+; under pid: \d+ procs/);
9398 expect(await waitFor(() => /answered again/.test(readFileSync(file, "utf8")), { every: 100, within: 10_000 })).toBe(true);
9499 dog.stop();
95100 }, 30_000);
101
102 // #17974: the stall line names what the thread was doing, by pattern or duty name only.
103 test("with a step the blocked line names it; with none it is unchanged", () => {
104 const at = new Date("2026-12-02T23:10:00.000Z");
105 const plain = blockedLine(at, 1_500, false, "; load 1m 4.0");
106 expect(blockedLine(at, 1_500, false, stepWords(readStep(stepMemory())) + "; load 1m 4.0")).toBe(plain);
107 const line = inStep(stepId("route GET /:owner/:repo/info/refs"), () =>
108 blockedLine(at, 1_500, false, stepWords(readStep(stepMemory())) + "; load 1m 4.0"),
109 );
110 expect(line).toBe(
111 "2026-12-02T23:10:00.000Z WARN [loop] event loop still blocked: no heartbeat for 1.5 s (seen from outside the thread) in: route GET /:owner/:repo/info/refs; load 1m 4.0",
112 );
113 expect(readStep(stepMemory())).toBe("");
114 });
115
116 test("a request's step is its route pattern, never its path, query or a token in it", () => {
117 const router = new Router<string>().add("GET", "/:owner/:repo/info/refs", "refs");
118 const url = new URL("http://x/alice/ghp_abcdef1234567890/info/refs?service=git-upload-pack&token=s3cret");
119 const hit = router.match("GET", url.pathname)!;
120 const seen = inStep(hit.step, () => readStep(stepMemory()));
121 expect(seen).toBe("route GET /:owner/:repo/info/refs");
122 expect(seen).not.toContain("ghp_");
123 expect(seen).not.toContain("s3cret");
124 // The same pattern is one entry, however many routers add it.
125 expect(new Router<string>().add("GET", "/:owner/:repo/info/refs", "again").match("GET", url.pathname)!.step).toBe(hit.step);
126 });
127
128 test("a duty run under `during` is named while it runs and cleared when it ends", () => {
129 expect(during("maintain", () => readStep(stepMemory()))).toBe("duty maintain");
130 expect(readStep(stepMemory())).toBe("");
131 });
132
133 test("a name outside printable ASCII is written with ?; a name too long for a slot is not named", () => {
134 expect(inStep(stepId("duty caf\u00e9\n"), () => readStep(stepMemory()))).toBe("duty caf??");
135 // Never cut: two long names with one prefix stay two names, and one past the slot is none.
136 const a = `duty ${"x".repeat(100)}a`;
137 const b = `duty ${"x".repeat(100)}b`;
138 expect(inStep(stepId(a), () => readStep(stepMemory()))).toBe(a);
139 expect(inStep(stepId(b), () => readStep(stepMemory()))).toBe(b);
140 expect(stepId(`duty ${"x".repeat(300)}`)).toBe(0);
141 expect(inStep(0, () => readStep(stepMemory()))).toBe("");
142 });
143
144 test("an async step is named for its synchronous part only: its continuation is not misnamed", async () => {
145 const seen: string[] = [];
146 const pending = inStep(stepId("route GET /slow"), async () => {
147 seen.push(readStep(stepMemory()));
148 await Promise.resolve();
149 seen.push(readStep(stepMemory()));
150 });
151 // Another request's synchronous part runs while the first awaits; then the first resumes.
152 inStep(stepId("route GET /other"), () => seen.push(readStep(stepMemory())));
153 await pending;
154 expect(seen).toEqual(["route GET /slow", "route GET /other", ""]);
155 expect(readStep(stepMemory())).toBe("");
156 });
157
158 test("a duty is interned once per name on its watch", () => {
159 const watch = createJobWatch();
160 const id = watch.stepOf("maintain");
161 expect(id).toBeGreaterThan(0);
162 expect(watch.stepOf("maintain")).toBe(id);
163 expect(inStep(id, () => readStep(stepMemory()))).toBe("duty maintain");
164 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs