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

Count the cold home's work instead of timing it, so production's-size budgets are exact on any machine #17220

opened this in answer to

Merged 35h 23m ago, live in production

torque/forge:torque/17101-count-the-cold-home-s-work-instead-of-ti → main 0 commits fork

  • Merged. torque/17101-count-the-cold-home-s-work-instead-of-ti was merged into main as 15d3197.

Review

Sign in to review this change.
3 files changed +129 −66
src/kernel/list_texts.ts +3
@@ -23,6 +23,7 @@
2323 */
2424
2525 import type { Database, Statement } from "bun:sqlite";
26 import { statementLogger } from "./statement_log.ts";
2627
2728 /** The list texts one connection keeps prepared. */
2829 export const LIST_TEXTS_KEPT = 64;
@@ -99,9 +100,11 @@ export function keepFixedTexts(db: Database): Database {
99100 if (retiring.length > RETIRING_KEPT) retiring.shift()!.finalize();
100101 return [made, 0];
101102 };
103 const logged = statementLogger();
102104 handle.query = (sql: string): Statement => {
103105 // Not a text: Bun's own query says what is wrong with it.
104106 if (typeof sql !== "string") return cached(sql);
107 logged?.(sql);
105108 if (isListText(sql)) {
106109 const [made, added] = keep(lists, sql, LIST_TEXTS_KEPT);
107110 keptHere += added;
src/kernel/statement_log.ts added +21
@@ -0,0 +1,21 @@
1 /**
2 * A log of the statements a process asks for, so a test can count a page's work (#17101).
3 *
4 * A budget in CPU time moved with the machine: the same page read 12 to 22 reference units on a
5 * Mac and 34 to 39 on a many-core runner. The statements a page asks for do not move. But the
6 * lanes, pipeline and pages workers open connections of their own, so a counter wrapped round the
7 * main handle misses most of a cold page. Every wrapped connection (`keepFixedTexts`) appends the
8 * text of each statement it is asked for, one JSON string a line, to the file named by
9 * `FORGE_STATEMENT_LOG`, read once when the connection is wrapped; a worker inherits the variable.
10 * Unset (production), nothing is read or written. The test owns the file; it is never under the
11 * app's data.
12 */
13
14 import { appendFileSync } from "node:fs";
15
16 /** The function that records one statement text on a connection made now, or none. */
17 export function statementLogger(): ((sql: string) => void) | undefined {
18 const path = process.env["FORGE_STATEMENT_LOG"];
19 if (path === undefined || path === "") return undefined;
20 return (sql) => appendFileSync(path, `${JSON.stringify(sql)}\n`);
21 }
test/observability-budget.test.ts +105 −66
@@ -2,15 +2,17 @@
22 * `/boards`, `/map` and home on a forge sized like production's (#3693):
33 * a month of 100,000 runs, 1,500 merged pulls, 400 open asks and 2,266
44 * edges between them. The owner saw /boards take 8–10 s, a cold /map 34.7 s
5 * and home 9.2 s. Each budget is a multiple of one full pass over the run
6 * table, timed in the same run, so a loaded machine slows both sides and
7 * the wall clock is never the judge (#3069). Before the fix each page cost
8 * hundreds of those passes. Both sides are process CPU time (the server and its workers run in
9 * this process), so a busy runner's waiting counts on neither side.
5 * and home 9.2 s. Each budget counts the page's own work (#17101), not its time: the statements
6 * it asks for, in the main thread and in the workers that read for it, and the full passes over the
7 * run table those statements make (by `EXPLAIN QUERY PLAN`, since a `COUNT(*)` over 100,000 runs
8 * returns one row). The ceilings are the same on every machine; a timing against a reference pass
9 * moved with the core count (#3069, #16696). Before the fix each page cost hundreds of passes.
1010 */
1111 import { forgetHome } from "../src/web/studio/home_last.ts";
1212 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1313 import { rm } from "node:fs/promises";
14 import { readFileSync, writeFileSync } from "node:fs";
15 import { join } from "node:path";
1416 import { tmpdir } from "node:os";
1517 import { createApp, type App } from "../src/app.ts";
1618 import { createSession } from "../src/core/sessions.ts";
@@ -23,11 +25,15 @@ import { seedFlowFixture } from "./helpers/flow-fixture.ts";
2325 import { SCRATCH_ROOT, scratchDir } from "./helpers/scratch.ts";
2426
2527 let dataDir = "";
28 let logPath = "";
2629 let app: App, servers: Servers, cookie = "";
2730
2831 beforeAll(async () => {
2932 // ~49 MB of database: on the checkout's disk, not the cell's shared /tmp.
3033 dataDir = scratchDir("forge-obs-budget-");
34 logPath = join(dataDir, "statements.log");
35 writeFileSync(logPath, "");
36 process.env["FORGE_STATEMENT_LOG"] = logPath; // env-restored: afterAll
3137 app = createApp({ dataDir, port: 0 });
3238 servers = await serve(app);
3339 const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
@@ -38,55 +44,93 @@ beforeAll(async () => {
3844
3945 afterAll(async () => {
4046 // A setup that failed part way leaves these unset: say only what it said.
47 delete process.env["FORGE_STATEMENT_LOG"]; // env-restored: here
4148 servers?.stop();
4249 app?.close();
4350 if (dataDir !== "") await rm(dataDir, { recursive: true, force: true });
4451 });
4552
46 /** The process's CPU time, in ms: the server, its workers and this test all run in it. */
47 const cpuMs = (): number => {
48 const used = process.cpuUsage();
49 return (used.user + used.system) / 1000;
50 };
51
52 /**
53 * One full pass over every run, read into this process as the pages read them (rows made into
54 * objects), in CPU ms: the unit the budgets are counted in. A pass counted inside SQLite alone made
55 * no objects, so it paid none of the collector's threads, which a page does and which cost more
56 * CPU on a runner with many cores: the cold home read 34 to 39 such units there and 12 on the Mac.
57 */
58 function scan(): number {
59 const started = cpuMs();
60 const rows = app.db.query<{ id: string; branch: string; created_at: string }, []>("SELECT id, branch, created_at FROM run").all();
61 if (rows.length === 0) throw new Error("the fixture has no runs");
62 return cpuMs() - started;
53 /** The statement texts in the log at `path`, one per statement asked for, in order. */
54 function readStatementLog(path: string): string[] {
55 const text = readFileSync(path, "utf8");
56 return text === "" ? [] : text.trimEnd().split("\n").map((line) => JSON.parse(line) as string);
6357 }
6458
65 function baseline(): number {
66 const spent = [scan(), scan(), scan()].sort((a, b) => a - b);
67 return spent[1]!;
68 }
69
70 /**
71 * `path` timed, with the unit measured on both sides of it and the larger kept. CPU time still
72 * stretches a little on a contended machine (caches, cores); the unit read after the page shares
73 * whatever contention the page met. The wall clock read a cold home at 773 ms against a 739 ms
74 * budget on a busy runner (#16696); in CPU, waiting counts on neither side.
75 */
76 async function timedAgainstUnit(path: string): Promise<{ ms: number; status: number; timing: string; unit: number }> {
77 const before = baseline();
78 const res = await get(path);
79 return { ...res, unit: Math.max(before, baseline()) };
80 }
81
82 /** `path` fetched; `ms` is the CPU the process spent answering it (its workers' included). */
83 async function get(path: string): Promise<{ ms: number; status: number; timing: string }> {
84 const started = cpuMs();
59 /** `path` fetched, and what it did: the statements it asked for and how long the server took. */
60 async function get(path: string): Promise<{ status: number; timing: string; work: Work }> {
61 writeFileSync(logPath, "");
8562 const res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
8663 await res.arrayBuffer();
87 return { ms: cpuMs() - started, status: res.status, timing: res.headers.get("server-timing") ?? "" };
64 return { status: res.status, timing: res.headers.get("server-timing") ?? "", work: workOf(readStatementLog(logPath)) };
8865 }
8966
67 /**
68 * What a page's statements stepped through: how many ran, and how many of them walk the run table.
69 */
70 interface Work {
71 statements: number;
72 /** Full passes over `run`: each statement's plan lines that scan it, once per time it ran. */
73 runPasses: number;
74 /** The distinct texts that scan it, for the failure message. */
75 scanning: string[];
76 }
77
78 /**
79 * The run table's name in `sql`, with its aliases: `FROM run r`, `JOIN run AS x`. A plan line names
80 * the alias, not the table.
81 */
82 function runNames(sql: string): Set<string> {
83 const names = new Set(["run"]);
84 const keyword = new Set(["where", "on", "join", "left", "inner", "cross", "group", "order", "limit", "using", "union", "as", "set", "natural"]);
85 for (const m of sql.matchAll(/\b(?:FROM|JOIN)\s+run\b(?:\s+(?:AS\s+)?(\w+))?/gi)) {
86 const alias = m[1]?.toLowerCase();
87 if (alias !== undefined && !keyword.has(alias)) names.add(alias);
88 }
89 return names;
90 }
91
92 /**
93 * A page's work from the statements it asked for. A `COUNT(*)` or `SUM` over 100,000 runs returns
94 * one row but steps through all of them, so rows returned say nothing: the plan says what a
95 * statement steps through (`EXPLAIN QUERY PLAN`, https://www.sqlite.org/eqp.html). A `SCAN` of the
96 * run table, by any index or none, is one full pass; a `SEARCH` is a probe and is not.
97 */
98 function workOf(texts: string[]): Work {
99 const passesOf = new Map<string, number>();
100 let runPasses = 0;
101 const scanning = new Set<string>();
102 for (const sql of texts) {
103 let passes = passesOf.get(sql);
104 if (passes === undefined) {
105 const names = runNames(sql);
106 const marks = app.db.prepare(sql).paramsCount;
107 const plan = app.db
108 .query<{ detail: string }, null[]>(`EXPLAIN QUERY PLAN ${sql}`)
109 .all(...Array.from({ length: marks }, () => null));
110 passes = plan.filter((r) => {
111 const m = /^SCAN (\w+)/.exec(r.detail);
112 return m !== null && names.has(m[1]!.toLowerCase());
113 }).length;
114 passesOf.set(sql, passes);
115 }
116 runPasses += passes;
117 if (passes > 0) scanning.add(sql.replace(/\s+/g, " ").slice(0, 160));
118 }
119 return { statements: texts.length, runPasses, scanning: [...scanning] };
120 }
121
122 /**
123 * The ceilings are counts, the same on every machine: what the page asks for does not depend on
124 * how fast the machine answers. They sit above what each page asks for now (boards 56, map 32,
125 * home 177 statements) by room for the process's own background reads, and a pass over `run`
126 * is a pass whatever the machine.
127 */
128 function withinWork(work: Work, ceiling: { statements: number; runPasses: number }): void {
129 if (work.runPasses > ceiling.runPasses) throw new Error(`${work.runPasses} passes over the runs, at most ${ceiling.runPasses}: ${work.scanning.join(" | ")}`);
130 expect(work.statements).toBeLessThanOrEqual(ceiling.statements);
131 }
132
133
90134 const names = (timing: string): string[] => timing.split(", ").map((p) => p.split(";")[0]!);
91135
92136 describe("on production's size", () => {
@@ -103,42 +147,37 @@ describe("on production's size", () => {
103147
104148 test("/boards answers within a few passes over the runs, and names its phases", async () => {
105149 await get("/boards");
106 const res = await timedAgainstUnit("/boards");
150 const res = await get("/boards");
107151 expect(res.status).toBe(200);
108152 for (const n of ["session", "picture", "flow", "render"]) expect(names(res.timing)).toContain(n);
109 expect(res.ms).toBeLessThan(30 * res.unit);
153 withinWork(res.work, { statements: 80, runPasses: 1 });
110154 });
111155
112156 test("a cold /map answers within a few passes over the runs", async () => {
113157 await get("/map");
114158 clearMapCache();
115 const res = await timedAgainstUnit("/map");
159 const res = await get("/map");
116160 expect(res.status).toBe(200);
117161 expect(names(res.timing)).toContain("layout");
118 expect(res.ms).toBeLessThan(60 * res.unit);
162 withinWork(res.work, { statements: 50, runPasses: 0 });
119163 });
120164
121165 test("a cold home answers from the picture, within a few passes over the runs", async () => {
122166 await get("/");
123 // what this budget measures is the cold path, a miss on every one of them and on the regions
124 // home remembers (#7660). CPU is shared with whatever else the process does (a worker finishing
125 // an earlier page, the collector), and one stray burst inside the window failed this twice in a
126 // week (#17033). A real regression is slow on every cold try, a stray burst on one: the budget
127 // is met when the best of three cold tries meets it.
128 let best: Awaited<ReturnType<typeof timedAgainstUnit>> | undefined;
129 for (let attempt = 0; attempt < 3; attempt++) {
130 app.db.run("UPDATE repo SET description = description || ''");
131 for (const cache of [kpiCache(app.db), panelCache(app.db)]) cache.clear();
132 forgetHome(app.db);
133 const res = await timedAgainstUnit("/");
134 expect(res.status).toBe(200);
135 // the home reads no table itself: the lanes' worker does, and the page is drawn from its
136 // picture
137 expect(names(res.timing)).toContain("picture");
138 if (best === undefined || res.ms / res.unit < best.ms / best.unit) best = res;
139 if (res.ms < 30 * res.unit) break;
140 }
141 expect(best!.ms).toBeLessThan(30 * best!.unit);
167 app.db.run("UPDATE repo SET description = description || ''");
168 for (const cache of [kpiCache(app.db), panelCache(app.db)]) cache.clear();
169 forgetHome(app.db);
170 const res = await get("/");
171 expect(res.status).toBe(200);
172 expect(names(res.timing)).toContain("picture");
173 withinWork(res.work, { statements: 240, runPasses: 0 });
174 });
175
176 test("the count sees a scan the rows returned would hide, and not a probe", () => {
177 const scan = workOf(["SELECT COUNT(*) FROM run", "SELECT SUM(id) FROM run r WHERE r.branch = 'x'"]);
178 expect(scan.runPasses).toBe(2);
179 expect(workOf(["SELECT COUNT(*) FROM run WHERE id = ?1"]).runPasses).toBe(0);
180 expect(workOf(["SELECT 1", "SELECT 1"]).statements).toBe(2);
142181 });
143182 });
144183

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

Keyboard shortcuts

Docs