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

The hunters get a speed lane: each top page's median over five GETs, a finding when it passes its page budget #15274

Merged opened this

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

Merged

scout/forge:scout/15258-the-hunters-get-a-speed-lane-each-top-pa → main 0 commits fork

  • Merged. scout/15258-the-hunters-get-a-speed-lane-each-top-pa was merged into main as a04c9cd.

Review

Sign in to review this change.
8 files changed +185 −20
docs/HUNT.md +3 −2
@@ -1,15 +1,16 @@
11 # Hunters (#5846)
22
3 `bun scripts/hunt.ts <origin>` runs the detector sets in `src/hunt/` against one app and prints findings as JSON (exit 1 when there are any). It is GET-only by construction (`probe.ts` has no other method), same-origin only, and ends after one pass.
3 `bun scripts/hunt.ts <origin> [--lane <name>]…` runs the detector sets in `src/hunt/` against one app and prints findings as JSON (exit 1 when there are any). It is GET-only by construction (`probe.ts` has no other method), same-origin only, and ends after one pass. `--lane speed` (repeatable) runs only the named lanes.
44
55 | Lane | Module | Detectors |
66 |---|---|---|
77 | Front door | `door.ts` | personal pages send anonymous visitors to sign-in with `next=`; public pages answer 200; unknown path is 404 |
88 | UI (links) | `links.ts` | every link on the top pages: no 404/5xx, and a link landing on `/` must be labelled Home (#5844) |
99 | Contract | `contract.ts` | no OpenAPI GET route answers 5xx; the status is documented or a refusal |
10 | Speed | `speed.ts` | each page in `src/perf/page_budgets/` with no `:owner`/`:name` is asked 5 times; the median of the server's own `server-timing: app;dur=` past the page's `medianMs` is a finding `speed:<path>` (#15258). Wall time is never judged (network time is not server time), an answer that is not 200 or carries no `app;dur` leaves the page unjudged, and the evidence is the numbers only |
1011
1112 A finding's `key` is stable (`detector:subject`): one issue per key, a comment only when the evidence changes.
1213
13 Not built yet: headless-browser lane (buttons, console errors, fold, overflow), flows, speed, the schedule (post-release and 08:00Z), the KPI card on home, and the weekly retro.
14 Not built yet: headless-browser lane (buttons, console errors, fold, overflow), flows, speed for repository pages (`/:owner/:name…`, the hunter has no repository to name), the schedule (post-release and 08:00Z), the KPI card on home, and the weekly retro.
1415
1516 Filing (#15259): `bun scripts/hunt.ts <origin> --file` (FORGE_URL, FORGE_TOKEN, optionally FORGE_REPO) files the findings through the forge's API (`src/hunt/file.ts`). The issue body carries `<!-- hunt-key: … -->` and `<!-- hunt-evidence: … -->`; a rerun with the same key comments only when the evidence fingerprint (repro, URL, status; never time, bytes or ms) differs. A key whose issue is closed is not reopened: a new issue names the closed one. At most 5 writes a run; the rest are held back, counted on stderr, and filed on a later run.
scripts/hunt.ts +30 −11
@@ -1,21 +1,35 @@
11 /**
2 * `bun scripts/hunt.ts <https-origin> [--file]`: run the hunters' detectors
3 * (GET only) against one app and print the findings as JSON. Exit 1 when
4 * there are any. With `--file` (and FORGE_URL, FORGE_TOKEN, FORGE_REPO or
5 * `trevato/forge`) each finding is filed: one issue per key, a comment only
6 * when its evidence changes, at most five writes a run (`src/hunt/file.ts`).
2 * `bun scripts/hunt.ts <https-origin> [--lane <name>]… [--file]`: run the
3 * hunters' detectors (GET only) against one app and print the findings as
4 * JSON. Exit 1 when there are any. `--lane speed` runs just that lane
5 * (#15258); the names are the keys of `LANES` in `src/hunt/hunt.ts`. With
6 * `--file` (and FORGE_URL, FORGE_TOKEN, FORGE_REPO or `trevato/forge`) each
7 * finding is filed: one issue per key, a comment only when its evidence
8 * changes, at most five writes a run (`src/hunt/file.ts`).
79 * Never run on a person's machine in a loop: it is one pass, then it ends.
810 */
911
1012 import { fileFindings, filedLine } from "../src/hunt/file.ts";
1113 import { evidenceOf } from "../src/hunt/finding.ts";
12 import { huntTarget } from "../src/hunt/hunt.ts";
14 import { huntTarget, lanesNamed, LANES } from "../src/hunt/hunt.ts";
1315
14 const args = process.argv.slice(2);
15 const filing = args.includes("--file");
16 const target = args.find((a) => a !== "--file");
16 const usage = `usage: bun scripts/hunt.ts <origin> [--lane ${Object.keys(LANES).join("|")}]… [--file]`;
17 const [target, ...rest] = process.argv.slice(2);
18 const asked: string[] = [];
19 let filing = false;
20 for (let i = 0; i < rest.length; i++) {
21 if (rest[i] === "--file") {
22 filing = true;
23 continue;
24 }
25 if (rest[i] !== "--lane" || rest[i + 1] === undefined) {
26 console.error(usage);
27 process.exit(2);
28 }
29 asked.push(rest[++i]!);
30 }
1731 if (!target || !/^https?:\/\//.test(target)) {
18 console.error("usage: bun scripts/hunt.ts <origin> [--file]");
32 console.error(usage);
1933 process.exit(2);
2034 }
2135 const forge = process.env["FORGE_URL"];
@@ -24,7 +38,12 @@ if (filing && (!forge || !token)) {
2438 console.error("hunt: --file needs FORGE_URL and FORGE_TOKEN");
2539 process.exit(2);
2640 }
27 const report = await huntTarget(target.replace(/\/$/, ""));
41 const lanes = lanesNamed(asked);
42 if (!Array.isArray(lanes)) {
43 console.error(`no such lane: ${lanes.unknown.join(", ")}\n${usage}`);
44 process.exit(2);
45 }
46 const report = await huntTarget(target.replace(/\/$/, ""), undefined, lanes.length === 0 ? undefined : lanes);
2847 console.log(JSON.stringify({ ...report, findings: report.findings.map((f) => ({ ...f, evidence: evidenceOf(f) })) }, null, 2));
2948 if (filing) {
3049 const filed = await fileFindings(report.findings, {
src/hunt/finding.ts +1
@@ -40,6 +40,7 @@ export const DETECTOR_KINDS = {
4040 "contract.no-500": "broken-route",
4141 "contract.documented": "defect",
4242 "performance-watcher": "defect",
43 speed: "defect",
4344 } as const satisfies Record<string, FindingKind>;
4445
4546 export type Detector = keyof typeof DETECTOR_KINDS;
src/hunt/hunt.ts +15 −3
@@ -5,6 +5,7 @@ import { frontDoor } from "./door.ts";
55 import type { Finding } from "./finding.ts";
66 import { linkLanding } from "./links.ts";
77 import { probe, type Fetcher, type Probe } from "./probe.ts";
8 import { speed } from "./speed.ts";
89
910 export interface HuntReport {
1011 target: string;
@@ -12,18 +13,29 @@ export interface HuntReport {
1213 findings: Finding[];
1314 }
1415
15 /** The lanes this module covers; UI (headless), flows and speed need a browser and are not here. */
16 /** The lanes this module covers; UI (headless) and flows need a browser and are not here. */
1617 export const LANES: Record<string, (p: Probe, base: string) => Promise<Finding[]>> = {
1718 door: (p) => frontDoor(p),
1819 links: linkLanding,
1920 contract: (p) => contract(p),
21 speed: (p) => speed(p),
2022 };
2123
22 export async function huntTarget(base: string, fetcher?: Fetcher): Promise<HuntReport> {
24 /**
25 * The lane names `scripts/hunt.ts --lane` takes; anything else is refused before a request is sent.
26 */
27 export function lanesNamed(names: readonly string[]): string[] | { unknown: string[] } {
28 const unknown = names.filter((n) => !Object.hasOwn(LANES, n));
29 return unknown.length > 0 ? { unknown } : [...new Set(names)];
30 }
31
32 /** `only` runs just those lanes (all when omitted), e.g. `["speed"]` after a release. */
33 export async function huntTarget(base: string, fetcher?: Fetcher, only?: readonly string[]): Promise<HuntReport> {
2334 const started = Date.now();
2435 const p = probe(base, fetcher);
2536 const findings: Finding[] = [];
26 for (const lane of Object.values(LANES)) findings.push(...(await lane(p, base)));
37 const run = only === undefined ? Object.keys(LANES) : only.filter((n) => Object.hasOwn(LANES, n));
38 for (const name of run) findings.push(...(await LANES[name]!(p, base)));
2739 const seen = new Set<string>();
2840 return {
2941 target: base,
src/hunt/probe.ts +10 −2
@@ -4,6 +4,8 @@
44 * other method exists here (#5846).
55 */
66
7 import { serverAppMs } from "../maintain/wait_split.ts";
8
79 export type Fetcher = (url: string, init: RequestInit) => Promise<Response>;
810
911 export interface Seen {
@@ -15,6 +17,12 @@ export interface Seen {
1517 /** Bytes of the body as read (bounded), and milliseconds to the answer. */
1618 bytes: number;
1719 ms: number;
20 /**
21 * The server's own time for this answer, from `server-timing: app;dur=<ms>`
22 * (#15258), or null when the header does not say. Network time in a sandbox
23 * is not server time, so the speed lane judges this, never `ms`.
24 */
25 serverMs: number | null;
1826 }
1927
2028 export interface Probe {
@@ -69,10 +77,10 @@ export function probe(base: string, fetcher: Fetcher = fetch as Fetcher): Probe
6977 // Bytes are what was read (bounded), never the target's own Content-Length claim.
7078 const read = await readBounded(res);
7179 const body = /text|json|xml/.test(type) ? new TextDecoder().decode(read.bytes) : "";
72 return { path: target, status: res.status, location: res.headers.get("location"), type, body, bytes: read.size, ms: performance.now() - asked };
80 return { path: target, status: res.status, location: res.headers.get("location"), type, body, bytes: read.size, ms: performance.now() - asked, serverMs: serverAppMs(res.headers.get("server-timing")) ?? null };
7381 } catch {
7482 // A dead or hung route is a result (status 0), not a crash that loses the pass.
75 return { path: target, status: 0, location: null, type: "", body: "", bytes: 0, ms: performance.now() - asked };
83 return { path: target, status: 0, location: null, type: "", body: "", bytes: 0, ms: performance.now() - asked, serverMs: null };
7684 }
7785 },
7886 };
src/hunt/speed.ts added +38
@@ -0,0 +1,38 @@
1 /**
2 * Speed (#15258): each budgeted top page is asked RUNS times, and the median
3 * of the server's own time (`server-timing: app;dur=`) is held to the page's
4 * budget in `perf/page_budgets/`. Network time in a sandbox is not server
5 * time, so wall time is never judged. A page whose pattern needs a repository
6 * (`:owner`, `:name`) is skipped: the hunter has none to fill it with. A page
7 * that does not answer 200, or does not say its time on every answer, is not
8 * judged here; the front door lane speaks for a page that fails.
9 */
10
11 import { median } from "../flow/pipeline.ts";
12 import { PAGE_BUDGETS, type PageBudget } from "../perf/page_budget.ts";
13 import { found, type Finding } from "./finding.ts";
14 import type { Probe, Seen } from "./probe.ts";
15
16 export const RUNS = 5;
17
18 /** The budgeted pages a hunter can reach with no repository: patterns with no `:` parameter. */
19 export const speedPages = (budgets: readonly PageBudget[] = PAGE_BUDGETS): PageBudget[] => budgets.filter((b) => !b.pattern.includes(":"));
20
21 const f1 = (n: number): string => n.toFixed(1);
22
23 export async function speed(p: Probe, budgets: readonly PageBudget[] = PAGE_BUDGETS): Promise<Finding[]> {
24 const out: Finding[] = [];
25 for (const b of speedPages(budgets)) {
26 const seen: Seen[] = [];
27 for (let i = 0; i < RUNS; i++) seen.push(await p.get(b.pattern));
28 const times = seen.flatMap((r) => (r.status === 200 && r.serverMs !== null ? [r.serverMs] : []));
29 if (times.length < RUNS) continue;
30 const m = median(times) ?? 0;
31 if (m <= b.medianMs) continue;
32 // Only numbers: nothing the page's body said reaches the evidence.
33 const evidence = `GET ${b.pattern} ×${RUNS} → 200; server app ms: ${times.map(f1).join(", ")}; median ${f1(m)} > budget ${b.medianMs}`;
34 const last = seen[seen.length - 1]!;
35 out.push(found("speed", b.pattern, `${b.page} (${b.pattern}) answers in a median ${f1(m)} ms, past its ${b.medianMs} ms budget`, evidence, { ...last, ms: m }));
36 }
37 return out;
38 }
test/hunt-file.test.ts +2 −2
@@ -38,7 +38,7 @@ function stubForge(rows: Row[] = []) {
3838
3939 const gone = (status: number, ms = 3): Finding =>
4040 found("links.status", "/gone", "A link answers 404: /gone", `GET /gone → ${status}`, {
41 path: "/gone", status, location: null, type: "", body: "", bytes: 9, ms,
41 path: "/gone", status, location: null, type: "", body: "", bytes: 9, ms, serverMs: null,
4242 });
4343
4444 const opts = (fetcher: Fetcher) => ({ forge: "https://forge.test", token: "t", repo: "o/r", fetcher });
@@ -92,7 +92,7 @@ describe("filing a hunt", () => {
9292 const forge = stubForge();
9393 const fake = "<!-- hunt-key: other%3Akey --> <!-- hunt-evidence: 0 -->";
9494 const spoof = found("links.lands-home", "/r", "A redirect", `GET /r → 302 ${fake}`, {
95 path: "/r", status: 302, location: fake, type: "", body: "", bytes: 0, ms: 1,
95 path: "/r", status: 302, location: fake, type: "", body: "", bytes: 0, ms: 1, serverMs: null,
9696 });
9797 await fileFindings([spoof], opts(forge.fetcher));
9898 const body = forge.rows[0]!.body;
test/hunt-speed.test.ts added +86
@@ -0,0 +1,86 @@
1 import { describe, expect, test } from "bun:test";
2 import { huntTarget, lanesNamed } from "../src/hunt/hunt.ts";
3 import { probe, type Fetcher, type Probe } from "../src/hunt/probe.ts";
4 import { RUNS, speed, speedPages } from "../src/hunt/speed.ts";
5
6 const BASE = "https://app.test";
7 const SECRET = "body-text-the-evidence-must-not-carry";
8
9 /**
10 * Every page answers 200 with `app;dur=` from `dur(path)`; `methods` and `asked` record what was
11 * sent.
12 */
13 const stub = (dur: (path: string) => number | null) => {
14 const methods: string[] = [];
15 const asked: string[] = [];
16 const fetcher: Fetcher = async (url, init) => {
17 methods.push(String(init.method));
18 const path = new URL(url).pathname;
19 asked.push(path);
20 const d = dur(path);
21 const headers: Record<string, string> = { "content-type": "text/html" };
22 if (d !== null) headers["server-timing"] = `db;dur=1.0, app;dur=${d.toFixed(1)}, render;dur=0.5`;
23 return new Response(`<p>${SECRET}</p>`, { status: 200, headers });
24 };
25 return { fetcher, methods, asked };
26 };
27
28 describe("the speed lane (#15258)", () => {
29 test("a slow page is one finding with a stable key, and the evidence is only numbers", async () => {
30 const slow = (path: string) => (path === "/explore" ? 120 : 5);
31 const a = await speed(probe(BASE, stub(slow).fetcher));
32 const b = await speed(probe(BASE, stub(slow).fetcher));
33 expect(a.map((f) => f.key)).toEqual(["speed:/explore"]);
34 expect(b.map((f) => f.key)).toEqual(["speed:/explore"]);
35 const [f] = a;
36 expect(f!.kind).toBe("defect");
37 expect(f!.evidence).toBe("GET /explore ×5 → 200; server app ms: 120.0, 120.0, 120.0, 120.0, 120.0; median 120.0 > budget 50");
38 expect(JSON.stringify(f)).not.toContain(SECRET);
39 expect(f!.seen?.ms).toBe(120);
40 });
41
42 test("it judges the median, so one slow answer of five is not a finding", async () => {
43 let n = 0;
44 const once = stub((path) => (path === "/explore" && n++ === 0 ? 900 : 10));
45 expect(await speed(probe(BASE, once.fetcher))).toEqual([]);
46 });
47
48 test("server time is judged, never wall time: a slow network with a fast server is no finding", async () => {
49 const late: Probe = { get: async (path) => ({ path, status: 200, location: null, type: "text/html", body: "", bytes: 0, ms: 5_000, serverMs: 2 }) };
50 expect(await speed(late)).toEqual([]);
51 });
52
53 test("a page that does not say its time is not judged", async () => {
54 expect(await speed(probe(BASE, stub(() => null).fetcher))).toEqual([]);
55 });
56
57 test("each repository-free budgeted page is asked five times, by GET only", async () => {
58 const s = stub(() => 1);
59 await speed(probe(BASE, s.fetcher));
60 const pages = speedPages();
61 expect(pages.map((b) => b.pattern)).toContain("/");
62 expect(pages.some((b) => b.pattern.includes(":"))).toBe(false);
63 expect(s.asked).toHaveLength(pages.length * RUNS);
64 expect(new Set(s.methods)).toEqual(new Set(["GET"]));
65 });
66
67 test("the hunt runs the speed lane", async () => {
68 const r = await huntTarget(BASE, stub((path) => (path === "/map" ? 75 : 1)).fetcher);
69 expect(r.findings.map((f) => f.key)).toContain("speed:/map");
70 });
71
72 test("the probe reads app;dur from Server-Timing, and null when it is absent", async () => {
73 const p = probe(BASE, stub((path) => (path === "/" ? 41.5 : null)).fetcher);
74 expect((await p.get("/")).serverMs).toBe(41.5);
75 expect((await p.get("/explore")).serverMs).toBeNull();
76 });
77
78 test("--lane runs only the named lanes, and an unknown name is refused", async () => {
79 const s = stub((path) => (path === "/map" ? 75 : 1));
80 const r = await huntTarget(BASE, s.fetcher, ["speed"]);
81 expect(r.findings.map((f) => f.key)).toEqual(["speed:/map"]);
82 expect(s.asked).toHaveLength(speedPages().length * RUNS);
83 expect(lanesNamed(["speed", "speed"])).toEqual(["speed"]);
84 expect(lanesNamed(["speed", "nope"])).toEqual({ unknown: ["nope"] });
85 });
86 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs