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
Merged 35h 23m ago, live in production
torque/forge:torque/17101-count-the-cold-home-s-work-instead-of-ti → main 0 commits fork
3 files
changed +129
−66
src/kernel/list_texts.ts +3
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | */ |
| 24 | 24 | |
| 25 | 25 | import type { Database, Statement } from "bun:sqlite"; |
| 26 | import { statementLogger } from "./statement_log.ts"; | |
| 26 | 27 | |
| 27 | 28 | /** The list texts one connection keeps prepared. */ |
| 28 | 29 | export const LIST_TEXTS_KEPT = 64; |
| @@ -99,9 +100,11 @@ export function keepFixedTexts(db: Database): Database { | ||
| 99 | 100 | if (retiring.length > RETIRING_KEPT) retiring.shift()!.finalize(); |
| 100 | 101 | return [made, 0]; |
| 101 | 102 | }; |
| 103 | const logged = statementLogger(); | |
| 102 | 104 | handle.query = (sql: string): Statement => { |
| 103 | 105 | // Not a text: Bun's own query says what is wrong with it. |
| 104 | 106 | if (typeof sql !== "string") return cached(sql); |
| 107 | logged?.(sql); | |
| 105 | 108 | if (isListText(sql)) { |
| 106 | 109 | const [made, added] = keep(lists, sql, LIST_TEXTS_KEPT); |
| 107 | 110 | 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 @@ | ||
| 2 | 2 | * `/boards`, `/map` and home on a forge sized like production's (#3693): |
| 3 | 3 | * a month of 100,000 runs, 1,500 merged pulls, 400 open asks and 2,266 |
| 4 | 4 | * 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. | |
| 10 | 10 | */ |
| 11 | 11 | import { forgetHome } from "../src/web/studio/home_last.ts"; |
| 12 | 12 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 13 | 13 | import { rm } from "node:fs/promises"; |
| 14 | import { readFileSync, writeFileSync } from "node:fs"; | |
| 15 | import { join } from "node:path"; | |
| 14 | 16 | import { tmpdir } from "node:os"; |
| 15 | 17 | import { createApp, type App } from "../src/app.ts"; |
| 16 | 18 | import { createSession } from "../src/core/sessions.ts"; |
| @@ -23,11 +25,15 @@ import { seedFlowFixture } from "./helpers/flow-fixture.ts"; | ||
| 23 | 25 | import { SCRATCH_ROOT, scratchDir } from "./helpers/scratch.ts"; |
| 24 | 26 | |
| 25 | 27 | let dataDir = ""; |
| 28 | let logPath = ""; | |
| 26 | 29 | let app: App, servers: Servers, cookie = ""; |
| 27 | 30 | |
| 28 | 31 | beforeAll(async () => { |
| 29 | 32 | // ~49 MB of database: on the checkout's disk, not the cell's shared /tmp. |
| 30 | 33 | dataDir = scratchDir("forge-obs-budget-"); |
| 34 | logPath = join(dataDir, "statements.log"); | |
| 35 | writeFileSync(logPath, ""); | |
| 36 | process.env["FORGE_STATEMENT_LOG"] = logPath; // env-restored: afterAll | |
| 31 | 37 | app = createApp({ dataDir, port: 0 }); |
| 32 | 38 | servers = await serve(app); |
| 33 | 39 | const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); |
| @@ -38,55 +44,93 @@ beforeAll(async () => { | ||
| 38 | 44 | |
| 39 | 45 | afterAll(async () => { |
| 40 | 46 | // A setup that failed part way leaves these unset: say only what it said. |
| 47 | delete process.env["FORGE_STATEMENT_LOG"]; // env-restored: here | |
| 41 | 48 | servers?.stop(); |
| 42 | 49 | app?.close(); |
| 43 | 50 | if (dataDir !== "") await rm(dataDir, { recursive: true, force: true }); |
| 44 | 51 | }); |
| 45 | 52 | |
| 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); | |
| 63 | 57 | } |
| 64 | 58 | |
| 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, ""); | |
| 85 | 62 | const res = await fetch(`${servers.url}${path}`, { headers: { cookie } }); |
| 86 | 63 | 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)) }; | |
| 88 | 65 | } |
| 89 | 66 | |
| 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 | ||
| 90 | 134 | const names = (timing: string): string[] => timing.split(", ").map((p) => p.split(";")[0]!); |
| 91 | 135 | |
| 92 | 136 | describe("on production's size", () => { |
| @@ -103,42 +147,37 @@ describe("on production's size", () => { | ||
| 103 | 147 | |
| 104 | 148 | test("/boards answers within a few passes over the runs, and names its phases", async () => { |
| 105 | 149 | await get("/boards"); |
| 106 | const res = await timedAgainstUnit("/boards"); | |
| 150 | const res = await get("/boards"); | |
| 107 | 151 | expect(res.status).toBe(200); |
| 108 | 152 | 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 }); | |
| 110 | 154 | }); |
| 111 | 155 | |
| 112 | 156 | test("a cold /map answers within a few passes over the runs", async () => { |
| 113 | 157 | await get("/map"); |
| 114 | 158 | clearMapCache(); |
| 115 | const res = await timedAgainstUnit("/map"); | |
| 159 | const res = await get("/map"); | |
| 116 | 160 | expect(res.status).toBe(200); |
| 117 | 161 | expect(names(res.timing)).toContain("layout"); |
| 118 | expect(res.ms).toBeLessThan(60 * res.unit); | |
| 162 | withinWork(res.work, { statements: 50, runPasses: 0 }); | |
| 119 | 163 | }); |
| 120 | 164 | |
| 121 | 165 | test("a cold home answers from the picture, within a few passes over the runs", async () => { |
| 122 | 166 | 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); | |
| 142 | 181 | }); |
| 143 | 182 | }); |
| 144 | 183 |
new above
offline