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

opened this

Merged 19h 40m ago, live in production

sql-tally-by-statement → main 0 commits 2 threads · 2 unresolved

  • Merged. sql-tally-by-statement was merged into main as 0b3603a.

Review

Sign in to review this change.
2 files changed +107 −21
src/kernel/slow_sql.ts +32 −18
@@ -10,8 +10,9 @@
1010 * log redacts anything credential-shaped besides. At most `PER_MINUTE`
1111 * lines a minute, so a lock held for minutes is a few lines, not thousands.
1212 *
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.
1516 */
1617
1718 import type { Database } from "bun:sqlite";
@@ -21,6 +22,12 @@ import type { Log } from "./log.ts";
2122 export const SLOW_SQL_MS = 200;
2223 const PER_MINUTE = 10;
2324 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;
2431 const METHODS = ["run", "get", "all", "values"] as const;
2532
2633 /** Transaction factories this module has already wrapped. */
@@ -47,26 +54,33 @@ function callers(depth = 6): string {
4754 }
4855
4956 /**
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:
outdated

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.

61 * taken on every one, it cost 54-112 us a statement where the statement itself cost 2 (#17629).
5362 */
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 };
5667 add(sql: unknown, ms: number): void {
57 const key = callers(3);
68 const key = String(sql);
5869 const t = this.by.get(key);
outdated

The 'slowest run replaces the caller' branch has no test that would fail without it. Add one with two call sites and a controlled clock.

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];
6176 }
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. */
6378 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)` });
6881 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);
7084 }
7185 }
7286
@@ -86,14 +100,14 @@ export function timeStatements(
86100 if (++told > PER_MINUTE) return;
87101 log.warn("slow statement held the thread", { ms: Math.round(ms), sql: sqlHead(sql), stack: callers() });
88102 };
89 const tally = new CallerTally();
103 const tally = new StatementTally();
90104 let tallied = Math.floor(wall() / 60_000);
91105 const count = (sql: unknown, ms: number): void => {
92106 const at = Math.floor(wall() / 60_000);
93107 if (at !== tallied) {
94108 tallied = at;
95109 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) });
97111 }
98112 tally.add(sql, ms);
99113 };
test/loop-stall.test.ts +75 −3
@@ -12,7 +12,7 @@ import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { createApp } from "../src/app.ts";
1414 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";
1616 import { holdLease } from "../src/runs/lease.ts";
1717 import { PEER_FRESH_MS, peerRuns, waitForPeer } from "../src/runs/peer.ts";
1818 import type { LogFields } from "../src/kernel/log.ts";
@@ -100,7 +100,7 @@ describe("slow statements", () => {
100100 db.close();
101101 });
102102
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", () => {
104104 const db = new Database(":memory:");
105105 const { lines, log } = recorder();
106106 let wall = 60_000 * 100;
@@ -111,7 +111,7 @@ describe("slow statements", () => {
111111 expect(lines).toHaveLength(0);
112112 wall += 60_000;
113113 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");
115115 expect(told).toHaveLength(1);
116116 const top = JSON.parse(String(told[0]!.fields?.top)) as { caller: string; n: number; sql: string }[];
117117 expect(top.length).toBeLessThanOrEqual(10);
@@ -121,6 +121,78 @@ describe("slow statements", () => {
121121 db.close();
122122 });
123123
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
124196 test("a lock held by another process is the slow statement, named", async () => {
125197 const dir = await mkdtemp(join(tmpdir(), "forge-slowsql-"));
126198 const file = join(dir, "db.sqlite");

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

Keyboard shortcuts

Docs