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

Sentinel: shared:01m23vygyffx5hg2f5vm8r74sr:3f0ik8dh7l is past its budget: trevato/forge: "every GET page is within its counted work, warm, naming its slowest phase" failed on 11 pulls in the la… #15956

Merged opened this

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

Merged

mason/forge:mason/15924-sentinel-shared-01m23vygyffx5hg2f5vm8r74 → main 0 commits fork

  • Merged. mason/15924-sentinel-shared-01m23vygyffx5hg2f5vm8r74 was merged into main as ddbf675.

Review

Sign in to review this change.
3 files changed +112 −6
test/helpers/statements.ts +8 −2
@@ -31,16 +31,22 @@ const RUNS = 5;
3131
3232 type Door = { query: unknown };
3333
34 /** Run `work` once with the statement counter on; return what it cost. */
34 /**
35 * Run `work` once with the statement counter on; return what it cost. With
36 * `counts`, only the statements it says yes to are counted (the request's own,
37 * see `helpers/work.ts`): noise from elsewhere in the process is then never
38 * added, not only dropped after the fact.
39 */
3540 export async function once(
3641 db: Database,
3742 work: () => Promise<void> | void,
43 counts?: () => boolean,
3844 ): Promise<number> {
3945 const door = db as unknown as Door;
4046 const original = db.query.bind(db);
4147 let count = 0;
4248 door.query = (sql: string) => {
43 count++;
49 if (counts === undefined || counts()) count++;
4450 return original(sql);
4551 };
4652 try {
test/helpers/work.ts +41 −4
@@ -9,7 +9,8 @@
99 */
1010 import type { Database } from "bun:sqlite";
1111 import { expect } from "bun:test";
12 import { gitRecord } from "../../src/perf/live.ts";
12 import { AsyncLocalStorage } from "node:async_hooks";
13 import { gitRecord, inFlight } from "../../src/perf/live.ts";
1314 import { once, statements } from "./statements.ts";
1415
1516 /** The fewest SQL statements one request for `url` costs (server and test share `db`). */
@@ -52,27 +53,63 @@ export function parsePhases(header: string): Array<{ name: string; ms: number }>
5253 .sort((a, b) => b.ms - a.ms);
5354 }
5455
56 /** The header that marks the one request `pageWork` measures. */
57 const MEASURED = "x-test-measured";
58 /** The request the server is answering, along its async chain (set by `ownRequests`). */
59 const answering = new AsyncLocalStorage<Request>();
60 let owning = false;
61 /** The marks of the measured requests the server opened through `inFlight.during`. */
62 const opened = new Set<string>();
63
64 /**
65 * Runs every request the server answers inside `answering`, so a statement can
66 * tell whose it is. The server opens each request with `inFlight.during`
67 * (`http/server.ts`); this wraps that one door, once, and changes nothing it
68 * does.
69 */
70 function ownRequests(): void {
71 if (owning) return;
72 owning = true;
73 const during = inFlight.during.bind(inFlight);
74 inFlight.during = (key, at, work) => {
75 const mark = key.headers.get(MEASURED);
76 if (mark !== null) opened.add(mark);
77 return during(key, at, () => answering.run(key, work));
78 };
79 }
80
5581 /**
5682 * Walks one URL warm: a first request fills the caches, a second is measured
5783 * (statements, git spawns, Server-Timing) with no wait for rest, so a sweep of
58 * every page stays in seconds. Stray background work only raises a count.
84 * every page stays in seconds. Only the measured request's own statements are
85 * counted (#15924): a worker's tick or an earlier request's tail running
86 * beside it on a loaded machine is not the page's work.
5987 */
6088 export async function pageWork(db: Database, url: string, init?: RequestInit): Promise<PageWork> {
89 ownRequests();
6190 await (await fetch(url, init)).arrayBuffer();
6291 let status = 0;
6392 let header = "";
6493 let ms = 0;
6594 let git = Number.POSITIVE_INFINITY;
95 const mark = crypto.randomUUID();
96 const headers = new Headers(init?.headers);
97 headers.set(MEASURED, mark);
98 const measured = { ...init, headers };
99 const mine = () => answering.getStore()?.headers.get(MEASURED) === mark;
66100 const count = await once(db, async () => {
67101 const g = await gitSpawns(async () => {
68102 const t = performance.now();
69 const res = await fetch(url, init);
103 const res = await fetch(url, measured);
70104 await res.arrayBuffer();
71105 ms = performance.now() - t;
72106 status = res.status;
73107 header = res.headers.get("server-timing") ?? "";
74108 });
75109 git = Math.min(git, g);
76 });
110 }, mine);
111 // A server that stops answering through `inFlight.during` would count nothing and pass every
112 // budget: say so instead.
113 if (!opened.delete(mark)) throw new Error(`pageWork: ${url} was not answered through inFlight.during, so its statements cannot be told from the process's`);
77114 return { status, statements: count, git, phases: parsePhases(header), ms };
78115 }
test/page-work-own.test.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * `pageWork` counts the measured request's own statements and nobody else's
3 * (#15924). A worker ticking beside the request on a loaded check machine
4 * used to raise a page past its budget on pulls that had not touched it;
5 * here a background loop queries the same database throughout the request,
6 * and the count is still the handler's three.
7 */
8 import { Database } from "bun:sqlite";
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { inFlight } from "../src/perf/live.ts";
11 import { pageWork } from "./helpers/work.ts";
12
13 const db = new Database(":memory:");
14 let noise: ReturnType<typeof setInterval>;
15 let server: ReturnType<typeof Bun.serve>;
16 let bypass: ReturnType<typeof Bun.serve>;
17
18 /** Waiters for the background loop's next ticks. */
19 let waiting: Array<() => void> = [];
20 /** Resolves after the background loop has queried `n` more times. */
21 async function ticks(n: number): Promise<void> {
22 for (let i = 0; i < n; i++) await new Promise<void>((resolve) => waiting.push(resolve));
23 }
24 function tick(): void {
25 db.query("SELECT 'worker tick'").get();
26 const now = waiting;
27 waiting = [];
28 for (const resolve of now) resolve();
29 }
30
31 /** The page: three statements, with the background loop querying between them. */
32 async function page(): Promise<Response> {
33 db.query("SELECT 1").get();
34 await ticks(5);
35 db.query("SELECT 2").get();
36 await ticks(5);
37 db.query("SELECT 3").get();
38 return new Response("ok");
39 }
40
41 beforeAll(() => {
42 // Opened the way `http/server.ts` opens every request.
43 server = Bun.serve({ port: 0, fetch: (request) => inFlight.during(request, performance.now(), page) });
44 // A server that skips that door: its statements cannot be told apart, so the helper refuses.
45 bypass = Bun.serve({ port: 0, fetch: () => page() });
46 noise = setInterval(tick, 1);
47 });
48 afterAll(() => {
49 clearInterval(noise);
50 server.stop(true);
51 bypass.stop(true);
52 db.close();
53 });
54
55 test("a background worker's statements during the request are not the page's", async () => {
56 const w = await pageWork(db, `http://localhost:${server.port}/`);
57 expect(w.status).toBe(200);
58 expect(w.statements).toBe(3);
59 });
60
61 test("a request not opened through inFlight.during is refused, never counted as zero", async () => {
62 await expect(pageWork(db, `http://localhost:${bypass.port}/`)).rejects.toThrow("inFlight.during");
63 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs