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

Boards, step 1: an admin queries the forge's tables as sources through one typed query #1583

Closed opened this
Closed without merging

scout/forge:scout/1559-boards-step-1-an-admin-queries-the-forge → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +693 −0
scripts/gate.ts +1
@@ -89,6 +89,7 @@ export const GATE: readonly string[] = [
8989 "test/landing.test.ts",
9090 "test/decide.test.ts",
9191 "test/ledger.test.ts",
92 "test/boards-query.test.ts",
9293 "test/capacity.test.ts",
9394 "test/guard-new-accounts.test.ts",
9495 "test/checks.test.ts",
src/boards/query.ts added +213
@@ -0,0 +1,213 @@
1 /**
2 * One typed question over one source (#1557): plain data in, plain data out.
3 * `parseQuery` validates at the boundary — an unknown source, column or
4 * operator is refused by name — and `runQuery` turns the checked question
5 * into parameterised SQL. Column expressions come from `sources.ts`; input
6 * only ever picks among them or becomes a bound value, never SQL text.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import { findSource, type Column, type Source } from "./sources.ts";
12
13 export const OPS = ["eq", "ne", "lt", "lte", "gt", "gte", "in"] as const;
14 export const AGGREGATES = ["count", "sum", "avg", "p50", "p95", "max"] as const;
15 export const BUCKETS = ["minute", "hour", "day"] as const;
16
17 type Op = (typeof OPS)[number];
18 type Aggregate = (typeof AGGREGATES)[number];
19 type Bucket = (typeof BUCKETS)[number];
20 type Value = string | number;
21
22 export interface Query {
23 readonly source: string;
24 readonly from?: string;
25 readonly to?: string;
26 readonly filter: readonly { column: string; op: Op; value: Value | Value[] }[];
27 readonly groupBy?: string | { bucket: Bucket };
28 readonly aggregate: Aggregate;
29 readonly column?: string;
30 }
31
32 export interface Row {
33 readonly group: string | number | null;
34 readonly value: number | null;
35 }
36
37 export interface Answer {
38 readonly source: string;
39 readonly aggregate: Aggregate;
40 readonly rows: Row[];
41 readonly truncated: boolean;
42 }
43
44 const MAX_ROWS = 1000;
45 const MAX_FILTERS = 20;
46 const MAX_IN = 100;
47 const MAX_TEXT = 200;
48 const OPS_SET: readonly string[] = OPS;
49 const SQL_OPS: Record<Exclude<Op, "in">, string> = {
50 eq: "=", ne: "<>", lt: "<", lte: "<=", gt: ">", gte: ">=",
51 };
52 const BUCKET_FORMAT: Record<Bucket, string> = {
53 minute: "%Y-%m-%dT%H:%M:00Z",
54 hour: "%Y-%m-%dT%H:00:00Z",
55 day: "%Y-%m-%dT00:00:00Z",
56 };
57
58 const isRecord = (v: unknown): v is Record<string, unknown> =>
59 typeof v === "object" && v !== null && !Array.isArray(v);
60
61 const column = (source: Source, name: unknown): Column | undefined =>
62 typeof name === "string" ? source.columns.find((c) => c.name === name) : undefined;
63
64 /** An instant as the database stores it, or nothing. */
65 function instant(v: unknown): string | undefined {
66 if (typeof v !== "string" || v.length > 40) return undefined;
67 const t = Date.parse(v);
68 return Number.isNaN(t) ? undefined : new Date(t).toISOString();
69 }
70
71 function scalar(col: Column, v: unknown): Value | undefined {
72 if (col.type === "number")
73 return typeof v === "number" && Number.isFinite(v) ? v : undefined;
74 if (typeof v !== "string" || v.length > MAX_TEXT) return undefined;
75 return col.type === "time" ? instant(v) : v;
76 }
77
78 export function parseQuery(raw: unknown): Result<Query, string> {
79 if (!isRecord(raw)) return err("the query must be a JSON object");
80 const source = typeof raw.source === "string" ? findSource(raw.source) : undefined;
81 if (!source) return err(`unknown source: ${JSON.stringify(raw.source ?? null)}`);
82
83 const times: { from?: string; to?: string } = {};
84 for (const key of ["from", "to"] as const) {
85 if (raw[key] === undefined) continue;
86 const t = instant(raw[key]);
87 if (t === undefined) return err(`${key} must be an ISO 8601 time`);
88 times[key] = t;
89 }
90
91 const filters = raw.filter ?? [];
92 if (!Array.isArray(filters)) return err("filter must be a list");
93 if (filters.length > MAX_FILTERS) return err(`at most ${MAX_FILTERS} filters`);
94 const filter: Query["filter"][number][] = [];
95 for (const f of filters) {
96 if (!isRecord(f)) return err("a filter is {column, op, value}");
97 const col = column(source, f.column);
98 if (!col) return err(`unknown column: ${JSON.stringify(f.column ?? null)} in ${source.name}`);
99 if (typeof f.op !== "string" || !OPS_SET.includes(f.op))
100 return err(`unknown op: ${JSON.stringify(f.op ?? null)}`);
101 const op = f.op as Op;
102 if (op === "in") {
103 if (!Array.isArray(f.value) || f.value.length === 0 || f.value.length > MAX_IN)
104 return err(`in takes a list of 1 to ${MAX_IN} values`);
105 const values = f.value.map((v) => scalar(col, v));
106 if (values.some((v) => v === undefined))
107 return err(`a value for ${col.name} must be a ${col.type === "number" ? "number" : "string"}`);
108 filter.push({ column: col.name, op, value: values as Value[] });
109 } else {
110 const value = scalar(col, f.value);
111 if (value === undefined)
112 return err(`the value for ${col.name} must be ${col.type === "number" ? "a number" : col.type === "time" ? "an ISO 8601 time" : "a string"}`);
113 filter.push({ column: col.name, op, value });
114 }
115 }
116
117 let groupBy: Query["groupBy"];
118 if (raw.groupBy !== undefined) {
119 if (isRecord(raw.groupBy)) {
120 const b = raw.groupBy.bucket;
121 if (typeof b !== "string" || !(BUCKETS as readonly string[]).includes(b))
122 return err(`unknown bucket: ${JSON.stringify(b ?? null)}`);
123 groupBy = { bucket: b as Bucket };
124 } else {
125 const col = column(source, raw.groupBy);
126 if (!col) return err(`unknown column: ${JSON.stringify(raw.groupBy)} in ${source.name}`);
127 groupBy = col.name;
128 }
129 }
130
131 if (typeof raw.aggregate !== "string" || !(AGGREGATES as readonly string[]).includes(raw.aggregate))
132 return err(`unknown aggregate: ${JSON.stringify(raw.aggregate ?? null)}`);
133 const aggregate = raw.aggregate as Aggregate;
134
135 let measured: string | undefined;
136 if (aggregate !== "count") {
137 const col = column(source, raw.column);
138 if (!col) return err(`${aggregate} needs a column of ${source.name}: ${JSON.stringify(raw.column ?? null)} is unknown`);
139 if (col.type === "text") return err(`${aggregate} needs a number or time column, not ${col.name}`);
140 if (col.type === "time" && aggregate !== "max")
141 return err(`${aggregate} needs a number column, not ${col.name}`);
142 measured = col.name;
143 } else if (raw.column !== undefined && !column(source, raw.column)) {
144 return err(`unknown column: ${JSON.stringify(raw.column)} in ${source.name}`);
145 }
146
147 return ok({
148 source: source.name,
149 ...times,
150 filter,
151 ...(groupBy === undefined ? {} : { groupBy }),
152 aggregate,
153 ...(measured === undefined ? {} : { column: measured }),
154 });
155 }
156
157 export function runQuery(db: Database, q: Query): Answer {
158 const source = findSource(q.source)!;
159 const col = (name: string): Column => column(source, name)!;
160 const at = col(source.at).sql;
161
162 const where: string[] = [source.where];
163 const params: (string | number)[] = [...source.params];
164 if (q.from !== undefined) { where.push(`${at} >= ?`); params.push(q.from); }
165 if (q.to !== undefined) { where.push(`${at} < ?`); params.push(q.to); }
166 for (const f of q.filter) {
167 const sql = col(f.column).sql;
168 if (f.op === "in") {
169 const values = f.value as Value[];
170 where.push(`${sql} IN (${values.map(() => "?").join(", ")})`);
171 params.push(...values);
172 } else {
173 where.push(`${sql} ${SQL_OPS[f.op]} ?`);
174 params.push(f.value as Value);
175 }
176 }
177
178 const group =
179 q.groupBy === undefined
180 ? "NULL"
181 : typeof q.groupBy === "string"
182 ? col(q.groupBy).sql
183 : `strftime('${BUCKET_FORMAT[q.groupBy.bucket]}', ${at})`;
184 const measure = q.column === undefined ? "1" : col(q.column).sql;
185 const base = `SELECT ${group} AS g, ${measure} AS v FROM ${source.from} WHERE ${where.join(" AND ")}`;
186
187 let sql: string;
188 switch (q.aggregate) {
189 case "count":
190 sql = `SELECT g, COUNT(*) AS value FROM (${base}) GROUP BY g ORDER BY g LIMIT ${MAX_ROWS + 1}`;
191 break;
192 case "p50":
193 case "p95": {
194 // Nearest rank: the ceil(p·n)-th smallest value in each group.
195 const p = q.aggregate === "p50" ? 50 : 95;
196 sql = `SELECT g, v AS value FROM (
197 SELECT g, v, ROW_NUMBER() OVER (PARTITION BY g ORDER BY v) AS rn,
198 COUNT(*) OVER (PARTITION BY g) AS n
199 FROM (${base}) WHERE v IS NOT NULL)
200 WHERE rn = MAX(1, (n * ${p} + 99) / 100) ORDER BY g LIMIT ${MAX_ROWS + 1}`;
201 break;
202 }
203 default:
204 sql = `SELECT g, ${q.aggregate.toUpperCase()}(v) AS value FROM (${base}) GROUP BY g ORDER BY g LIMIT ${MAX_ROWS + 1}`;
205 }
206
207 const rows = db
208 .query<{ g: string | number | null; value: number | null }, (string | number)[]>(sql)
209 .all(...params)
210 .map((r) => ({ group: r.g, value: r.value }));
211 const truncated = rows.length > MAX_ROWS;
212 return { source: q.source, aggregate: q.aggregate, rows: truncated ? rows.slice(0, MAX_ROWS) : rows, truncated };
213 }
src/boards/sources.ts added +237
@@ -0,0 +1,237 @@
1 /**
2 * The tables an admin may ask questions of (#1557), each as a named source
3 * with its columns and their types. Plain data: `boards/query.ts` reads it
4 * to validate a question and to build the SQL, and the API lists it.
5 *
6 * A column is here only if it is safe to show to a forge admin as a number
7 * or a short word. Free text (titles, bodies, summaries, logs), sealed
8 * values and anything secret is never a column; each source names what it
9 * withholds, so the listing says so. Rows that belong to a sealed report —
10 * the issue, or the private repository the crew works it in — are not in a
11 * source at all.
12 */
13
14 import { CAPACITY_KEYS } from "../core/capacity.ts";
15
16 export type ColumnType = "text" | "number" | "time";
17
18 export interface Column {
19 readonly name: string;
20 readonly type: ColumnType;
21 /** The SQL expression behind it: written here, never taken from input. */
22 readonly sql: string;
23 }
24
25 export interface Source {
26 readonly name: string;
27 readonly about: string;
28 /** FROM clause with its joins, aliased so `sql` expressions resolve. */
29 readonly from: string;
30 /** Always-applied condition and its bound values. */
31 readonly where: string;
32 readonly params: readonly string[];
33 /** The time column `from`/`to` and buckets work on. */
34 readonly at: string;
35 readonly columns: readonly Column[];
36 /** What the table holds that no column shows. */
37 readonly withheld: readonly string[];
38 }
39
40 const text = (name: string, sql = name): Column => ({ name, type: "text", sql });
41 const num = (name: string, sql = name): Column => ({ name, type: "number", sql });
42 const time = (name: string, sql = name): Column => ({ name, type: "time", sql });
43
44 /** Not a row of a sealed report, nor of the repository it is worked in. */
45 const notSealed = (issue: string, repo: string): string =>
46 `(${issue} IS NULL OR ${issue} NOT IN (SELECT id FROM issue WHERE sealed = 1))
47 AND ${repo} NOT IN (SELECT id FROM repo WHERE sealed_for IS NOT NULL)`;
48
49 const ms = (end: string, start: string): string =>
50 `CAST((julianday(${end}) - julianday(${start})) * 86400000 AS INTEGER)`;
51
52 const SOURCES: readonly Source[] = [
53 {
54 name: "runs",
55 about: "Every run: agent work, deploys and checks.",
56 from: "run r",
57 where: notSealed("r.issue_id", "r.repo_id"),
58 params: [],
59 at: "created_at",
60 columns: [
61 text("id", "r.id"),
62 text("repo_id", "r.repo_id"),
63 text("kind", "r.kind"),
64 text("state", "r.state"),
65 text("env", "r.env"),
66 text("branch", "r.branch"),
67 text("actor_id", "r.actor_id"),
68 text("subscription_id", "r.subscription_id"),
69 num("cost_usd", "r.cost_usd"),
70 num("turns", "r.turns"),
71 num("attempt", "r.attempt"),
72 num("duration_ms", `CASE WHEN r.started_at IS NOT NULL AND r.finished_at IS NOT NULL THEN ${ms("r.finished_at", "r.started_at")} END`),
73 time("created_at", "r.created_at"),
74 time("started_at", "r.started_at"),
75 time("finished_at", "r.finished_at"),
76 ],
77 withheld: ["summary", "reason", "session_id", "check_detail", "sandbox_note"],
78 },
79 {
80 name: "pulls",
81 about: "Pull requests, from opening to merge.",
82 from: "pull p JOIN issue i ON i.id = p.issue_id",
83 where: notSealed("i.id", "i.repo_id"),
84 params: [],
85 at: "created_at",
86 columns: [
87 text("id", "i.id"),
88 text("repo_id", "i.repo_id"),
89 num("number", "i.number"),
90 text("state", "i.state"),
91 text("author_id", "i.author_id"),
92 text("base_branch", "p.base_branch"),
93 text("head_branch", "p.head_branch"),
94 text("merged_by", "p.merged_by"),
95 num("open_ms", `${ms("COALESCE(p.merged_at, i.closed_at)", "i.created_at")}`),
96 time("created_at", "i.created_at"),
97 time("closed_at", "i.closed_at"),
98 time("merged_at", "p.merged_at"),
99 ],
100 withheld: ["title", "body", "head_oid", "base_oid", "merged_oid"],
101 },
102 {
103 name: "reviews",
104 about: "Reviews left on pulls.",
105 from: "review v JOIN issue i ON i.id = v.issue_id",
106 where: notSealed("i.id", "i.repo_id"),
107 params: [],
108 at: "created_at",
109 columns: [
110 text("id", "v.id"),
111 text("issue_id", "v.issue_id"),
112 text("repo_id", "i.repo_id"),
113 text("author_id", "v.author_id"),
114 text("state", "v.state"),
115 time("created_at", "v.created_at"),
116 ],
117 withheld: ["body", "commit_oid"],
118 },
119 {
120 name: "deploys",
121 about: "Deploy runs: how long they took and how they ended.",
122 from: "run r",
123 where: `r.kind = 'deploy' AND ${notSealed("r.issue_id", "r.repo_id")}`,
124 params: [],
125 at: "created_at",
126 columns: [
127 text("id", "r.id"),
128 text("repo_id", "r.repo_id"),
129 text("env", "r.env"),
130 text("branch", "r.branch"),
131 text("state", "r.state"),
132 num("attempt", "r.attempt"),
133 num("duration_ms", `CASE WHEN r.started_at IS NOT NULL AND r.finished_at IS NOT NULL THEN ${ms("r.finished_at", "r.started_at")} END`),
134 time("created_at", "r.created_at"),
135 time("serving_at", "r.serving_at"),
136 time("finished_at", "r.finished_at"),
137 ],
138 withheld: ["summary", "reason", "check_detail", "sandbox_note"],
139 },
140 {
141 name: "apps",
142 about: "Apps the forge runs, by access and age.",
143 from: "app a",
144 where: "a.repo_id NOT IN (SELECT id FROM repo WHERE sealed_for IS NOT NULL)",
145 params: [],
146 at: "created_at",
147 columns: [
148 text("id", "a.id"),
149 text("repo_id", "a.repo_id"),
150 text("slug", "a.slug"),
151 text("access", "a.access"),
152 time("created_at", "a.created_at"),
153 ],
154 withheld: ["preview_data", "environment values", "domain tokens"],
155 },
156 {
157 name: "capacity_changes",
158 about: "Every change to the forge's capacity settings: who, when, from what to what.",
159 from: "forge_setting_change c",
160 where: `c.key IN (${CAPACITY_KEYS.map(() => "?").join(", ")})`,
161 params: CAPACITY_KEYS,
162 at: "at",
163 columns: [
164 text("key", "c.key"),
165 text("from_value", "c.from_value"),
166 text("to_value", "c.to_value"),
167 text("actor_id", "c.actor_id"),
168 time("at", "c.at"),
169 ],
170 withheld: ["every forge setting that is not a capacity setting"],
171 },
172 {
173 name: "decisions",
174 about: "The decision ledger: what the crew chose, with what confidence and how it turned out.",
175 from: "decision d",
176 where: notSealed("d.issue_id", "d.repo_id"),
177 params: [],
178 at: "created_at",
179 columns: [
180 text("id", "d.id"),
181 text("kind", "d.kind"),
182 text("repo_id", "d.repo_id"),
183 text("issue_id", "d.issue_id"),
184 text("state", "d.state"),
185 text("answer", "d.answer"),
186 num("p", "d.p"),
187 text("by", "d.by"),
188 num("ms", "d.ms"),
189 text("outcome", "d.outcome"),
190 time("created_at", "d.created_at"),
191 time("outcome_at", "d.outcome_at"),
192 ],
193 withheld: [],
194 },
195 {
196 name: "spend",
197 about: "Model usage by run: tokens, dollars and wall time.",
198 from: "usage u",
199 where: notSealed("u.issue_id", "u.repo_id"),
200 params: [],
201 at: "at",
202 columns: [
203 text("run_id", "u.run_id"),
204 text("repo_id", "u.repo_id"),
205 text("issue_id", "u.issue_id"),
206 text("agent_id", "u.agent_id"),
207 text("subscription_id", "u.subscription_id"),
208 text("kind", "u.kind"),
209 num("tokens_in", "u.tokens_in"),
210 num("tokens_out", "u.tokens_out"),
211 num("cost_usd", "u.cost_usd"),
212 num("wall_ms", "u.wall_ms"),
213 text("outcome", "u.outcome"),
214 time("at", "u.at"),
215 ],
216 withheld: ["subscription credentials"],
217 },
218 ];
219
220 export function listSources(): readonly Source[] {
221 return SOURCES;
222 }
223
224 export function findSource(name: string): Source | undefined {
225 return SOURCES.find((s) => s.name === name);
226 }
227
228 /** What the API shows of a source: names and types, never the SQL. */
229 export function describeSources(): unknown[] {
230 return SOURCES.map((s) => ({
231 name: s.name,
232 about: s.about,
233 at: s.at,
234 columns: s.columns.map((c) => ({ name: c.name, type: c.type })),
235 withheld: s.withheld,
236 }));
237 }
src/http/api.ts +26
@@ -10,6 +10,8 @@
1010
1111 import { askCheck } from "../checks/again.ts";
1212 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
13 import { parseQuery, runQuery } from "../boards/query.ts";
14 import { describeSources } from "../boards/sources.ts";
1315 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
1416 import {
1517 accountSignIns,
@@ -1270,6 +1272,30 @@ export function apiRoutes(router: Router<Handler>): void {
12701272 );
12711273 });
12721274
1275 // The boards' sources and the one typed query over them (`boards/`): a
1276 // site admin who is a person; an agent or anyone else is refused (403).
1277 const boardsAdmin = (ctx: Ctx): Response | undefined => {
1278 const user = ctx.auth.user;
1279 if (!user) return unauthorized();
1280 if (user.kind === "agent" || user.isAdmin !== true)
1281 return apiError("forbidden", 403, "boards are for a site admin who is a person");
1282 return requireScope(ctx, "ro");
1283 };
1284
1285 router.add("GET", "/api/v1/boards/sources", (ctx) => {
1286 const denied = boardsAdmin(ctx);
1287 if (denied) return denied;
1288 return json({ items: describeSources() });
1289 });
1290
1291 router.add("POST", "/api/v1/boards/query", async (ctx) => {
1292 const denied = boardsAdmin(ctx);
1293 if (denied) return denied;
1294 const parsed = parseQuery(await body(ctx.request));
1295 if (!parsed.ok) return apiError("bad_query", 400, parsed.error);
1296 return json(runQuery(ctx.app.db, parsed.value));
1297 });
1298
12731299 router.add("GET", "/api/v1/admin/accounts", (ctx) => {
12741300 const denied = accountAdmin(ctx, "ro");
12751301 if (denied) return denied;
test/boards-query.test.ts added +216
@@ -0,0 +1,216 @@
1 /**
2 * Boards, step 1 (#1559): a site admin who is a person asks the forge's
3 * tables questions through one typed query. An agent or a non-admin is
4 * refused; no sealed value is a column or a row; a bad question is a 400
5 * that names what was wrong; and a day of runs answers in under 50 ms.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createAgent } from "../src/actions/crew.ts";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { runQuery, parseQuery } from "../src/boards/query.ts";
16 import { listSources } from "../src/boards/sources.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser } from "../src/core/users.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20
21 describe("boards: one typed query over the forge's tables", () => {
22 let dataDir: string;
23 let app: App;
24 let servers: Servers;
25 let admin: string;
26 let member: string;
27 let agent: string;
28 let repoId: string;
29 let sealedRepoId: string;
30
31 const call = (token: string, method: string, path: string, body?: unknown) =>
32 fetch(`${servers.url}/api/v1${path}`, {
33 method,
34 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
35 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
36 });
37 const ask = (token: string, q: unknown) => call(token, "POST", "/boards/query", q);
38
39 const seed = (id: string, repo: string, at: string, extra: Record<string, unknown> = {}) =>
40 app.db
41 .query(
42 `INSERT INTO run (id, repo_id, kind, state, summary, session_id, cost_usd, created_at, started_at, finished_at)
43 VALUES (?1, ?2, ?3, ?4, 'LEAK-SUMMARY', 'LEAK-SESSION', ?5, ?6, ?6, ?7)`,
44 )
45 .run(
46 id,
47 repo,
48 (extra.kind as string) ?? "agent",
49 (extra.state as string) ?? "ok",
50 (extra.cost as number) ?? 1,
51 at,
52 (extra.end as string) ?? at,
53 );
54
55 beforeAll(async () => {
56 dataDir = await mkdtemp(join(tmpdir(), "forge-boards-"));
57 app = createApp({ dataDir, port: 0 });
58 servers = await serve(app);
59 const mk = async (username: string, first = false) => {
60 const r = await createUser(app.db, {
61 trusted: true,
62 username,
63 email: `${username}@forge.local`,
64 password: "a-good-passphrase",
65 adminIfFirst: first,
66 });
67 if (!r.ok) throw new Error(r.error);
68 return r.value;
69 };
70 const alice = await mk("alice", true);
71 const bob = await mk("bob");
72 const made = await createAgent(app, alice, { username: "scout" });
73 if (!made.ok) throw new Error(String(made.error));
74 admin = createToken(app.db, alice.id, "t", "admin").token;
75 member = createToken(app.db, bob.id, "t", "rw").token;
76 agent = createToken(app.db, made.value.user.id, "t", "rw").token;
77 const repo = await createRepo(app, alice, { name: "demo", visibility: "public" });
78 if (!repo.ok) throw new Error(String(repo.error));
79 repoId = repo.value.id;
80 const sealed = await createRepo(app, alice, { name: "hidden", visibility: "private" });
81 if (!sealed.ok) throw new Error(String(sealed.error));
82 sealedRepoId = sealed.value.id;
83 app.db.query("UPDATE repo SET sealed_for = ?1 WHERE id = ?2").run(repoId, sealedRepoId);
84
85 seed("r1", repoId, "2026-10-01T10:05:00.000Z");
86 seed("r2", repoId, "2026-10-01T10:20:00.000Z", { state: "failed", cost: 3 });
87 seed("r3", repoId, "2026-10-01T10:59:00.000Z", { cost: 5 });
88 seed("r4", repoId, "2026-10-01T11:01:00.000Z", { kind: "deploy" });
89 seed("secret", sealedRepoId, "2026-10-01T10:30:00.000Z");
90 });
91
92 afterAll(async () => {
93 servers.stop();
94 app.close();
95 await rm(dataDir, { recursive: true, force: true });
96 });
97
98 test("runs counted per hour", async () => {
99 const res = await ask(admin, {
100 source: "runs",
101 from: "2026-10-01T00:00:00Z",
102 to: "2026-10-02T00:00:00Z",
103 filter: [],
104 groupBy: { bucket: "hour" },
105 aggregate: "count",
106 });
107 expect(res.status).toBe(200);
108 const body = (await res.json()) as { rows: { group: string; value: number }[] };
109 expect(body.rows).toEqual([
110 { group: "2026-10-01T10:00:00Z", value: 3 },
111 { group: "2026-10-01T11:00:00Z", value: 1 },
112 ]);
113 });
114
115 test("filters, columns and aggregates", async () => {
116 const q = (extra: object) =>
117 ask(admin, { source: "runs", filter: [], aggregate: "count", ...extra }).then(
118 (r) => r.json() as Promise<{ rows: { group: unknown; value: number }[] }>,
119 );
120 expect((await q({ filter: [{ column: "state", op: "eq", value: "failed" }] })).rows[0]!.value).toBe(1);
121 expect((await q({ filter: [{ column: "kind", op: "in", value: ["deploy"] }] })).rows[0]!.value).toBe(1);
122 expect((await q({ groupBy: "state" })).rows.map((r) => [r.group, r.value])).toEqual([
123 ["failed", 1],
124 ["ok", 3],
125 ]);
126 expect((await q({ aggregate: "sum", column: "cost_usd" })).rows[0]!.value).toBe(10);
127 expect((await q({ aggregate: "max", column: "cost_usd" })).rows[0]!.value).toBe(5);
128 expect((await q({ aggregate: "p50", column: "cost_usd" })).rows[0]!.value).toBe(1);
129 expect((await q({ aggregate: "p95", column: "cost_usd" })).rows[0]!.value).toBe(5);
130 expect((await q({ aggregate: "avg", column: "cost_usd" })).rows[0]!.value).toBe(2.5);
131 });
132
133 test("an agent token and a non-admin get 403, at both doors", async () => {
134 for (const token of [agent, member]) {
135 expect((await call(token, "GET", "/boards/sources")).status).toBe(403);
136 expect((await ask(token, { source: "runs", filter: [], aggregate: "count" })).status).toBe(403);
137 }
138 const none = await fetch(`${servers.url}/api/v1/boards/sources`);
139 expect(none.status).toBe(401);
140 expect((await call(admin, "GET", "/boards/sources")).status).toBe(200);
141 });
142
143 test("no sealed or secret value appears in any source", async () => {
144 const listed = await (await call(admin, "GET", "/boards/sources")).json();
145 const names = (listed as { items: { name: string }[] }).items.map((s) => s.name);
146 expect(names).toEqual(["runs", "pulls", "reviews", "deploys", "apps", "capacity_changes", "decisions", "spend"]);
147 expect(JSON.stringify(listed)).not.toMatch(/LEAK/);
148 for (const s of listSources()) {
149 for (const c of s.columns)
150 expect(c.name).not.toMatch(/secret|^token$|password|hash|body|summary|session_id|title|_enc/);
151 for (const c of s.columns.filter((c) => c.type === "text")) {
152 const res = await ask(admin, { source: s.name, filter: [], groupBy: c.name, aggregate: "count" });
153 expect(res.status).toBe(200);
154 expect(JSON.stringify(await res.json())).not.toMatch(/LEAK|secret/);
155 }
156 }
157 const runs = listSources().find((s) => s.name === "runs")!;
158 expect(runs.withheld).toContain("summary");
159 // the sealed repository's run is not a row of any source
160 const all = (await (await ask(admin, { source: "runs", filter: [], aggregate: "count" })).json()) as {
161 rows: { value: number }[];
162 };
163 expect(all.rows[0]!.value).toBe(4);
164 });
165
166 test("a bad question is a 400 that names what is wrong", async () => {
167 const bad = async (q: unknown, named: string) => {
168 const res = await ask(admin, q);
169 expect(res.status).toBe(400);
170 expect(((await res.json()) as { message: string }).message).toContain(named);
171 };
172 await bad({ source: "nope", filter: [], aggregate: "count" }, "nope");
173 await bad({ source: "runs", filter: [{ column: "summary", op: "eq", value: "x" }], aggregate: "count" }, "summary");
174 await bad({ source: "runs", filter: [{ column: "state", op: "like", value: "x" }], aggregate: "count" }, "like");
175 await bad({ source: "runs", filter: [], groupBy: "x; DROP TABLE run", aggregate: "count" }, "DROP TABLE");
176 await bad({ source: "runs", filter: [], aggregate: "median" }, "median");
177 await bad({ source: "runs", filter: [], aggregate: "sum", column: "state" }, "state");
178 await bad({ source: "runs", filter: [], groupBy: { bucket: "week" }, aggregate: "count" }, "week");
179 await bad({ source: "runs", from: "yesterday-ish", filter: [], aggregate: "count" }, "from");
180 expect(parseQuery("x").ok).toBe(false);
181 });
182
183 test("input is a bound value, never SQL", async () => {
184 const res = await ask(admin, {
185 source: "runs",
186 filter: [{ column: "state", op: "eq", value: "ok' OR '1'='1" }],
187 aggregate: "count",
188 });
189 expect(res.status).toBe(200);
190 expect(((await res.json()) as { rows: unknown[] }).rows).toEqual([]);
191 });
192
193 test("a day of runs answers in under 50 ms", () => {
194 const insert = app.db.query(
195 `INSERT INTO run (id, repo_id, kind, state, created_at) VALUES (?1, ?2, 'agent', 'ok', ?3)`,
196 );
197 app.db.transaction(() => {
198 for (let i = 0; i < 20000; i++)
199 insert.run(`bulk${i}`, repoId, new Date(Date.UTC(2026, 9, 5) + i * 4000).toISOString());
200 })();
201 const parsed = parseQuery({
202 source: "runs",
203 from: "2026-10-05T00:00:00Z",
204 to: "2026-10-06T00:00:00Z",
205 filter: [{ column: "state", op: "eq", value: "ok" }],
206 groupBy: { bucket: "hour" },
207 aggregate: "count",
208 });
209 if (!parsed.ok) throw new Error(parsed.error);
210 runQuery(app.db, parsed.value);
211 const t = performance.now();
212 const answer = runQuery(app.db, parsed.value);
213 expect(performance.now() - t).toBeLessThan(50);
214 expect(answer.rows.length).toBe(23);
215 });
216 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs