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

Sampler: count sample times before the grouped row count #16716

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

sampler-cap → main 0 commits

  • Merged. sampler-cap was merged into main as f719db4.

Review

Sign in to review this change.
2 files changed +92 −0
src/boards/sampler.ts +17
@@ -165,6 +165,11 @@ export function droppedRows(): number {
165165 * this is the bound for when points come faster than that rule expects.
166166 */
167167 export function capRows(db: Database, cap: number): number {
168 // A source holds at most one row per instant (the key is step, at, target), so while the
169 // table holds no more than `cap` instants no source can be over. Counting instants is a seek
170 // per instant, stopped one past the cap: 20 ms on production, where the count by source below
171 // read all 1.07 M rows of 370 sources for 0.6 to 1.8 s on the serving thread every 5 min.
172 if (instantsUpTo(db, cap + 1) <= cap) return 0;
168173 const over = db.query<{ target: string }, [number]>(
169174 "SELECT target FROM machine_sample WHERE step = 15 GROUP BY target HAVING COUNT(*) > ?1",
170175 ).all(cap);
@@ -181,6 +186,18 @@ export function capRows(db: Database, cap: number): number {
181186 return dropped;
182187 }
183188
189 /** How many distinct 15-s instants the table holds, counting no further than `most`. */
190 function instantsUpTo(db: Database, most: number): number {
191 return db.query<{ n: number }, [number]>(
192 `WITH RECURSIVE instant(at, n) AS (
193 SELECT MAX(at), 1 FROM machine_sample WHERE step = 15
194 UNION ALL
195 SELECT (SELECT MAX(at) FROM machine_sample WHERE step = 15 AND at < instant.at), n + 1
196 FROM instant WHERE instant.at IS NOT NULL AND n < ?1)
197 SELECT COUNT(at) AS n FROM instant`,
198 ).get(most)!.n;
199 }
200
184201 /** `gaps` is what this sampler cannot read, said once at start and kept here for whoever asks. */
185202 export type Sampler = { tick(now?: number): void; stop(): void; gaps: readonly string[] };
186203
test/boards-sampler-cap-instants.test.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * The sampler's cap asks first how many instants the table holds: a source has at most one row
3 * per instant, so at or under the cap no source can be over and the count by source (every
4 * 15-s row, 1.07 M on production, up to 1.8 s on the serving thread every 5 min) is not run.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp } from "../src/app.ts";
11 import { capRows } from "../src/boards/sampler.ts";
12
13 const T0 = Date.parse("2026-10-15T12:00:00.000Z");
14 const at = (i: number) => new Date(T0 + i * 15_000).toISOString();
15 let dir = "";
16 let app: ReturnType<typeof createApp>;
17
18 beforeAll(async () => {
19 dir = await mkdtemp(join(tmpdir(), "forge-sampler-instants-"));
20 app = createApp({ dataDir: dir, port: 0 });
21 });
22 afterAll(async () => {
23 app.close();
24 await rm(dir, { recursive: true, force: true });
25 });
26
27 /** The SQL `capRows` ran, and what it returned. */
28 function traced(cap: number): { dropped: number; sql: string[] } {
29 const sql: string[] = [];
30 const real = app.db.query.bind(app.db);
31 app.db.query = ((text: string) => {
32 sql.push(text);
33 return real(text);
34 }) as typeof app.db.query;
35 try {
36 return { dropped: capRows(app.db, cap), sql };
37 } finally {
38 app.db.query = real;
39 }
40 }
41
42 const grouped = (sql: string[]) => sql.filter((s) => s.includes("GROUP BY target"));
43
44 test("with no more instants than the cap, nothing is counted by source and nothing goes", () => {
45 const put = app.db.prepare("INSERT INTO machine_sample (at, step, target, cpu_cores) VALUES (?, 15, ?, 1)");
46 // Many sources, six instants each: wide, never over a cap of six.
47 for (let i = 0; i < 6; i++) for (let t = 0; t < 50; t++) put.run(at(i), `cpu:${String(t).padStart(3, "0")}`);
48 const { dropped, sql } = traced(6);
49 expect(dropped).toBe(0);
50 expect(grouped(sql)).toEqual([]);
51 expect(sql).toHaveLength(1);
52 });
53
54 test("one instant past the cap, the sources over it are found and trimmed", () => {
55 const put = app.db.prepare("INSERT INTO machine_sample (at, step, target, cpu_cores) VALUES (?, 15, ?, 1)");
56 put.run(at(6), "cpu:000");
57 const { dropped, sql } = traced(6);
58 expect(grouped(sql)).toHaveLength(1);
59 expect(dropped).toBe(1);
60 expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM machine_sample WHERE step = 15 AND target = 'cpu:000'").get()!.n).toBe(
61 6,
62 );
63 // The other sources, at the cap, are untouched.
64 expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM machine_sample WHERE step = 15").get()!.n).toBe(6 * 50);
65 });
66
67 test("the 5-min and hourly roll-ups are not instants of the 15-s rows", () => {
68 app.db.run("DELETE FROM machine_sample");
69 const put = app.db.prepare("INSERT INTO machine_sample (at, step, target, cpu_cores) VALUES (?, ?, 'x', 1)");
70 for (let i = 0; i < 20; i++) put.run(at(i * 20), 300);
71 for (let i = 0; i < 3; i++) put.run(at(i), 15);
72 const { dropped, sql } = traced(3);
73 expect(dropped).toBe(0);
74 expect(grouped(sql)).toEqual([]);
75 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs