Public: anyone can read this; the crew can change it.
The minute's statement tally takes a caller's stack only on a statement's first and slowest runs: 1 us of overhead a statement, not 12-15 #17668
Merged 19h 40m ago, live in production
sql-tally-by-statement → main 0 commits 2 threads · 2 unresolved
2 files
changed +107
−21
src/kernel/slow_sql.ts +32 −18
| @@ -10,8 +10,9 @@ | ||
| 10 | 10 | * log redacts anything credential-shaped besides. At most `PER_MINUTE` |
| 11 | 11 | * lines a minute, so a lock held for minutes is a few lines, not thousands. |
| 12 | 12 | * |
| 13 | * Besides the slow ones, once a minute one line counts every statement per | |
| 14 | * caller (`CallerTally`): where the thread's time goes, under any threshold. | |
| 13 | * Besides the slow ones, once a minute one line counts every statement by its SQL | |
| 14 | * (`StatementTally`), each with the caller of its slowest run: where the thread's time goes, | |
| 15 | * under any threshold. | |
| 15 | 16 | */ |
| 16 | 17 | |
| 17 | 18 | import type { Database } from "bun:sqlite"; |
| @@ -21,6 +22,12 @@ import type { Log } from "./log.ts"; | ||
| 21 | 22 | export const SLOW_SQL_MS = 200; |
| 22 | 23 | const PER_MINUTE = 10; |
| 23 | 24 | const TOP_CALLERS = 10; |
| 25 | /** | |
| 26 | * Distinct statements kept a minute (#17668). The key is the SQL itself, and SQL built with values | |
| 27 | * inlined (an IN list, a literal) is a new key each time: past this many, the rest of the minute | |
| 28 | * is one row, so the map never outgrows it on the serving thread. | |
| 29 | */ | |
| 30 | export const MAX_STATEMENTS = 500; | |
| 24 | 31 | const METHODS = ["run", "get", "all", "values"] as const; |
| 25 | 32 | |
| 26 | 33 | /** Transaction factories this module has already wrapped. */ |
| @@ -47,26 +54,33 @@ function callers(depth = 6): string { | ||
| 47 | 54 | } |
| 48 | 55 | |
| 49 | 56 | /** |
| 50 | * Every statement counted under the code that ran it (#8103): the slow ones | |
| 51 | * are a small part of a busy thread, so a minute's count and total ms per | |
| 52 | * caller, the top ten, says where the time goes without a threshold. | |
| 57 | * Every statement counted by its SQL (#8103): the slow ones are a small part of a busy thread, so | |
| 58 | * a minute's count and total ms per statement, the top ten, says where the time goes without a | |
| 59 | * threshold. Each names the caller of its slowest run that minute. The stack is taken only then, | |
| 60 | * on a statement's first run of the minute and when a run is its slowest yet, not on every run: | |
| 61 | * taken on every one, it cost 54-112 us a statement where the statement itself cost 2 (#17629). | |
| 53 | 62 | */ |
| 54 | class CallerTally { | |
| 55 | private readonly by = new Map<string, { n: number; ms: number; sql: string }>(); | |
| 63 | class StatementTally { | |
| 64 | private readonly by = new Map<string, { n: number; ms: number; slowest: number; caller: string }>(); | |
| 65 | /** Statements past `MAX_STATEMENTS` distinct ones this minute: one row, never another key. */ | |
| 66 | private other = { n: 0, ms: 0 }; | |
| 56 | 67 | add(sql: unknown, ms: number): void { |
| 57 | const key = callers(3); | |
| 68 | const key = String(sql); | |
| 58 | 69 | const t = this.by.get(key); |
| 59 | if (t) [t.n, t.ms] = [t.n + 1, t.ms + ms]; | |
| 60 | else this.by.set(key, { n: 1, ms, sql: sqlHead(sql) }); | |
| 70 | if (t !== undefined) { | |
| 71 | t.n++; | |
| 72 | t.ms += ms; | |
| 73 | if (ms > t.slowest) [t.slowest, t.caller] = [ms, callers(3)]; | |
| 74 | } else if (this.by.size < MAX_STATEMENTS) this.by.set(key, { n: 1, ms, slowest: ms, caller: callers(3) }); | |
| 75 | else [this.other.n, this.other.ms] = [this.other.n + 1, this.other.ms + ms]; | |
| 61 | 76 | } |
| 62 | /** The heaviest callers by total ms, and forget them. */ | |
| 77 | /** The heaviest statements by total ms, the overflow among them as one row, and forget them. */ | |
| 63 | 78 | take(top = TOP_CALLERS): { caller: string; n: number; ms: number; sql: string }[] { |
| 64 | const rows = [...this.by] | |
| 65 | .map(([caller, t]) => ({ caller, n: t.n, ms: Math.round(t.ms), sql: t.sql })) | |
| 66 | .sort((a, b) => b.ms - a.ms) | |
| 67 | .slice(0, top); | |
| 79 | const rows = [...this.by].map(([sql, t]) => ({ caller: t.caller, n: t.n, ms: Math.round(t.ms), sql: sqlHead(sql) })); | |
| 80 | if (this.other.n > 0) rows.push({ caller: "(not kept)", n: this.other.n, ms: Math.round(this.other.ms), sql: `(statements past the first ${MAX_STATEMENTS} distinct this minute)` }); | |
| 68 | 81 | this.by.clear(); |
| 69 | return rows; | |
| 82 | this.other = { n: 0, ms: 0 }; | |
| 83 | return rows.sort((a, b) => b.ms - a.ms || b.n - a.n).slice(0, top); | |
| 70 | 84 | } |
| 71 | 85 | } |
| 72 | 86 | |
| @@ -86,14 +100,14 @@ export function timeStatements( | ||
| 86 | 100 | if (++told > PER_MINUTE) return; |
| 87 | 101 | log.warn("slow statement held the thread", { ms: Math.round(ms), sql: sqlHead(sql), stack: callers() }); |
| 88 | 102 | }; |
| 89 | const tally = new CallerTally(); | |
| 103 | const tally = new StatementTally(); | |
| 90 | 104 | let tallied = Math.floor(wall() / 60_000); |
| 91 | 105 | const count = (sql: unknown, ms: number): void => { |
| 92 | 106 | const at = Math.floor(wall() / 60_000); |
| 93 | 107 | if (at !== tallied) { |
| 94 | 108 | tallied = at; |
| 95 | 109 | const top = tally.take(); |
| 96 | if (top.length > 0) log.info("statements by caller, last minute", { top: JSON.stringify(top) }); | |
| 110 | if (top.length > 0) log.info("statements by SQL, last minute", { top: JSON.stringify(top) }); | |
| 97 | 111 | } |
| 98 | 112 | tally.add(sql, ms); |
| 99 | 113 | }; |
test/loop-stall.test.ts +75 −3
| @@ -12,7 +12,7 @@ import { tmpdir } from "node:os"; | ||
| 12 | 12 | import { join } from "node:path"; |
| 13 | 13 | import { createApp } from "../src/app.ts"; |
| 14 | 14 | import { watchStalls } from "../src/kernel/loop_lag.ts"; |
| 15 | import { sqlHead, timeStatements } from "../src/kernel/slow_sql.ts"; | |
| 15 | import { MAX_STATEMENTS, sqlHead, timeStatements } from "../src/kernel/slow_sql.ts"; | |
| 16 | 16 | import { holdLease } from "../src/runs/lease.ts"; |
| 17 | 17 | import { PEER_FRESH_MS, peerRuns, waitForPeer } from "../src/runs/peer.ts"; |
| 18 | 18 | import type { LogFields } from "../src/kernel/log.ts"; |
| @@ -100,7 +100,7 @@ describe("slow statements", () => { | ||
| 100 | 100 | db.close(); |
| 101 | 101 | }); |
| 102 | 102 | |
| 103 | test("every statement is counted under its caller, and the top ten are one line a minute", () => { | |
| 103 | test("every statement is counted by its SQL with the caller of its slowest run, and the top ten are one line a minute", () => { | |
| 104 | 104 | const db = new Database(":memory:"); |
| 105 | 105 | const { lines, log } = recorder(); |
| 106 | 106 | let wall = 60_000 * 100; |
| @@ -111,7 +111,7 @@ describe("slow statements", () => { | ||
| 111 | 111 | expect(lines).toHaveLength(0); |
| 112 | 112 | wall += 60_000; |
| 113 | 113 | db.query("SELECT x FROM t").all(); |
| 114 | const told = lines.filter((l) => l.message === "statements by caller, last minute"); | |
| 114 | const told = lines.filter((l) => l.message === "statements by SQL, last minute"); | |
| 115 | 115 | expect(told).toHaveLength(1); |
| 116 | 116 | const top = JSON.parse(String(told[0]!.fields?.top)) as { caller: string; n: number; sql: string }[]; |
| 117 | 117 | expect(top.length).toBeLessThanOrEqual(10); |
| @@ -121,6 +121,78 @@ describe("slow statements", () => { | ||
| 121 | 121 | db.close(); |
| 122 | 122 | }); |
| 123 | 123 | |
| 124 | const tallied = (lines: { message: string; fields?: Record<string, unknown> }[]) => | |
| 125 | JSON.parse(String(lines.filter((l) => l.message === "statements by SQL, last minute").at(-1)!.fields?.top)) as { caller: string; n: number; ms: number; sql: string }[]; | |
| 126 | ||
| 127 | test("the caller named is the slowest run's, and the stack is taken on a first or a slower run only (#17668)", () => { | |
| 128 | const db = new Database(":memory:"); | |
| 129 | const { lines, log } = recorder(); | |
| 130 | let wall = 60_000 * 200; | |
| 131 | // Each statement reads the clock twice: 0 as it starts, `lasts` as it ends. | |
| 132 | let lasts = 0; | |
| 133 | let ending = false; | |
| 134 | timeStatements(db, log, 10_000, () => ((ending = !ending) ? 0 : lasts), () => wall); | |
| 135 | db.run("CREATE TABLE t (x INTEGER)"); | |
| 136 | const sql = "SELECT x FROM t WHERE x = ?1"; | |
| 137 | const run = () => db.query(sql).get(1); | |
| 138 | // The line a call is made on, as the stack names it: each site below calls on its own line. | |
| 139 | const lineHere = (): number => Number(/:(\d+):\d+\)?$/.exec(new Error().stack!.split("\n")[2]!.trim())![1]); | |
| 140 | const minute = () => { | |
| 141 | wall += 60_000; | |
| 142 | db.query("SELECT 1").get(); | |
| 143 | return tallied(lines).find((r) => r.sql === sql)!; | |
| 144 | }; | |
| 145 | // A slower later run from another site: it is the one named. | |
| 146 | lasts = 5; | |
| 147 | const a = lineHere(); run(); | |
| 148 | lasts = 9; | |
| 149 | const b = lineHere(); run(); | |
| 150 | let row = minute(); | |
| 151 | expect(row.n).toBe(2); | |
| 152 | expect(row.caller).toContain(`:${b}:`); | |
| 153 | expect(row.caller).not.toContain(`:${a}:`); | |
| 154 | // A faster later run keeps the first. | |
| 155 | lasts = 9; | |
| 156 | const c = lineHere(); run(); | |
| 157 | lasts = 5; | |
| 158 | const d = lineHere(); run(); | |
| 159 | row = minute(); | |
| 160 | expect(row.caller).toContain(`:${c}:`); | |
| 161 | expect(row.caller).not.toContain(`:${d}:`); | |
| 162 | // A hundred runs no slower than the first take no stack: `callers` sets the trace limit twice. | |
| 163 | let sets = 0; | |
| 164 | const limit = Error.stackTraceLimit; | |
| 165 | const own = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); | |
| 166 | let held = limit; | |
| 167 | Object.defineProperty(Error, "stackTraceLimit", { configurable: true, get: () => held, set: (v: number) => void ((held = v), sets++) }); | |
| 168 | try { | |
| 169 | lasts = 3; | |
| 170 | for (let i = 0; i < 100; i++) run(); | |
| 171 | } finally { | |
| 172 | if (own) Object.defineProperty(Error, "stackTraceLimit", own); | |
| 173 | Error.stackTraceLimit = limit; | |
| 174 | } | |
| 175 | // The first run of the minute takes one: two sets. None of the other 99 does. | |
| 176 | expect(sets).toBe(2); | |
| 177 | db.close(); | |
| 178 | }); | |
| 179 | ||
| 180 | test("ten thousand distinct inlined statements keep the tally to its bound, the rest one row (#17668)", () => { | |
| 181 | const db = new Database(":memory:"); | |
| 182 | const { lines, log } = recorder(); | |
| 183 | let wall = 60_000 * 300; | |
| 184 | timeStatements(db, log, 10_000, () => 0, () => wall); | |
| 185 | for (let i = 0; i < 10_000; i++) db.query(`SELECT ${i} AS v`).get(); | |
| 186 | wall += 60_000; | |
| 187 | db.query("SELECT 1").get(); | |
| 188 | const top = tallied(lines); | |
| 189 | expect(top.length).toBeLessThanOrEqual(10); | |
| 190 | const rest = top.find((r) => r.caller === "(not kept)"); | |
| 191 | expect(rest?.n).toBe(10_000 - MAX_STATEMENTS); | |
| 192 | expect(rest?.sql).toContain(`${MAX_STATEMENTS} distinct`); | |
| 193 | db.close(); | |
| 194 | }); | |
| 195 | ||
| 124 | 196 | test("a lock held by another process is the slow statement, named", async () => { |
| 125 | 197 | const dir = await mkdtemp(join(tmpdir(), "forge-slowsql-")); |
| 126 | 198 | const file = join(dir, "db.sqlite"); |
new above
offline
Keyed by the full SQL string: with inlined values the key set is unbounded within a minute. Bound it by keying on
sqlHead(sql)or by capping distinct keys per minute.