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

The performance watcher measures budgeted routes that had no traffic, through an admin-only door, kept apart from real requests #16083

Merged opened this

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

Merged

mason/forge:mason/16066-the-performance-watcher-measures-budgete → main 0 commits fork

  • Merged. mason/16066-the-performance-watcher-measures-budgete was merged into main as 78ec2ba.

Review

Sign in to review this change.
18 files changed +423 −48
docs/features/performance-watcher.md +4 −2
@@ -6,13 +6,15 @@ row: Performance watcher
66
77 `src/perf/` keeps a capped in-memory record of real requests per route pattern (total, each Server-Timing phase, signed in or out; no paths, ids or queries). `budgets.ts` holds the budgets in words with the number beside them. Once a minute `duty.ts` files one issue per route and phase in the forge's repo when p95 has been over budget for 15 min with 20+ real requests; the finding names the slowest phase, its share and the cache hit rate. `git.ts` keeps the same record for every git process the forge spawns (`git/env.ts`, `git/local.ts`), keyed `git <subcommand>` from a fixed list (never an argument, path or ref; anything else is `git other`), timed from before the spawn gate so a queue counts; a subcommand whose p95 passes its budget the same way (250 ms; 10 s for the pack-moving ones: clone, fetch, push, gc, repack, pack-objects and the like) files one issue naming it, its count, p50 and p95. `loop.ts` names the routes running across an event-loop stall in the `loop` log line; nothing is kept beyond that line. `loop_worst.ts` keeps the worst event-loop lag of the last 10 s (ten one-second slots fed by the 50 ms sampler) and every response's Server-Timing names it as `lag;dur`; `/healthz` answers it as `loopLagMs` to `Accept: application/json`, so a slow time to first byte with a small `app;dur` reads as a stall outside the handler.
88
9 `history.ts` (#11477): every tick the duty folds the record's new samples into an in-memory ledger under the hour each sample happened in (so 10:50 traffic is never stamped 11:00) and upserts one row per route pattern (route, hour, n, p50, p95) into `route_hour`, so a row is the hour's p50 and p95, not the last 15 minutes'. At most 5,000 samples per route and hour are kept (past it the row stands on the first), at most 200 routes (the busiest) and 168 hours; older rows go in the same write. A restart starts an empty ledger: an empty record writes nothing, and a row is never replaced by one with fewer requests, so the hours before the restart keep the fuller row. Admins read them at `GET /api/v1/telemetry/routes?hours=N` (1 to 168, default 24; else 400).
9 `history.ts` (#11477): every tick the duty folds the record's new samples into an in-memory ledger under the hour each sample happened in (so 10:50 traffic is never stamped 11:00) and upserts one row per route pattern (route, hour, n, p50, p95) into `route_hour`, so a row is the hour's p50 and p95, not the last 15 minutes'. At most 5,000 samples per route and hour are kept (past it the row stands on the first), at most 200 routes (the busiest) and 168 hours; older rows go in the same write. A restart starts an empty ledger: an empty record writes nothing, and a row is never replaced by one with fewer requests, so the hours before the restart keep the fuller row. Admins read them at `GET /api/v1/telemetry/routes?hours=N` (1 to 168, default 24; else 400); each row says `synthetic`.
10
11 `probe.ts` (#16066): from minute 50 of each hour, the duty asks once for each budgeted GET route that had no real request that hour and has a sample address in `budgets.ts` (`/`, `/boards`, `/explore`, `/api/v1/health`). The door is `Servers.probe`, a function the booting process hands the duty: it answers through the routes without the listener, so nothing in a request names it (no header, query or address a client can set) and it is counted in no record. The answer's time becomes one `route_hour` row with `synthetic` set (`n` 1); it never replaces a row of real traffic, a later real write replaces it, and it never enters the record `evaluate` reads, so a probe cannot file a finding. A route with parameters (`/:owner/:name`) or a phase budget (`/explore#read`) is not probed; the admin read lists them as `notProbed` with why. Nothing is probed while `FORGE_CHECK` is set, and a probe answered 4xx or 5xx leaves no row. The probe is anonymous, the same as a visitor's; every probed route is public, so it needs no admin identity, only that the server alone can ask.
1012
1113 The last 24 hours read in the terminal's System screen (admin who is a person; the five slowest p95 first, with n, p50, p95 and the budget) and as the admin-only `route_hour` boards source (route, hour, n, p50, p95; `slowestRoutes` is one indexed query).
1214
1315 `/changelog` shows admins, under a heading, a plain row per release of the last seven days saying which routes got faster or slower after it (`release_delta.ts` compares the p95 of the 24 hours either side; `release_speed.ts` reads the rows). The terminal's changelog screen (`src/tui/screens/changelog.ts`) puts the same line in the release's own row, for an admin who is a person.
1416
15 Not yet: a synthetic probe for routes with no traffic (a client-written label would let anyone hide requests; it needs an admin-only door first), browser timings.
17 Not yet: browser timings.
1618
1719 ## Sampling the main thread: `FORGE_PROFILE=1` (#12455)
1820
src/boards/sources.ts +2 −1
@@ -171,8 +171,9 @@ export const SOURCES: Readonly<Record<string, Source>> = {
171171 route_hour: {
172172 table: "route_hour",
173173 owner: "admin",
174 // Real hours only: the probe's synthetic rows (#16066) are a sample of one, not traffic.
174175 select:
175 "SELECT route, strftime('%Y-%m-%dT%H:00:00.000Z', hour * 3600, 'unixepoch') AS hour, n, p50, p95 FROM route_hour",
176 "SELECT route, strftime('%Y-%m-%dT%H:00:00.000Z', hour * 3600, 'unixepoch') AS hour, n, p50, p95 FROM route_hour WHERE synthetic = 0",
176177 time: "hour",
177178 columns: { route: "text", hour: "time", n: "number", p50: "number", p95: "number" },
178179 docs: {
src/contract/openapi/routes/getApiV1TelemetryRoutes.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "get",
55 path: "/api/v1/telemetry/routes",
66 summary: "Route p50 and p95 by the hour, kept 7 days",
7 detail: "Route p50 and p95 by the hour, kept 7 days (a forge admin's, read scope): { hours, rows: [{ route, hour, n, p50, p95 }] }, hour is hours since the epoch, ms; hours 1 to 168 (default 24), a bad value is a 400",
7 detail: "Route p50 and p95 by the hour, kept 7 days (a forge admin's, read scope): { hours, rows: [{ route, hour, n, p50, p95, synthetic }], notProbed: [{ route, why }] }; synthetic is true on a row the hourly probe wrote for a budgeted route with no real request that hour, and notProbed lists the budgeted routes the probe does not ask, with why, hour is hours since the epoch, ms; hours 1 to 168 (default 24), a bad value is a 400",
88 auth: true,
99 role: "admin",
1010 query: { hours: { type: "integer", min: 1, max: 168 } },
src/core/migration-pins/20261123130000-route-hour-synthetic.pin added +1
@@ -0,0 +1,1 @@
1 d7150b50c3f4dc3a3be557a7e7aada5bf5dae39a467d922921cd9147c75d3e06
src/core/migrations/20261123130000-route-hour-synthetic.ts added +6
@@ -0,0 +1,6 @@
1 // `route_hour.synthetic` (#16066): 1 on a row the hourly probe wrote (the forge asking its own
2 // budgeted route in-process because no real request came that hour), 0 on every row of real
3 // traffic. Additive, defaulted: a row from before is real.
4 export default `
5 ALTER TABLE route_hour ADD COLUMN synthetic INTEGER NOT NULL DEFAULT 0;
6 `;
src/http/api.ts +2 −1
@@ -75,6 +75,7 @@ import { takeOrTell } from "../actions/follow.ts";
7575 import { noteRead, telemetryReader, type Reader } from "../actions/telemetry.ts";
7676 import { flowCopy, flowEtag, flowMaxAge } from "../system/flow_cache.ts";
7777 import { readHours, routeHours } from "../perf/history.ts";
78 import { planProbes } from "../perf/probe.ts";
7879 import { countRead } from "../system/telemetry_reads.ts";
7980 import { historyFor, sourcesOut, systemWithReaders, welcome } from "../system/telemetry.ts";
8081 import { weekCard, WEEK_DAYS } from "../crew/week_card.ts";
@@ -1355,7 +1356,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
13551356 const hours = readHours(ctx.url.searchParams.get("hours"));
13561357 if (hours === null) return apiError("invalid_hours", 400, "hours is a whole number from 1 to 168");
13571358 const rows = timePhase(ctx.request, "read", () => routeHours(ctx.app.db, hours));
1358 return timePhase(ctx.request, "render", () => json({ hours, rows }));
1359 return timePhase(ctx.request, "render", () => json({ hours, rows, notProbed: planProbes().notProbed }));
13591360 });
13601361
13611362 // The week's line per crew member (`crew/week_card.ts`); as MCP `crew` with kind "week".
src/http/server.ts +15
@@ -2383,6 +2383,12 @@ const fromStored = (stored: StoredResponse, replay: boolean): Response => {
23832383 export interface Servers {
23842384 /** Resolves once the post-boot warm-up of the public families has run (#14662). */
23852385 readonly warmed: Promise<void>;
2386 /**
2387 * The performance watcher's hourly probe (#16066): one GET answered through the routes without
2388 * the listener. Nothing in a request names it, so no client can reach or imitate it; it is
2389 * counted nowhere (`counted` never sees it), so it is in no real p95.
2390 */
2391 probe(path: string): Promise<{ status: number; ms: number }>;
23862392 readonly url: string;
23872393 /** Requests the listener still holds: 0 once every one has settled. */
23882394 readonly inFlight: number;
@@ -2620,6 +2626,7 @@ export async function serve(app: App, options: { warm?: { families?: readonly Fa
26202626 // One limiter per listener: its state is a minute of timestamps, and two
26212627 // forges in one process (every test file) must not share a budget.
26222628 const limiter = new RateLimiter();
2629 const probeLimiter = new RateLimiter();
26232630 // Hosted children answered in-process: one ForgeHttp per child dataDir,
26242631 // for the App open there now.
26252632 const childHttps = new Map<string, { child: App; http: ForgeHttp }>();
@@ -3061,6 +3068,14 @@ export async function serve(app: App, options: { warm?: { families?: readonly Fa
30613068 });
30623069 return {
30633070 warmed: warm.done,
3071 async probe(path) {
3072 const started = performance.now();
3073 const request = new Request(`http://localhost${path}`, { method: "GET" });
3074 // Its own limiter: the shared one is keyed by client, and a probe is nobody's.
3075 const response = await answer(app, router, apiRouter, probeLimiter, request);
3076 await response.arrayBuffer();
3077 return { status: response.status, ms: performance.now() - started };
3078 },
30643079 url: `http://localhost:${port}`,
30653080 port,
30663081 get inFlight() {
src/main.ts +4 −1
@@ -150,6 +150,7 @@ import { during } from "./perf/jobs.ts";
150150 import { stallLine } from "./perf/loop.ts";
151151 import { memoryWatch } from "./perf/memory_watch.ts";
152152 import { bootStall, gitRecord, liveOf } from "./perf/live.ts";
153 import type { ProbeDoor } from "./perf/probe.ts";
153154 import { keepFlowReadings, KEPT_MS } from "./flow/kept.ts";
154155 import { startKeeping } from "./flow/keep.ts";
155156 import { keepForgePages } from "./flow/pages.ts";
@@ -434,7 +435,8 @@ if (readOnly) {
434435 const bootSignup = signupFromEnv(process.env.FORGE_SIGNUP);
435436 if (bootSignup.ok && bootSignup.value !== null)
436437 setSignup(app.db, bootSignup.value, BOOT_ACTOR);
437 startPerfWatcher(app, liveOf(app).perfRecord, Date.now, TICK_MS, gitRecord);
438 const probeDoor: ProbeDoor = {};
439 startPerfWatcher(app, liveOf(app).perfRecord, Date.now, TICK_MS, gitRecord, probeDoor);
438440 // A release shipped by hand is recorded as live at boot, so live estimates and the base rate
439441 // resolve whichever way a release ships; estimates of "done" come due as time passes (#11955).
440442 const byHand = recordByHand(app.db);
@@ -477,6 +479,7 @@ await warmFlow(app);
477479 await warmPlans(app);
478480 await warmDisplays(app).catch(() => undefined);
479481 const servers = await serve(app, { warm: {} });
482 probeDoor.ask = servers.probe;
480483 // A fetch of this forge's own public host is answered by this listener, not the network (#14664).
481484 setOwnHost(canonicalUrl, servers.url);
482485 markReady();
src/perf/budgets.ts +13 −4
@@ -9,23 +9,32 @@ export interface Budget {
99 readonly words: string;
1010 /** p95 over this many ms, warm, is a finding. */
1111 readonly p95Ms: number;
12 /**
13 * A GET path the hourly probe may ask for this pattern (#16066): one that reads, names no
14 * account and needs none. Absent on a pattern with parameters, which is then listed as not
15 * probed rather than guessed at.
16 */
17 readonly sample?: string;
1218 }
1319
1420 export const BUDGETS: readonly Budget[] = [
15 { pattern: "/", words: "home p95 under 800 ms warm", p95Ms: 800 },
16 { pattern: "/boards", words: "boards p95 under 800 ms warm", p95Ms: 800 },
17 { pattern: "/explore", words: "explore p95 under 800 ms warm", p95Ms: 800 },
21 { pattern: "/", words: "home p95 under 800 ms warm", p95Ms: 800, sample: "/" },
22 { pattern: "/boards", words: "boards p95 under 800 ms warm", p95Ms: 800, sample: "/boards" },
23 { pattern: "/explore", words: "explore p95 under 800 ms warm", p95Ms: 800, sample: "/explore" },
1824 // The `read` phase of /explore's Server-Timing (#10946): a phase of that route, not a route; its
1925 // p95 is the same read's.
2026 { pattern: "/explore#read", words: "the ranked explore read over 200 repositories p95 under 50 ms", p95Ms: 50 },
2127 // The admin board of duties (#13388): stored state only, no duty runs on a GET. The `render`
2228 // phase of its Server-Timing, not the whole route, is held to this over 200 stored duty rows.
2329 { pattern: "/maintenance#render", words: "the maintenance board answers from stored state, under 50 ms over 200 duty rows", p95Ms: 50 },
24 { pattern: "/api/v1/health", words: "health p95 under 100 ms", p95Ms: 100 },
30 { pattern: "/api/v1/health", words: "health p95 under 100 ms", p95Ms: 100, sample: "/api/v1/health" },
2531 { pattern: "/:owner/:name", words: "repo page p95 under 800 ms warm", p95Ms: 800 },
2632 { pattern: "/:owner/:name/*", words: "repo sub-page p95 under 1000 ms warm", p95Ms: 1000 },
2733 ];
2834
35 /** A budget that is a phase of a route (`/explore#read`), not a route: nothing to request. */
36 export const isPhaseBudget = (b: Budget): boolean => b.pattern.includes("#");
37
2938 /** The budget a route pattern is held to, or undefined for a route with none. */
3039 export function budgetFor(pattern: string): Budget | undefined {
3140 return (
src/perf/duty.ts +39 −20
@@ -5,7 +5,8 @@
55 * open is not filed twice, and neither is a key this process has filed. A
66 * slow route or subcommand is a defect: filed with its kind's labels, a `bug`
77 * on its clock (#8856). Each tick it also folds the new samples into the hour's p50 and p95
8 * per route in `route_hour` (`history.ts`, #11477).
8 * per route in `route_hour` (`history.ts`, #11477), and, late in the hour, probes the budgeted
9 * routes that had no real request (`probe.ts`, #16066).
910 */
1011
1112 import type { App } from "../app.ts";
@@ -20,19 +21,44 @@ import type { PerfRecord } from "./record.ts";
2021 import { evaluate, evaluateGit, fresh } from "./watch.ts";
2122 import { during } from "./jobs.ts";
2223 import { createHourLedger } from "./history.ts";
24 import { probeIdleRoutes, type ProbeDoor } from "./probe.ts";
2325
2426 export const TICK_MS = 60_000;
2527
28 /** File each slow route or subcommand not yet filed as a defect issue on the forge's own repo. */
29 function fileFindings(app: App, record: PerfRecord, gitRecord: PerfRecord, at: number, filed: Set<string>): void {
30 try {
31 const slug = app.config.forgeRepo;
32 if (slug === undefined) return;
33 const [owner, name] = slug.split("/") as [string, string];
34 const repo = getRepo(app.db, owner, name);
35 const actor = repo && getUserById(app.db, repo.ownerId);
36 if (!repo || !actor) return;
37 const open = new Set(listIssues(app.db, repo.id, { state: "open" }).map((i) => i.title));
38 const findings = [...evaluate(record, at), ...evaluateGit(gitRecord, at)];
39 for (const f of fresh(findings, filed)) {
40 if (open.has(f.title)) continue;
41 const made = openIssue(app, actor, repo, { title: f.title, body: evidenceOf(f, new Date(at).toISOString()) });
42 if (made.ok) addLabels(app, repo.id, actor.id, made.value, kindLabels(app, repo.id, f.kind));
43 }
44 } catch (error) {
45 app.log.warn("performance watcher failed", { error: String(error) });
46 }
47 }
48
2649 export function startPerfWatcher(
2750 app: App,
2851 record: PerfRecord,
2952 now: () => number = Date.now,
3053 everyMs = TICK_MS,
3154 gitRecord: PerfRecord = createGitRecord(),
32 ): (() => void) & { tick: () => void } {
55 probeDoor: ProbeDoor = {},
56 ): (() => void) & { tick: () => Promise<void> } {
3357 const ledger = createHourLedger();
3458 const filed = new Set<string>();
35 const tick = (): void => {
59 let probing = false;
60 const tick = (): Promise<void> => {
61 let probed: Promise<void> = Promise.resolve();
3662 try {
3763 // Each tick folds the new samples into their own hour's row, off the request path (#11477).
3864 ledger.note(record, now());
@@ -40,25 +66,18 @@ export function startPerfWatcher(
4066 } catch (error) {
4167 app.log.warn("route history write failed", { error: String(error) });
4268 }
43 try {
44 const slug = app.config.forgeRepo;
45 if (slug === undefined) return;
46 const [owner, name] = slug.split("/") as [string, string];
47 const repo = getRepo(app.db, owner, name);
48 const actor = repo && getUserById(app.db, repo.ownerId);
49 if (!repo || !actor) return;
50 const open = new Set(listIssues(app.db, repo.id, { state: "open" }).map((i) => i.title));
51 const findings = [...evaluate(record, now()), ...evaluateGit(gitRecord, now())];
52 for (const f of fresh(findings, filed)) {
53 if (open.has(f.title)) continue;
54 const made = openIssue(app, actor, repo, { title: f.title, body: evidenceOf(f, new Date(now()).toISOString()) });
55 if (made.ok) addLabels(app, repo.id, actor.id, made.value, kindLabels(app, repo.id, f.kind));
56 }
57 } catch (error) {
58 app.log.warn("performance watcher failed", { error: String(error) });
69 // Late in the hour, a budgeted route nobody asked for is asked once (`probe.ts`, #16066): its
70 // row is flagged synthetic and the record that files findings never sees it.
71 if (probeDoor.ask !== undefined && !probing) {
72 probing = true;
73 probed = probeIdleRoutes({ db: app.db, record, ask: probeDoor.ask, now: now() })
74 .then(() => undefined, (error) => app.log.warn("route probe failed", { error: String(error) }))
75 .finally(() => (probing = false));
5976 }
77 fileFindings(app, record, gitRecord, now(), filed);
78 return probed;
6079 };
61 const timer = setInterval(() => during("perf-watcher", tick, undefined, app), everyMs);
80 const timer = setInterval(() => during("perf-watcher", () => void tick(), undefined, app), everyMs);
6281 timer.unref();
6382 return Object.assign(() => clearInterval(timer), { tick });
6483 }
src/perf/history.ts +39 −10
@@ -18,6 +18,11 @@ export interface RouteHour {
1818 readonly n: number;
1919 readonly p50: number;
2020 readonly p95: number;
21 /**
22 * True on a row the hourly probe wrote (`probe.ts`): not a person's request, never judged against
23 * a budget.
24 */
25 readonly synthetic: boolean;
2126 }
2227
2328 /** Samples kept per route and hour; past it an hour's row stands on its first `MAX_HOUR_SAMPLES`. */
@@ -62,12 +67,12 @@ export function createHourLedger(): HourLedger {
6267 db.transaction(() => {
6368 // A restart starts with an empty ledger: a row never shrinks to a thinner sample of its hour.
6469 const put = db.query(
65 `INSERT INTO route_hour (route, hour, n, p50, p95) VALUES (?1, ?2, ?3, ?4, ?5)
66 ON CONFLICT (route, hour) DO UPDATE SET n = excluded.n, p50 = excluded.p50, p95 = excluded.p95
67 WHERE excluded.n >= route_hour.n`,
70 `INSERT INTO route_hour (route, hour, n, p50, p95, synthetic) VALUES (?1, ?2, ?3, ?4, ?5, 0)
71 ON CONFLICT (route, hour) DO UPDATE SET n = excluded.n, p50 = excluded.p50, p95 = excluded.p95, synthetic = 0
72 WHERE excluded.n >= route_hour.n OR route_hour.synthetic = 1`,
6873 );
6974 for (const hour of touched) {
70 const rows: RouteHour[] = [];
75 const rows: Omit<RouteHour, "synthetic">[] = [];
7176 for (const [route, ms] of hours.get(hour) ?? [])
7277 rows.push({ route, hour, n: ms.length, p50: percentile(ms, 50)!, p95: percentile(ms, 95)! });
7378 // The busiest routes survive the cap.
@@ -87,14 +92,38 @@ export function createHourLedger(): HourLedger {
8792 };
8893 }
8994
90 /** The last `hours` hours (1 to 168) up to `now`, oldest first. */
91 export function routeHours(db: Database, hours: number, now: number = Date.now()): RouteHour[] {
95 /**
96 * One probe's answer, as the hour's row for a route that had no real request (#16066): n = 1,
97 * flagged synthetic. It never replaces a row, so a real hour is never overwritten by a probe, and
98 * the next real write replaces it (`write` above). Returns whether a row was written.
99 */
100 export function writeProbe(db: Database, route: string, hour: number, ms: number): boolean {
101 const res = db
102 .query(
103 `INSERT INTO route_hour (route, hour, n, p50, p95, synthetic) VALUES (?1, ?2, 1, ?3, ?3, 1)
104 ON CONFLICT (route, hour) DO NOTHING`,
105 )
106 .run(route, hour, ms);
107 return res.changes > 0;
108 }
109
110 /** Whether `route` has a row, real or probed, for `hour`. */
111 export function hasRow(db: Database, route: string, hour: number): boolean {
112 return db.query("SELECT 1 FROM route_hour WHERE route = ?1 AND hour = ?2").get(route, hour) !== null;
113 }
114
115 /**
116 * The last `hours` hours (1 to 168) up to `now`, oldest first. `realOnly` leaves out the probe's
117 * synthetic rows (#16066): every reader that says "how the forge answers" passes it.
118 */
119 export function routeHours(db: Database, hours: number, now: number = Date.now(), realOnly = false): RouteHour[] {
92120 const last = Math.floor(now / HOUR_MS);
93121 return db
94 .query<RouteHour, [number, number]>(
95 "SELECT route, hour, n, p50, p95 FROM route_hour WHERE hour > ?1 AND hour <= ?2 ORDER BY hour, route",
122 .query<Omit<RouteHour, "synthetic"> & { synthetic: number }, [number, number, number]>(
123 "SELECT route, hour, n, p50, p95, synthetic FROM route_hour WHERE hour > ?1 AND hour <= ?2 AND synthetic <= ?3 ORDER BY hour, route",
96124 )
97 .all(last - hours, last);
125 .all(last - hours, last, realOnly ? 0 : 1)
126 .map((r) => ({ ...r, synthetic: Number(r.synthetic) === 1 }));
98127 }
99128
100129 /** `?hours=` as a whole number 1 to 168 (default 24), or null. */
@@ -115,7 +144,7 @@ export function slowestRoutes(db: Database, hours: number, limit: number, now: n
115144 .query<RouteHour, [number, number, number]>(
116145 `SELECT route, hour, n, p50, p95 FROM (
117146 SELECT route, MAX(hour) AS hour, SUM(n) AS n, MAX(p50) AS p50, MAX(p95) AS p95
118 FROM route_hour WHERE hour > ?1 AND hour <= ?2 GROUP BY route)
147 FROM route_hour WHERE hour > ?1 AND hour <= ?2 AND synthetic = 0 GROUP BY route)
119148 ORDER BY p95 DESC, n DESC, route LIMIT ?3`,
120149 )
121150 .all(last - hours, last, limit);
src/perf/probe.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * The hourly synthetic probe (#16066): a budgeted GET route that had no real request this hour is
3 * asked for once, in-process, so the history says how it answers when nobody is looking.
4 *
5 * The door is a function the server hands the duty (`Servers.probe`): it answers through the
6 * router without the listener, so the request carries no label a client could copy, and it never
7 * reaches `PerfRecord`, the record real p95s and findings are judged from. A probe lands only in
8 * `route_hour`, flagged `synthetic`, and never replaces a real row.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import { BUDGETS, isPhaseBudget, type Budget } from "./budgets.ts";
13 import { HOUR_MS, hasRow, writeProbe } from "./history.ts";
14 import type { PerfRecord } from "./record.ts";
15
16 /** One in-process GET of `path`: the status and the ms until its body was read. */
17 export type Ask = (path: string) => Promise<{ readonly status: number; readonly ms: number }>;
18
19 /** Set once the server is up (`main.ts`); until then there is nothing to probe with. */
20 export interface ProbeDoor {
21 ask?: Ask;
22 }
23
24 /**
25 * A probe waits for the last minutes of the hour, so "no real request that hour" has meant
26 * something.
27 */
28 export const PROBE_FROM_MINUTE = 50;
29
30 export interface ProbePlan {
31 readonly probe: readonly { readonly route: string; readonly path: string }[];
32 readonly notProbed: readonly { readonly route: string; readonly why: string }[];
33 }
34
35 /**
36 * Which budgeted routes can be probed, and why each of the others cannot. Plain data in, plain data
37 * out.
38 */
39 export function planProbes(budgets: readonly Budget[] = BUDGETS): ProbePlan {
40 const probe: { route: string; path: string }[] = [];
41 const notProbed: { route: string; why: string }[] = [];
42 for (const b of budgets) {
43 if (isPhaseBudget(b)) notProbed.push({ route: b.pattern, why: "a phase of a route, not a route" });
44 else if (b.sample !== undefined) probe.push({ route: b.pattern, path: b.sample });
45 else if (/[:*]/.test(b.pattern)) notProbed.push({ route: b.pattern, why: "has parameters and its budget names no sample address" });
46 else notProbed.push({ route: b.pattern, why: "its budget names no sample address" });
47 }
48 return { probe, notProbed };
49 }
50
51 export interface ProbeDeps {
52 readonly db: Database;
53 readonly record: PerfRecord;
54 readonly ask: Ask;
55 readonly now: number;
56 /** The environment, for `FORGE_CHECK`: nothing is probed while a check runs. */
57 readonly env?: Readonly<Record<string, string | undefined>>;
58 readonly plan?: ProbePlan;
59 }
60
61 /** Probe each route that had no real request this hour; returns the routes it wrote a row for. */
62 export async function probeIdleRoutes(deps: ProbeDeps): Promise<string[]> {
63 const env = deps.env ?? process.env;
64 if (env["FORGE_CHECK"] !== undefined && env["FORGE_CHECK"] !== "") return [];
65 const hour = Math.floor(deps.now / HOUR_MS);
66 if ((deps.now - hour * HOUR_MS) / 60_000 < PROBE_FROM_MINUTE) return [];
67 const wrote: string[] = [];
68 for (const { route, path } of (deps.plan ?? planProbes()).probe) {
69 // Real traffic this hour, in the window or already written, and a probe already made, all say:
70 // leave it.
71 if (deps.record.traffic(route, hour * HOUR_MS).length > 0 || hasRow(deps.db, route, hour)) continue;
72 try {
73 const answer = await deps.ask(path);
74 if (answer.status < 400 && writeProbe(deps.db, route, hour, answer.ms)) wrote.push(route);
75 } catch {
76 // A probe that could not be answered leaves no row; the next tick asks again.
77 }
78 }
79 return wrote;
80 }
src/perf/release_delta.ts +1 −1
@@ -37,7 +37,7 @@ export function routesMoved(rows: readonly RouteHour[], releaseAt: number): Move
3737 const after = new Map<string, Side>();
3838 for (const r of rows) {
3939 const into = r.hour >= h - SIDE_HOURS && r.hour < h ? before : r.hour > h && r.hour <= h + SIDE_HOURS ? after : undefined;
40 if (into === undefined || r.n <= 0) continue;
40 if (into === undefined || r.n <= 0 || r.synthetic) continue;
4141 const side = into.get(r.route) ?? { n: 0, weighted: 0 };
4242 side.n += r.n;
4343 side.weighted += r.n * r.p95;
src/perf/release_speed.ts +1 −1
@@ -13,7 +13,7 @@ const DAY_MS = 86_400_000;
1313
1414 /** A release with nothing to say, or older than the 168 hours kept, has no line. */
1515 export function speedLines(db: Database, entries: readonly ReleaseEntry[], now = Date.now()): { version: string; line: string }[] {
16 const rows = routeHours(db, 168, now);
16 const rows = routeHours(db, 168, now, true);
1717 if (rows.length === 0) return [];
1818 return entries.flatMap((e) => {
1919 const at = Date.parse(e.date);
test/perf-history.test.ts +3 −3
@@ -60,8 +60,8 @@ test("a write keeps one row per route with n, p50 and p95, replaced never duplic
6060 const ledger = createHourLedger();
6161 expect(step(ledger, recordWith(2), now)).toBe(2);
6262 expect(routeHours(app.db, 1, now)).toEqual([
63 { route: "/r0", hour, n: 10, p50: 50, p95: 100 },
64 { route: "/r1", hour, n: 10, p50: 51, p95: 101 },
63 { route: "/r0", hour, n: 10, p50: 50, p95: 100, synthetic: false },
64 { route: "/r1", hour, n: 10, p50: 51, p95: 101, synthetic: false },
6565 ]);
6666 step(createHourLedger(), recordWith(2), now);
6767 expect(count()).toBe(2);
@@ -143,5 +143,5 @@ test("the API answers an admin, and refuses hours=0 with 400, a non-admin with 4
143143 expect(ok.status).toBe(200);
144144 const body = (await ok.json()) as any;
145145 expect(body.hours).toBe(2);
146 expect(body.rows).toEqual([{ route: "/x", hour: Math.floor(Date.now() / HOUR_MS), n: 3, p50: 1, p95: 2 }]);
146 expect(body.rows).toEqual([{ route: "/x", hour: Math.floor(Date.now() / HOUR_MS), n: 3, p50: 1, p95: 2, synthetic: false }]);
147147 });
test/perf-probe.test.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * The hourly synthetic probe (#16066): flagged, never real, never a finding, never reachable from
3 * outside.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { listIssues } from "../src/core/issues.ts";
12 import { getRepo } from "../src/core/repos.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { BUDGETS } from "../src/perf/budgets.ts";
16 import { startPerfWatcher } from "../src/perf/duty.ts";
17 import { createGitRecord } from "../src/perf/git.ts";
18 import { HOUR_MS, routeHours } from "../src/perf/history.ts";
19 import { liveOf } from "../src/perf/live.ts";
20 import { planProbes, probeIdleRoutes, type Ask } from "../src/perf/probe.ts";
21 import { createPerfRecord } from "../src/perf/record.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { proveAll } from "./helpers/verified.ts";
24
25 quietLogs();
26
27 let root = "";
28 let app: App;
29 let servers: Servers;
30 const hour = 700;
31 const late = hour * HOUR_MS + 55 * 60_000;
32
33 beforeAll(async () => {
34 root = mkdtempSync(join(tmpdir(), "forge-perf-probe-"));
35 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
36 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
37 if (!u.ok) throw new Error(u.error);
38 proveAll(app);
39 const made = await createRepo(app, u.value, { name: "forge" });
40 if (!made.ok) throw new Error(made.error);
41 servers = await serve(app);
42 });
43 afterAll(async () => {
44 await servers.stop();
45 app.close();
46 rmSync(root, { recursive: true, force: true });
47 });
48
49 const rows = () => app.db.query<{ route: string; hour: number; n: number; synthetic: number }, []>("SELECT route, hour, n, synthetic FROM route_hour").all();
50 const clear = () => app.db.query("DELETE FROM route_hour").run();
51 const slowAsk: Ask = async () => ({ status: 200, ms: 5000 });
52
53 test("a route with parameters or no sample address is listed as not probed, with why", () => {
54 const plan = planProbes();
55 const routes = plan.probe.map((p) => p.route);
56 expect(routes).toEqual(expect.arrayContaining(["/", "/boards", "/explore", "/api/v1/health"]));
57 const why = Object.fromEntries(plan.notProbed.map((n) => [n.route, n.why]));
58 expect(why["/:owner/:name"]).toContain("parameters");
59 expect(why["/:owner/:name/*"]).toContain("parameters");
60 expect(why["/explore#read"]).toContain("phase");
61 // Every budget is accounted for exactly once.
62 expect(plan.probe.length + plan.notProbed.length).toBe(BUDGETS.length);
63 });
64
65 test("an idle budgeted route is probed late in the hour and its row says synthetic", async () => {
66 clear();
67 const asked: string[] = [];
68 const ask: Ask = async (path) => (asked.push(path), { status: 200, ms: 12 });
69 const wrote = await probeIdleRoutes({ db: app.db, record: createPerfRecord(), ask, now: late, env: {} });
70 expect(wrote.sort()).toEqual(["/", "/api/v1/health", "/boards", "/explore"]);
71 expect(asked.sort()).toEqual(["/", "/api/v1/health", "/boards", "/explore"]);
72 expect(rows().every((r) => r.synthetic === 1 && r.n === 1 && r.hour === hour)).toBe(true);
73 expect(routeHours(app.db, 1, late).every((r) => r.synthetic)).toBe(true);
74 // Once an hour: a second pass asks nothing.
75 expect(await probeIdleRoutes({ db: app.db, record: createPerfRecord(), ask, now: late + 60_000, env: {} })).toEqual([]);
76 });
77
78 test("not early in the hour, not during a check, not for a route with real traffic", async () => {
79 clear();
80 const ask: Ask = async () => ({ status: 200, ms: 1 });
81 const record = createPerfRecord();
82 expect(await probeIdleRoutes({ db: app.db, record, ask, now: hour * HOUR_MS + 10 * 60_000, env: {} })).toEqual([]);
83 expect(await probeIdleRoutes({ db: app.db, record, ask, now: late, env: { FORGE_CHECK: "run-1" } })).toEqual([]);
84 record.add("/boards", { at: late - 1000, ms: 30, signedIn: false, phases: [] });
85 const wrote = await probeIdleRoutes({ db: app.db, record, ask, now: late, env: {} });
86 expect(wrote).not.toContain("/boards");
87 expect(wrote).toContain("/");
88 });
89
90 test("a failed answer leaves no row, and a probe never replaces a real row", async () => {
91 clear();
92 const failing: Ask = async () => ({ status: 500, ms: 3 });
93 expect(await probeIdleRoutes({ db: app.db, record: createPerfRecord(), ask: failing, now: late, env: {} })).toEqual([]);
94 expect(rows()).toEqual([]);
95 app.db.query("INSERT INTO route_hour (route, hour, n, p50, p95) VALUES ('/', ?1, 9, 5, 7)").run(hour);
96 await probeIdleRoutes({ db: app.db, record: createPerfRecord(), ask: async () => ({ status: 200, ms: 1 }), now: late, env: {} });
97 expect(rows().find((r) => r.route === "/")).toMatchObject({ n: 9, synthetic: 0 });
98 });
99
100 test("a probe never files a finding, however slow, and never enters the real record", async () => {
101 clear();
102 const record = liveOf(app).perfRecord;
103 const before = record.patterns().length;
104 const door = { ask: slowAsk };
105 // The forge's own check sets FORGE_CHECK, which stops probing by design; this test is about
106 // probing.
107 const was = process.env["FORGE_CHECK"];
108 delete process.env["FORGE_CHECK"];
109 const stop = startPerfWatcher(app, record, () => late, 3_600_000, createGitRecord(), door);
110 try {
111 await stop.tick();
112 } finally {
113 stop();
114 if (was !== undefined) process.env["FORGE_CHECK"] = was;
115 }
116 expect(rows().filter((r) => r.synthetic === 1).length).toBeGreaterThan(0);
117 expect(rows().every((r) => r.synthetic === 1)).toBe(true);
118 expect(record.patterns().length).toBe(before);
119 expect(listIssues(app.db, getRepo(app.db, "alice", "forge")!.id, { state: "open" })).toEqual([]);
120 });
121
122 test("the server's probe door counts nowhere; a request from outside with any label is a real one", async () => {
123 clear();
124 const record = liveOf(app).perfRecord;
125 const answered = await servers.probe("/boards");
126 expect(answered.status).toBeLessThan(400);
127 expect(record.traffic("/boards", 0).length).toBe(0);
128
129 const labels = { "x-forge-synthetic": "1", "x-synthetic": "true", "x-forge-probe": "1", "x-probe": "1", "user-agent": "forge-probe", "x-forwarded-for": "127.0.0.1" };
130 const res = await fetch(`${servers.url}/boards?synthetic=1&probe=1`, { headers: labels });
131 await res.arrayBuffer();
132 expect(res.status).toBeLessThan(400);
133 const real = record.traffic("/boards", 0);
134 expect(real.length).toBe(1);
135 expect(Object.keys(real[0]!)).not.toContain("synthetic");
136
137 // The history takes it as real traffic, not as a probe row.
138 const stop = startPerfWatcher(app, record, () => Date.now(), 3_600_000, createGitRecord());
139 await stop.tick();
140 stop();
141 const row = rows().find((r) => r.route === "/boards");
142 expect(row?.synthetic).toBe(0);
143 });
test/perf-synthetic-reads.test.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * A probe's row (#16066) is a sample of one, not traffic: no reader that says how the forge answers
3 * may rank it, chart it or compare releases with it. The admin API alone shows it, flagged.
4 */
5 import { Database } from "bun:sqlite";
6 import { expect, test } from "bun:test";
7 import { mkdtempSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp } from "../src/app.ts";
11 import { runQuery } from "../src/boards/query.ts";
12 import routeHourSql from "../src/core/migrations/20261111160000-route-hour.ts";
13 import syntheticSql from "../src/core/migrations/20261123130000-route-hour-synthetic.ts";
14 import { HOUR_MS, routeHours, slowestRoutes } from "../src/perf/history.ts";
15 import { speedLines } from "../src/perf/release_speed.ts";
16 import { releaseDelta } from "../src/perf/release_delta.ts";
17
18 const now = 1100 * HOUR_MS + 5 * 60_000;
19
20 function seeded(): Database {
21 const db = new Database(":memory:");
22 db.run(routeHourSql);
23 db.run(syntheticSql);
24 const put = db.query("INSERT INTO route_hour (route, hour, n, p50, p95, synthetic) VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
25 put.run("/real", 1099, 40, 20, 80, 0);
26 put.run("/idle", 1099, 1, 9000, 9000, 1);
27 return db;
28 }
29
30 test("the migration defaults an old row to real", () => {
31 const db = new Database(":memory:");
32 db.run(routeHourSql);
33 db.query("INSERT INTO route_hour (route, hour, n, p50, p95) VALUES ('/old', 5, 10, 1, 2)").run();
34 db.run(syntheticSql);
35 expect(db.query("SELECT synthetic FROM route_hour WHERE route = '/old'").get()).toEqual({ synthetic: 0 });
36 db.query("INSERT INTO route_hour (route, hour, n, p50, p95) VALUES ('/new', 6, 10, 1, 2)").run();
37 expect(db.query("SELECT synthetic FROM route_hour WHERE route = '/new'").get()).toEqual({ synthetic: 0 });
38 });
39
40 test("a slow synthetic row does not rank first on the System screen's slowest routes", () => {
41 const rows = slowestRoutes(seeded(), 24, 5, now);
42 expect(rows.map((r) => r.route)).toEqual(["/real"]);
43 });
44
45 test("the boards source leaves the synthetic row out", () => {
46 const root = mkdtempSync(join(tmpdir(), "forge-synthetic-reads-"));
47 const app = createApp({ dataDir: root, port: 0 });
48 const put = app.db.query("INSERT INTO route_hour (route, hour, n, p50, p95, synthetic) VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
49 put.run("/real", 1099, 40, 20, 80, 0);
50 put.run("/idle", 1099, 1, 9000, 9000, 1);
51 const a = runQuery(app.db, { source: "route_hour", aggregate: "max", column: "p95", groupBy: "route" }, { repoIds: "all" });
52 app.close();
53 rmSync(root, { recursive: true, force: true });
54 if (!a.ok) throw new Error(a.error);
55 expect(a.rows.map((r) => r.group)).toEqual(["/real"]);
56 });
57
58 test("the changelog's speed lines and the release delta leave it out", () => {
59 const db = seeded();
60 expect(routeHours(db, 24, now, true).map((r) => r.route)).toEqual(["/real"]);
61 expect(routeHours(db, 24, now).map((r) => r.route).sort()).toEqual(["/idle", "/real"]);
62 const row = (hour: number, p95: number, synthetic: boolean) => ({ route: "/x", hour, n: 50, p50: p95, p95, synthetic });
63 const before = row(990, 100, false);
64 expect(releaseDelta([before, row(1010, 900, true)], 1000 * HOUR_MS + 60_000)).toBe("");
65 expect(speedLines(db, [], now)).toEqual([]);
66 });
test/release-route-delta.test.ts +3 −3
@@ -4,7 +4,7 @@ import type { RouteHour } from "../src/perf/history.ts";
44
55 const H = 3_600_000;
66 const at = 1000 * H + 5 * 60_000;
7 const row = (route: string, hour: number, n: number, p95: number): RouteHour => ({ route, hour, n, p50: p95 / 2, p95 });
7 const row = (route: string, hour: number, n: number, p95: number): RouteHour => ({ route, hour, n, p50: p95 / 2, p95, synthetic: false });
88 const pair = (route: string, was: number, now: number, n = 20): RouteHour[] => [row(route, 990, n, was), row(route, 1010, n, now)];
99
1010 test("names a route that moved 20% with 20 requests each side", () => {
@@ -36,9 +36,9 @@ test("the page's speed lines: only releases of the last seven days, none without
3636 const { Database } = await import("bun:sqlite");
3737 const { speedLines } = await import("../src/perf/release_speed.ts");
3838 const db = new Database(":memory:");
39 db.run("CREATE TABLE route_hour (route TEXT, hour INTEGER, n INTEGER, p50 INTEGER, p95 INTEGER, PRIMARY KEY (route, hour))");
39 db.run("CREATE TABLE route_hour (route TEXT, hour INTEGER, n INTEGER, p50 INTEGER, p95 INTEGER, synthetic INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (route, hour))");
4040 const now = 1100 * H;
41 const put = (r: RouteHour) => db.query("INSERT INTO route_hour VALUES (?,?,?,?,?)").run(r.route, r.hour, r.n, r.p50, r.p95);
41 const put = (r: RouteHour) => db.query("INSERT INTO route_hour (route, hour, n, p50, p95) VALUES (?,?,?,?,?)").run(r.route, r.hour, r.n, r.p50, r.p95);
4242 expect(speedLines(db, [{ version: "1.0.0", date: new Date(1050 * H).toISOString(), pulls: [], oid: "x" }], now)).toEqual([]);
4343 for (const r of [row("/a", 1040, 30, 100), row("/a", 1060, 30, 200)]) put(r);
4444 const e = (version: string, hour: number) => ({ version, date: new Date(hour * H + 60_000).toISOString(), pulls: [], oid: version });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs