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

perfRecord, loopWatch, stallBlame and lagMinutes belong to a forge, so page-budget and perf-server-hook stop failing in a full gate #12667

Closed opened this
Closed without merging

scout/forge:scout/12615-perfrecord-loopwatch-stallblame-and-lagm → main 7 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
30 files changed +238 −122
src/apps/proxy.ts +2 −2
@@ -70,7 +70,7 @@ import { holdPortRequest, holdPortSocket } from "./handoff.ts";
7070 import { secureFor } from "../http/cookie_secure.ts";
7171 import { currentLoopLag, forgeWaited, LAG_WINDOW_MS } from "../perf/loop_worst.ts";
7272 import { HOOK_MAX_BYTES, HOOK_PREFIX, hookPath, readCapped } from "./hook_relay.ts";
73 import { loopWatch } from "../perf/live.ts";
73 import { perfOf } from "../perf/live.ts";
7474 import { heldBy, noteRelayWait, stallTiming } from "./relay_wait.ts";
7575 import { cspNonce, htmlAnswer, readPage, rewritable, TOOLBAR_ASSET_PATH, TOOLBAR_ASSET_PREFIX, toolbarResponse, withToolbar, type PillWhere } from "./toolbar.ts";
7676
@@ -533,7 +533,7 @@ function relayUpstream(
533533 // What held a wait that was the forge's (#11000): the stalls of the lag's
534534 // window, read only then — at most 40 of them, so the common relay pays nothing.
535535 const now = performance.now();
536 const held = forgeWaited(lag, headersMs) ? heldBy(loopWatch.within(now - LAG_WINDOW_MS, now)) : [];
536 const held = forgeWaited(lag, headersMs) ? heldBy(perfOf(runtime.app).loopWatch.within(now - LAG_WINDOW_MS, now)) : [];
537537 // Production's slowest wait, for the app's speed card (`apps/relay_wait.ts`).
538538 if (target.env === "production") noteRelayWait(target.app.id, headersMs, lag, Date.now(), held);
539539 if (held.length > 0 && forgeAdmin(runtime, who)) stallFor.set(request, stallTiming(held));
src/http/api.ts +1 −1
@@ -3523,7 +3523,7 @@ export function apiRoutes(router: Router<Handler>): void {
35233523 router.add("GET", "/metrics", (ctx) => {
35243524 const denied = accountAdmin(ctx, "ro");
35253525 if (denied) return denied;
3526 return new Response(egressMetrics(egressRowsFor(ctx.app), egressTotalsFor(ctx.app)) + forgeMetrics(ctx.app.db, appSources(ctx.app)), {
3526 return new Response(egressMetrics(egressRowsFor(ctx.app), egressTotalsFor(ctx.app)) + forgeMetrics(ctx.app.db, appSources(ctx.app), Date.now(), ctx.app), {
35273527 headers: {
35283528 "content-type": "text/plain; version=0.0.4; charset=utf-8",
35293529 "cache-control": "no-store",
src/http/mcp/tools/system.ts +4 −4
@@ -4,7 +4,7 @@ import { scriptErrorCounts } from "../../script_errors.ts";
44 import { violationsByDirective, windowStart } from "../../csp_report.ts";
55 import { countRead } from "../../../system/telemetry_reads.ts";
66 import { stallHour, TOP_ROUTES } from "../../../metrics/stalls.ts";
7 import { lagMinutes, loopWatch, perfRecord } from "../../../perf/live.ts";
7 import { perfOf } from "../../../perf/live.ts";
88 import { LAG_BAR_MS, overBar } from "../../../perf/lag_minutes.ts";
99 import { slowestRoutes } from "../../../perf/watch.ts";
1010 import { footing, riskLines } from "../../../system/footing.ts";
@@ -28,7 +28,7 @@ export const tool: Tool = {
2828 const reader = telemetryReader(ctx.app, user);
2929 if (!reader) return bad("forbidden", "only an admin of this forge, or an agent granted telemetry:read, reads its route timings");
3030 noteRead(ctx.app, user, reader, "system");
31 return good({ routes: slowestRoutes(perfRecord, Date.now()) });
31 return good({ routes: slowestRoutes(perfOf(ctx.app).perfRecord, Date.now()) });
3232 }
3333 if (args["kind"] === "size") {
3434 const reader = telemetryReader(ctx.app, user);
@@ -63,11 +63,11 @@ export const tool: Tool = {
6363 noteRead(ctx.app, user, reader, "system");
6464 const out = systemWithReaders(ctx.app, reader);
6565 countRead("system", user.username);
66 const stalls = stallHour(loopWatch.tally(performance.now()))
66 const stalls = stallHour(perfOf(ctx.app).loopWatch.tally(performance.now()))
6767 .slice(0, TOP_ROUTES)
6868 .map((r) => ({ cause: r.route, ms: Math.round(r.ms), count: r.count }));
6969 // The same 20 minutes /system draws (#11220); `what` is null when no stall past 200 ms was named.
70 const rows = lagMinutes.readings();
70 const rows = perfOf(ctx.app).lagMinutes.readings();
7171 const readings = rows.map((r) => ({ at: new Date(r.at).toISOString(), ms: Math.round(r.ms * 10) / 10, what: r.what }));
7272 // At most 0.8 s on the walk (#11800); the last measurement, or null, when it is slower.
7373 const largest = await largestDirs.read(ctx.app.config.dataDir);
src/http/server.ts +8 −5
@@ -553,7 +553,7 @@ import {
553553 takeDbTime,
554554 type RouteTiming,
555555 } from "../core/route_timing.ts";
556 import { captureStore, inFlight, loopWatch, perfRecord, readLedger, stallBlame } from "../perf/live.ts";
556 import { captureStore, inFlight, perfOf, readLedger } from "../perf/live.ts";
557557 import { childLabel, markChildRequest, noteChildRequest } from "../perf/child_time.ts";
558558 import { parseHostedChildName } from "../spawn/placement.ts";
559559 import { childHost } from "../spawn/door.ts";
@@ -2674,8 +2674,11 @@ export async function serve(app: App): Promise<Servers> {
26742674 // map increment; a refused event would be a programming error, not worth a 500.
26752675 const counters = new Map<Database, UsageCounter>();
26762676 const timings = new Map<Database, RouteTiming>();
2677 // This forge's own record and loop watch (#12615), looked up once:
2678 // a request pays a property read.
2679 const perf = perfOf(app);
26772680 // The minute ledger's history: one write a minute, never on a request.
2678 const trafficWriter = createTrafficWriter(app.db, perfRecord.ledger, app.log);
2681 const trafficWriter = createTrafficWriter(app.db, perf.perfRecord.ledger, app.log);
26792682 // Page views are buffered by the beacon doors and written here; GitHub's traffic is pulled daily when a token is set.
26802683 const viewWriter = createViewWriter(app.db, app.log);
26812684 const githubPull = startGithubPull(app.db, app.log);
@@ -2710,7 +2713,7 @@ export async function serve(app: App): Promise<Servers> {
27102713 response.headers.set("server-timing", tag.role === "admin" ? withLag(header, currentLoopLag()) : header);
27112714 const end = performance.now();
27122715 const family = familyOf(request.headers.get("user-agent") ?? "");
2713 perfRecord.add(
2716 perf.perfRecord.add(
27142717 tag.pattern,
27152718 { at: Date.now(), ms, signedIn: tag.role !== "anon" && tag.role !== "crawler", crawler: wasCrawler(request), deepStranger: wasDeepStranger(request), internal: wasInternal(request), refused: response.status === 429 || wasShielded(request), phases: parseServerTiming(header) },
27162719 {
@@ -2721,7 +2724,7 @@ export async function serve(app: App): Promise<Servers> {
27212724 repo: response.status < 400 ? repoOf(tag.pattern, new URL(request.url).pathname) : null,
27222725 },
27232726 );
2724 loopWatch.finished(hostedChild === undefined ? tag.pattern : childLabel(hostedChild), started, end);
2727 perf.loopWatch.finished(hostedChild === undefined ? tag.pattern : childLabel(hostedChild), started, end);
27252728 if (hostedChild !== undefined) noteChildRequest(hostedChild, ms);
27262729 // Evidence of what was read, and the running capture, if any (never a signed-in person's).
27272730 const signedIn = tag.role !== "anon" && tag.role !== "crawler";
@@ -3102,7 +3105,7 @@ async function answerGet(
31023105 () => app.db.query("select 1").get(),
31033106 app.log,
31043107 wantsJson ? currentLoopLag() : undefined,
3105 wantsJson ? (stallBlame.worst(performance.now(), LAG_WINDOW_MS, 1)[0]?.what ?? null) : null,
3108 wantsJson ? (perfOf(app).stallBlame.worst(performance.now(), LAG_WINDOW_MS, 1)[0]?.what ?? null) : null,
31063109 );
31073110 noteDbTime(request, performance.now() - dbStart);
31083111 // The release proof learns which release answered, old pod or new; a
src/main.ts +7 −7
@@ -132,7 +132,7 @@ import { watchStalls } from "./kernel/loop_lag.ts";
132132 import { startPerfWatcher, TICK_MS } from "./perf/duty.ts";
133133 import { during } from "./perf/jobs.ts";
134134 import { stallLine } from "./perf/loop.ts";
135 import { bootStall, gitRecord, lagMinutes, loopWatch, perfRecord, stallBlame } from "./perf/live.ts";
135 import { adoptPerf, bootStall, createPerf, gitRecord, noteWake } from "./perf/live.ts";
136136 import { keepFlowReadings, KEPT_MS } from "./flow/kept.ts";
137137 import { startKeeping } from "./flow/keep.ts";
138138 import { keepForgePages } from "./flow/pages.ts";
@@ -269,13 +269,12 @@ if (parentProblem !== null) {
269269 // second is a warning that names its minute (kernel/loop_lag.ts, #6957),
270270 // draining included.
271271 const loopLog = createLog("loop");
272 // The forge's own readings (#12615), begun before it exists and adopted once it does.
273 const perf = createPerf();
272274 watchStalls(loopLog, undefined, undefined, undefined, (late, at) => {
273275 bootStall.note(late, at);
274 lagMinutes.note(late, at);
275 const stall = loopWatch.stalled(late, at);
276 if (stall === null) return;
277 loopLog.warn(stallLine(stall));
278 stallBlame.note(stall);
276 const stall = noteWake(perf, late, at);
277 if (stall !== null) loopLog.warn(stallLine(stall));
279278 });
280279
281280 const previewKey = previewIdentityKey(process.env);
@@ -363,6 +362,7 @@ const app = createApp({
363362 }),
364363 }),
365364 });
365 adoptPerf(app, perf);
366366
367367 // A statement that holds the thread past 200 ms names its caller (#6957).
368368 timeStatements(app.db, createLog("sql"));
@@ -397,7 +397,7 @@ if (readOnly) {
397397 const bootSignup = signupFromEnv(process.env.FORGE_SIGNUP);
398398 if (bootSignup.ok && bootSignup.value !== null)
399399 setSignup(app.db, bootSignup.value, BOOT_ACTOR);
400 startPerfWatcher(app, perfRecord, Date.now, TICK_MS, gitRecord);
400 startPerfWatcher(app, perf.perfRecord, Date.now, TICK_MS, gitRecord);
401401 // A release shipped by hand is recorded as live at boot, so live estimates and the base rate
402402 // resolve whichever way a release ships; estimates of "done" come due as time passes (#11955).
403403 const byHand = recordByHand(app.db);
src/metrics/forge.ts +8 −3
@@ -18,7 +18,7 @@ import type { EnvState } from "../apps/runtime.ts";
1818 import { EDGES_MS, readTotals } from "../core/route_timing.ts";
1919 import { closesFromBody } from "../core/pulls.ts";
2020 import { telemetryReadsFamily } from "../system/telemetry_reads.ts";
21 import { loopWatch } from "../perf/live.ts";
21 import { perfOf } from "../perf/live.ts";
2222 import { stallFamilies } from "./stalls.ts";
2323 import { openMetrics, type Family, type HistogramSample, type Sample } from "./openmetrics.ts";
2424
@@ -329,11 +329,16 @@ export function appFamilies({ apps, cells }: AppSources): Family[] {
329329 ];
330330 }
331331
332 /** The forge's families as Prometheus text (no `# EOF`: the body is `text/plain; version=0.0.4`). */
332 /**
333 * The forge's families as Prometheus text, its stalls its own (#12615)
334 * (no `# EOF`: the body is `text/plain; version=0.0.4`).
335 */
333336 export function forgeMetrics(
334337 db: Database,
335338 sources: AppSources = { apps: [], cells: [] },
336339 now: number = Date.now(),
340 /** Whose stalls (`perfOf`); absent, the scrape reports no stall families. */
341 app?: object,
337342 ): string {
338343 return openMetrics([
339344 durationFamily(db),
@@ -347,6 +352,6 @@ export function forgeMetrics(
347352 askToLiveFamily(db),
348353 mainRedFamily(db, now),
349354 telemetryReadsFamily(),
350 ...stallFamilies(loopWatch.tally(performance.now())),
355 ...(app ? stallFamilies(perfOf(app).loopWatch.tally(performance.now())) : []),
351356 ]).replace(/# EOF\n$/, "");
352357 }
src/perf/crawlers.ts +2 −2
@@ -6,11 +6,11 @@
66
77 import type { App } from "../app.ts";
88 import { crawlRefusalScopes, crawlRefusals } from "../http/crawl.ts";
9 import { perfRecord } from "./live.ts";
9 import { perfOf } from "./live.ts";
1010 import { WINDOW_MS, crawlerShare } from "./record.ts";
1111
1212 export function crawlReport(app: App, now = Date.now()) {
13 const share = crawlerShare(perfRecord, now - WINDOW_MS);
13 const share = crawlerShare(perfOf(app).perfRecord, now - WINDOW_MS);
1414 return {
1515 window_minutes: WINDOW_MS / 60_000,
1616 requests: share.requests,
src/perf/live.ts +64 −15
@@ -1,9 +1,13 @@
1 /** The process's one record, git record (#8158) and loop watch (#7559): what the server feeds and the duty reads. */
1 /**
2 * The process's git record (#8158), in-flight requests and captures, and each
3 * forge's own route record and loop watch (#7559, #12615): what the server
4 * feeds and the duty reads.
5 */
26
37 import { createBootStall } from "./boot_stall.ts";
48 import { createGitRecord } from "./git.ts";
59 import { jobWatch } from "./jobs.ts";
6 import { createLoopWatch } from "./loop.ts";
10 import { createLoopWatch, type Stall } from "./loop.ts";
711 import { createInFlight } from "./in_flight.ts";
812 import { childRequestLabel } from "./child_time.ts";
913 import { patternOf } from "../http/usage_tag.ts";
@@ -13,26 +17,71 @@ import { createStallBlame } from "./stall_blame.ts";
1317 import { createPerfRecord } from "./record.ts";
1418 import { createLagMinutes } from "./lag_minutes.ts";
1519
16 export const perfRecord = createPerfRecord();
1720 /** The requests the server is answering now (#11478): begun and ended around each one in `http/server.ts`. */
1821 export const inFlight = createInFlight<Request>((request) => childRequestLabel(request) ?? patternOf(request));
19 /**
20 * A stall names the requests that ran across it, finished or still in flight
21 * (#11478); when none did, the background jobs that did (#10834). A job that
22 * held the loop for most of a stall is named ahead of the requests that waited
23 * behind it, and a name that only brushed the stall is left out (`loop.ts`).
24 */
25 export const loopWatch = createLoopWatch(undefined, jobWatch.across, inFlight.since, jobWatch.held, jobWatch.awaited);
2622 export const gitRecord = createGitRecord();
2723 /** The worst stall in this process's first five minutes, read by the release keeper (#8848). */
2824 export const bootStall = createBootStall();
2925 /** What was read from repositories (`reads.ts`), and the one bounded capture an admin may run (`capture.ts`). */
3026 export const readLedger = createReadLedger();
3127 export const captureStore = createCaptureStore();
32 /** Each stall over 200 ms with what ran (#11069): the last hour's worst on /system, the last 10 s's on `/healthz`. */
33 export const stallBlame = createStallBlame();
28
3429 /**
35 * The last 20 minutes' worst loop lag (#11220), each blamed on the worst stall
36 * `stallBlame` named in it: /system and the MCP `system` tool read it.
30 * One forge's readings (#12615): its route record, loop watch, stall blame
31 * and lag minutes. One set for the process counted every forge in it as one,
32 * so in a test run one file's slow request was a row in the next file's
33 * /system and page budgets; a hosted child's were its parent's.
34 *
35 * A stall names the requests that ran across it, finished or still in flight
36 * (#11478); when none did, the background jobs that did (#10834). A job that
37 * held the loop for most of a stall is named ahead of the requests that waited
38 * behind it, and a name that only brushed the stall is left out (`loop.ts`).
39 * Each stall over 200 ms with what ran (#11069) is kept in `stallBlame`: the
40 * last hour's worst on /system, the last 10 s's on `/healthz`; `lagMinutes`
41 * holds the last 20 minutes' worst loop lag (#11220), each blamed on the
42 * worst stall `stallBlame` named in it.
3743 */
38 export const lagMinutes = createLagMinutes((to, span) => stallBlame.worst(to, span, 1)[0]?.what ?? null);
44 export interface Perf {
45 readonly perfRecord: ReturnType<typeof createPerfRecord>;
46 readonly loopWatch: ReturnType<typeof createLoopWatch>;
47 readonly stallBlame: ReturnType<typeof createStallBlame>;
48 readonly lagMinutes: ReturnType<typeof createLagMinutes>;
49 }
50
51 export function createPerf(): Perf {
52 const stallBlame = createStallBlame();
53 return {
54 perfRecord: createPerfRecord(),
55 loopWatch: createLoopWatch(undefined, jobWatch.across, inFlight.since, jobWatch.held, jobWatch.awaited),
56 stallBlame,
57 lagMinutes: createLagMinutes((to, span) => stallBlame.worst(to, span, 1)[0]?.what ?? null),
58 };
59 }
60
61 const perfs = new WeakMap<object, Perf>();
62
63 /** This forge's readings, made the first time it is asked for. */
64 export function perfOf(app: object): Perf {
65 let perf = perfs.get(app);
66 if (perf === undefined) perfs.set(app, (perf = createPerf()));
67 return perf;
68 }
69
70 /**
71 * One wake of the loop watcher, `late` ms after it was due: the lag minute,
72 * and the stall it was, if it was one, blamed.
73 */
74 export function noteWake(perf: Perf, late: number, at: number): Stall | null {
75 perf.lagMinutes.note(late, at);
76 const stall = perf.loopWatch.stalled(late, at);
77 if (stall !== null) perf.stallBlame.note(stall);
78 return stall;
79 }
80
81 /**
82 * `main.ts` watches the loop before its forge exists: what it measured from
83 * boot becomes the forge's.
84 */
85 export function adoptPerf(app: object, perf: Perf): void {
86 perfs.set(app, perf);
87 }
src/tui/screens/loopstalls.ts +6 −6
@@ -12,7 +12,7 @@
1212
1313 import { stallHour } from "../../metrics/stalls.ts";
1414 import { HOUR_MS, type RouteStall } from "../../perf/loop.ts";
15 import { lagMinutes, loopWatch, stallBlame } from "../../perf/live.ts";
15 import { perfOf } from "../../perf/live.ts";
1616 import { LAG_BAR_MS, LAG_READINGS, overBar, type LagReading } from "../../perf/lag_minutes.ts";
1717 import { WORST_STALLS, type BlamedStall } from "../../perf/stall_blame.ts";
1818 import type { Ctx, Screen } from "../app/app.ts";
@@ -34,9 +34,9 @@ export interface WorstNow {
3434 readonly wall: number;
3535 }
3636
37 function worstNow(): WorstNow {
37 function worstNow(app: object): WorstNow {
3838 const mono = performance.now();
39 return { rows: stallBlame.worst(mono, HOUR_MS, WORST_STALLS), mono, wall: Date.now() };
39 return { rows: perfOf(app).stallBlame.worst(mono, HOUR_MS, WORST_STALLS), mono, wall: Date.now() };
4040 }
4141
4242 /**
@@ -46,8 +46,8 @@ function worstNow(): WorstNow {
4646 */
4747 export function stallLines(
4848 session: Session,
49 rows: readonly RouteStall[] = stallHour(loopWatch.tally(performance.now())),
50 worst: WorstNow = worstNow(),
49 rows: readonly RouteStall[] = stallHour(perfOf(session.app).loopWatch.tally(performance.now())),
50 worst: WorstNow = worstNow(session.app),
5151 ): string[] {
5252 if (!mayRead(session)) return [];
5353 const col = (s: string) => pad(s, 10, "right");
@@ -71,7 +71,7 @@ export function stallLines(
7171 * start in UTC, its worst ms, `over` when strictly past the bar, and what ran
7272 * (or "not named"). Empty for anyone the gate refuses.
7373 */
74 export function lagLines(session: Session, rows: readonly LagReading[] = lagMinutes.readings()): string[] {
74 export function lagLines(session: Session, rows: readonly LagReading[] = perfOf(session.app).lagMinutes.readings()): string[] {
7575 if (!mayRead(session)) return [];
7676 const head = `Loop lag, last ${String(LAG_READINGS)} minutes`;
7777 if (rows.length === 0) return [head, "No full minute measured yet."];
src/tui/screens/traffic.ts +2 −2
@@ -8,7 +8,7 @@
88 import type { Ctx, Screen } from "../app/app.ts";
99 import { binding } from "../app/keys.ts";
1010 import { trafficShare, TRAFFIC_WORDS } from "../../flow/kpi_words.ts";
11 import { perfRecord } from "../../perf/live.ts";
11 import { perfOf } from "../../perf/live.ts";
1212 import { TRAFFIC_CLASSES } from "../../perf/traffic.ts";
1313 import { trafficHistory } from "../../perf/traffic_store.ts";
1414 import type { Session } from "../session.ts";
@@ -24,7 +24,7 @@ export function trafficScreen(f: Session, ctx: Ctx): Screen {
2424 const state = new ListState();
2525 const lines = (): ListRow[] => {
2626 if (!may(f)) return [];
27 const t = trafficHistory(f.app.db, perfRecord.ledger, Date.now(), "15m");
27 const t = trafficHistory(f.app.db, perfOf(f.app).perfRecord.ledger, Date.now(), "15m");
2828 if (t.requests === 0) return [{ title: "No requests in the last 15 minutes", meta: "each finished minute is written down" }];
2929 const rows: ListRow[] = [
3030 { title: `${t.requests} requests, ${(t.ms / 1000).toFixed(1)} s of answering time`, meta: `${t.refused} refused, about ${t.addresses} client addresses` },
src/web/pages/scrapes.ts +2 −2
@@ -9,7 +9,7 @@
99 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1010 import type { Ctx } from "../../http/context.ts";
1111 import { repoDir } from "../../git/repos.ts";
12 import { perfRecord, captureStore, readLedger } from "../../perf/live.ts";
12 import { perfOf, captureStore, readLedger } from "../../perf/live.ts";
1313 import { groupRequests, type Group } from "../../perf/actors.ts";
1414 import { CAPTURE_MAX, CAPTURE_MS } from "../../perf/capture.ts";
1515 import { networkTable, parseNetworks, saveNetworks, type Network, type NetworkTable } from "../../perf/network.ts";
@@ -154,7 +154,7 @@ export async function scrapesPage(ctx: Ctx): Promise<Response> {
154154 );
155155 }),
156156 );
157 const prefixes = trafficHistory(ctx.app.db, perfRecord.ledger, now, "24h").tops.prefixes;
157 const prefixes = trafficHistory(ctx.app.db, perfOf(ctx.app).perfRecord.ledger, now, "24h").tops.prefixes;
158158 const cap = captureStore.current(now);
159159 const groups = cap === null ? [] : groupRequests(cap.entries).filter((g) => g.size >= 3);
160160 const picked = groups.find((g) => g.id === q.get("group"));
src/web/pages/security.ts +2 −2
@@ -17,7 +17,7 @@ import { readBackup } from "../../flow/kpis.ts";
1717 import type { Ctx } from "../../http/context.ts";
1818 import { violationsByDirective } from "../../http/csp_report.ts";
1919 import { scriptErrorCounts } from "../../http/script_errors.ts";
20 import { perfRecord } from "../../perf/live.ts";
20 import { perfOf } from "../../perf/live.ts";
2121 import { getSignup } from "../../settings/signup.ts";
2222 import { trafficHistory } from "../../perf/traffic_store.ts";
2323 import { lastDrill } from "../../snapshot/drills.ts";
@@ -277,7 +277,7 @@ export function securityPage(ctx: Ctx): Response {
277277 const db = ctx.app.db;
278278 const dataDir = ctx.app.config.dataDir;
279279
280 const traffic = trafficHistory(db, perfRecord.ledger, nowMs, "15m");
280 const traffic = trafficHistory(db, perfOf(ctx.app).perfRecord.ledger, nowMs, "15m");
281281 const wrong = trafficAttention(traffic);
282282 const { admins, adminTokens, added } = peopleRows(db, since, nowIso);
283283 const { backup, backupAt } = readBackup(db, dataDir, nowMs);
src/web/pages/system.ts +4 −4
@@ -37,7 +37,7 @@ import { readerPaces, type ReaderPace } from "../../system/telemetry_reads.ts";
3737 import { slowPageLine, slowPages, type SlowPage } from "../../perf/watch.ts";
3838 import { stallHour } from "../../metrics/stalls.ts";
3939 import { HOUR_MS, type RouteStall } from "../../perf/loop.ts";
40 import { lagMinutes, loopWatch, stallBlame } from "../../perf/live.ts";
40 import { perfOf } from "../../perf/live.ts";
4141 import { childHours, childHourWords, type ChildHour } from "../../perf/child_time.ts";
4242 import { openChildren } from "../../spawn/host.ts";
4343 import { LAG_BAR_MS, LAG_READINGS, overBar, type LagReading } from "../../perf/lag_minutes.ts";
@@ -597,7 +597,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> {
597597 const self = owner ? timePhase(ctx.request, "self", () => selfUse(realSelf(ctx.app.config.dataDir))) : null;
598598 const listed = owner ? await listChildren(ctx.app) : [];
599599 const children = childrenUse(listed, (bodyId) => childDirOf(ctx.app, bodyId));
600 const tally = loopWatch.tally(performance.now());
600 const tally = perfOf(ctx.app).loopWatch.tally(performance.now());
601601 const stalls = timePhase(ctx.request, "stalls", () => stallHour(tally));
602602 // The forges open in this process now, and any that ran here in the hour: each with what it took
603603 // of this thread.
@@ -606,7 +606,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> {
606606 const mine = new Set(listed.map((c) => c.name));
607607 const inProcess = childHours(Date.now(), tally.hour, openChildren(ctx.app).map((c) => c.name)).filter((r) => mine.has(r.name));
608608 const nowMono = performance.now();
609 const worst = stallBlame.worst(nowMono, HOUR_MS, WORST_STALLS);
609 const worst = perfOf(ctx.app).stallBlame.worst(nowMono, HOUR_MS, WORST_STALLS);
610610 // Never waits on the cluster: the last reading, or the declared rows while the first read runs behind.
611611 const standsOn = footing.peek() ?? declaredFooting("the cluster is being read; reload in a moment");
612612 // Never waits on the walk: the last measurement, a new one started behind it when stale.
@@ -655,7 +655,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> {
655655 ${footingSection(standsOn)}
656656 ${offsiteSection(timePhase(ctx.request, "offsite", () => readOffsiteLane(ctx.app.config.dataDir, ctx.app.db)))}
657657 ${featuresSection(timePhase(ctx.request, "features", () => featureHealth(ctx.app, reader)))}
658 ${lagSection(lagMinutes.readings())}
658 ${lagSection(perfOf(ctx.app).lagMinutes.readings())}
659659 <div id="sys-stalls">${stallSection(stalls, worstStallsTable(worst, nowMono, Date.now()))}</div>
660660 ${owner ? askingSection(askingOf(ctx.app).heavy(), turnStatsOf(ctx.app)) : html``}
661661 <div id="sys-slow-pages">${slowPagesSection(timePhase(ctx.request, "slowpages", () => slowPagesCached(ctx.app.db)))}</div>
src/web/pages/traffic.ts +2 −2
@@ -14,7 +14,7 @@ import {
1414 trafficShare,
1515 TRAFFIC_WORDS,
1616 } from "../../flow/kpi_words.ts";
17 import { perfRecord } from "../../perf/live.ts";
17 import { perfOf } from "../../perf/live.ts";
1818 import {
1919 TRAFFIC_CLASSES,
2020 type TopRow,
@@ -118,7 +118,7 @@ export function trafficPage(ctx: Ctx): Response {
118118 const rendering = performance.now();
119119 const now = Date.now();
120120 const chosen = windowOf(new URL(ctx.request.url).searchParams.get("window"));
121 const t = trafficHistory(ctx.app.db, perfRecord.ledger, now, chosen);
121 const t = trafficHistory(ctx.app.db, perfOf(ctx.app).perfRecord.ledger, now, chosen);
122122 const tops = t.tops;
123123 const wrong = trafficAttention(t);
124124 const span = TRAFFIC_WINDOWS[chosen].words;
src/web/studio/kpi_probe.ts +2 −2
@@ -39,7 +39,7 @@ import {
3939 visitorsValue,
4040 } from "../../flow/kpi_words.ts";
4141 import { HOURS, median } from "../../flow/throughput.ts";
42 import { perfRecord } from "../../perf/live.ts";
42 import { perfOf } from "../../perf/live.ts";
4343 import { scanTraffic, type PerfRecord } from "../../perf/record.ts";
4444 import { TRAFFIC_CLASSES } from "../../perf/traffic.ts";
4545 import { HOME_TTL_MS, cachedKpis } from "./home_cache.ts";
@@ -315,6 +315,6 @@ export function kpiProbe(app: App, now: Date = new Date()): KpiProbe {
315315 now,
316316 { kpis: cachedKpis(app.db, now, forge), live: liveNow() },
317317 forge,
318 perfRecord,
318 perfOf(app).perfRecord,
319319 );
320320 }
test/helpers/stall-state.ts +7 −10
@@ -1,20 +1,17 @@
11 /**
2 * The process's stall watch, starting clean and left clean (#11069). The
3 * suite runs every file in one process, and `loopWatch`, `stallBlame` and the
4 * telemetry reader counts (`perf/live.ts`, `system/telemetry_reads.ts`) are
5 * that process's; a stall one file noted would otherwise be a row in the next
6 * file's /system. Call at a file's top level, as `quietLogs` is
7 * (`globals.ts`): it clears before the file's first test and after its last.
2 * The process's telemetry reader counts, starting clean and left clean
3 * (#11069). The suite runs every file in one process, and the counts
4 * (`system/telemetry_reads.ts`) are that process's. A forge's stalls are its
5 * own (`perfOf`, #12615) and need no clearing. Call at a file's top level, as
6 * `quietLogs` is (`globals.ts`): it clears before the file's first test and
7 * after its last.
88 */
99
1010 import { afterAll, beforeAll } from "bun:test";
11 import { loopWatch, stallBlame } from "../../src/perf/live.ts";
1211 import { resetTelemetryReads } from "../../src/system/telemetry_reads.ts";
1312
14 /** Forget every stall and telemetry read the process has noted. */
13 /** Forget every telemetry read the process has noted. */
1514 export function clearStallState(): void {
16 loopWatch.clear();
17 stallBlame.clear();
1815 resetTelemetryReads();
1916 }
2017
test/loop-stall-by-route.test.ts +10 −10
@@ -11,7 +11,7 @@ import { serve, type Servers } from "../src/http/server.ts";
1111 import { watchStalls } from "../src/kernel/loop_lag.ts";
1212 import { openMetrics } from "../src/metrics/openmetrics.ts";
1313 import { stallFamilies, TOP_ROUTES } from "../src/metrics/stalls.ts";
14 import { lagMinutes, loopWatch, stallBlame } from "../src/perf/live.ts";
14 import { perfOf } from "../src/perf/live.ts";
1515 import { WORST_STALLS } from "../src/perf/stall_blame.ts";
1616 import { createLoopWatch, HOUR_MS, NO_REQUEST } from "../src/perf/loop.ts";
1717 import { createAgent } from "../src/actions/crew.ts";
@@ -144,8 +144,8 @@ test("GET /metrics names the route a stall ran across", async () => {
144144 // millisecond was only across a 400 ms stall, not its cause (`WITNESS_SHARE`), so the one
145145 // that held the loop is noted as the server would have noted it: 300 ms of the window.
146146 const at = performance.now();
147 loopWatch.finished("/api/v1/health", at - 300, at);
148 expect(loopWatch.stalled(400, at)).not.toBeNull();
147 perfOf(app).loopWatch.finished("/api/v1/health", at - 300, at);
148 expect(perfOf(app).loopWatch.stalled(400, at)).not.toBeNull();
149149 const text = await (await fetch(`${servers.url}/metrics`, { headers: { authorization: `Bearer ${ro}` } })).text();
150150 expect(text).toMatch(/^forge_loop_stalls_total\{route="\/api\/v1\/health"\} [1-9]/m);
151151 expect(text).toMatch(/^forge_loop_stall_hour_milliseconds\{route="\/api\/v1\/health"\} [1-9]/m);
@@ -229,12 +229,12 @@ test("the Stalls screen lists the hour's worst single stalls as /system does: wh
229229 test("the Stalls screen reads the process's stall blame by default, the five /system reads", () => {
230230 const now = performance.now();
231231 for (const [ms, r] of [[300, "/a"], [800, "/b"], [250, "/c"], [500, "/d"], [700, "/e"], [210, "/f"]] as const)
232 stallBlame.note({ at: now - 1_000, lateMs: ms, routes: [r], jobs: [] });
232 perfOf(app).stallBlame.note({ at: now - 1_000, lateMs: ms, routes: [r], jobs: [] });
233233 const lines = stallLines(new Session(app, identity(alice)), []);
234234 const named = lines.slice(lines.indexOf("") + 2).map((l) => l.split(/\s+/)[0] ?? "");
235235 expect(named).toEqual(["/b", "/e", "/d", "/a", "/c"]);
236 expect(stallBlame.worst(performance.now(), HOUR_MS, WORST_STALLS).map((s) => s.what)).toEqual(named);
237 stallBlame.clear();
236 expect(perfOf(app).stallBlame.worst(performance.now(), HOUR_MS, WORST_STALLS).map((s) => s.what)).toEqual(named);
237 perfOf(app).stallBlame.clear();
238238 });
239239
240240 test("the Stalls screen shows the last 20 minutes' loop lag as /system does: over count, each minute, what ran (#11220)", async () => {
@@ -258,9 +258,9 @@ test("the Stalls screen shows the last 20 minutes' loop lag as /system does: ove
258258 for (const who of [bob, bot, undefined]) expect(lagLines(new Session(app, identity(who)), rows)).toEqual([]);
259259
260260 // The screen itself draws the process's readings above the stalls.
261 lagMinutes.clear();
262 lagMinutes.note(250, 0);
263 lagMinutes.note(0, 60_000); // closes the first minute
261 perfOf(app).lagMinutes.clear();
262 perfOf(app).lagMinutes.note(250, 0);
263 perfOf(app).lagMinutes.note(0, 60_000); // closes the first minute
264264 const { app: tui, session } = createForgeApp(app, identity(alice), { terminal: headlessTerminal(120, 40), exitHooks: false });
265265 tui.start();
266266 await settleApp(tui);
@@ -268,7 +268,7 @@ test("the Stalls screen shows the last 20 minutes' loop lag as /system does: ove
268268 await settleApp(tui);
269269 const shown = tui.screen.toText();
270270 tui.stop();
271 lagMinutes.clear();
271 perfOf(app).lagMinutes.clear();
272272 expect(shown).toContain("Loop lag, last 20 minutes: 1 of 1 over 100 ms");
273273 expect(shown).toContain("Route (last hour)");
274274 expect(shown.indexOf("Loop lag")).toBeLessThan(shown.indexOf("Route (last hour)"));
test/mcp-system-routes.test.ts +3 −3
@@ -9,7 +9,7 @@ import { setTelemetryGrant } from "../src/actions/telemetry.ts";
99 import { createToken } from "../src/core/tokens.ts";
1010 import { createUser, getUserByName } from "../src/core/users.ts";
1111 import { serve, type Servers } from "../src/http/server.ts";
12 import { perfRecord } from "../src/perf/live.ts";
12 import { perfOf } from "../src/perf/live.ts";
1313 import { quietLogs } from "./helpers/globals.ts";
1414
1515 quietLogs();
@@ -47,8 +47,8 @@ const call = async (token: string) => {
4747 };
4848
4949 test("routes lists the over-budget route first, with its budget and slowest phase; a non-admin is refused", async () => {
50 // perfRecord is the process's own, and a shard-mate's requests leave samples (and patterns, up to the cap) in it.
51 perfRecord.clear();
50 // The forge's own record (#12615): a shard-mate's requests leave nothing in it.
51 const perfRecord = perfOf(app).perfRecord;
5252 const at = Date.now();
5353 for (let i = 0; i < 25; i++) {
5454 perfRecord.add("/boards", { at, ms: 100, signedIn: true, phases: [{ name: "app", ms: 100, hit: false }] });
test/mcp-system-stalls.test.ts +3 −4
@@ -8,7 +8,7 @@ import { createToken } from "../src/core/tokens.ts";
88 import { createUser } from "../src/core/users.ts";
99 import { serve, type Servers } from "../src/http/server.ts";
1010 import { during } from "../src/perf/jobs.ts";
11 import { loopWatch } from "../src/perf/live.ts";
11 import { perfOf } from "../src/perf/live.ts";
1212 import { LIMIT_MS } from "../src/perf/loop.ts";
1313 import { quietLogs } from "./helpers/globals.ts";
1414
@@ -35,9 +35,8 @@ afterAll(async () => {
3535 });
3636
3737 test("a stall under a named job is read through system, at most 10, most ms first", async () => {
38 // The watch is the process's one: stalls and requests an earlier file left
39 // would crowd the top 10 or be blamed ahead of the job. Start from nothing.
40 loopWatch.clear();
38 // The forge's own watch (#12615): what an earlier file noted is not in it.
39 const { loopWatch } = perfOf(app);
4140 // The job holds the loop for a real share of the stall: one that only brushed it is not
4241 // named (`perf/loop.ts`).
4342 during("test-job-10907", () => {
test/metrics-forge.test.ts +7
@@ -64,3 +64,10 @@ test("totals are kept per database and stop growing new patterns at the cap", ()
6464 ta.record("/p0", 1);
6565 expect(readTotals(a).get("/p0")!.counts[0]).toBe(2);
6666 });
67
68 test("a scrape with no forge reports no stall families; with one it reports that forge's", () => {
69 const db = new Database(":memory:");
70 migrate(db, migrationFiles);
71 expect(forgeMetrics(db)).not.toContain("forge_loop_stall_hour_count");
72 expect(forgeMetrics(db, undefined, Date.now(), {})).toContain("forge_loop_stall_hour_count");
73 });
test/pages-budget.test.ts −3
@@ -36,7 +36,6 @@ import { keepTick } from "../src/flow/keep.ts";
3636 import { readLanesInline, useLanesReader } from "../src/flow/lanes.ts";
3737 import { usePagesReader } from "../src/flow/pages.ts";
3838 import { pagesConfig, readPagePicture, type Picture } from "../src/flow/pages_read.ts";
39 import { perfRecord } from "../src/perf/live.ts";
4039 import { buildApiRouter, buildRouter, serve, type Servers } from "../src/http/server.ts";
4140 import { quietLogs } from "./helpers/globals.ts";
4241 import { promote } from "./helpers/members.ts";
@@ -171,8 +170,6 @@ beforeAll(async () => {
171170 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
172171 }, 60_000);
173172 afterAll(() => {
174 // The walk fills the shared recorder to its pattern cap; leave it empty for the next file in this process.
175 perfRecord.clear();
176173 servers.stop();
177174 app.close();
178175 rmSync(root, { recursive: true, force: true });
test/perf-lag-minutes.test.ts +6 −6
@@ -13,7 +13,7 @@ import { createToken } from "../src/core/tokens.ts";
1313 import { createUser } from "../src/core/users.ts";
1414 import { serve, type Servers } from "../src/http/server.ts";
1515 import { createLagMinutes, LAG_BAR_MS, LAG_MINUTE_MS, LAG_READINGS, overBar } from "../src/perf/lag_minutes.ts";
16 import { lagMinutes } from "../src/perf/live.ts";
16 import { perfOf } from "../src/perf/live.ts";
1717 import { lagSection } from "../src/web/pages/system.ts";
1818 import { quietLogs } from "./helpers/globals.ts";
1919
@@ -122,18 +122,18 @@ describe("the MCP system tool", () => {
122122 }, 30_000);
123123
124124 afterAll(async () => {
125 lagMinutes.clear();
125 perfOf(app).lagMinutes.clear();
126126 servers.stop();
127127 app.close();
128128 await rm(dataDir, { recursive: true, force: true });
129129 });
130130
131131 test("answers the same readings as {at, ms, what}, with the bar and the count over it", async () => {
132 lagMinutes.clear();
132 perfOf(app).lagMinutes.clear();
133133 const base = 1_000 * MIN;
134 lagMinutes.note(20, base);
135 lagMinutes.note(180.04, base + MIN);
136 lagMinutes.note(1, base + 2 * MIN);
134 perfOf(app).lagMinutes.note(20, base);
135 perfOf(app).lagMinutes.note(180.04, base + MIN);
136 perfOf(app).lagMinutes.note(1, base + 2 * MIN);
137137 const res = await fetch(`${servers.url}/mcp`, {
138138 method: "POST",
139139 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
test/perf-loop-jobs.test.ts +3 −2
@@ -2,7 +2,7 @@
22
33 import { expect, test } from "bun:test";
44 import { createJobWatch, during } from "../src/perf/jobs.ts";
5 import { loopWatch } from "../src/perf/live.ts";
5 import { createPerf } from "../src/perf/live.ts";
66 import { createLoopWatch, NO_REQUEST, stallLine } from "../src/perf/loop.ts";
77 import { freshStallState } from "./helpers/stall-state.ts";
88
@@ -66,7 +66,8 @@ test("a loop stall while a job awaits and another blocks is tallied to the block
6666 await lane;
6767 });
6868
69 test("the process's loop watch reads the process's job watch", () => {
69 test("a forge's loop watch reads the process's job watch", () => {
70 const { loopWatch } = createPerf();
7071 const before = loopWatch.tally(performance.now()).total.find((r) => r.route === "job:wired-test")?.count ?? 0;
7172 during("wired-test", () => block(300));
7273 const at = performance.now();
test/perf-per-forge.test.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * Each forge in a process keeps its own readings (#12615): a slow request on
3 * one is in its record, loop watch, stall blame and lag minutes, and none of
4 * the other's. One set for the process made page-budget and perf-server-hook
5 * read a shard-mate's requests in a whole gate.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtempSync, rmSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { noteWake, perfOf } from "../src/perf/live.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 const HOUR_MS = 60 * 60_000;
19 let root = "";
20 let slow: App;
21 let quiet: App;
22 let slowServers: Servers;
23 let quietServers: Servers;
24 beforeAll(async () => {
25 root = mkdtempSync(join(tmpdir(), "forge-perf-per-forge-"));
26 slow = createApp({ dataDir: join(root, "slow"), port: 0 });
27 quiet = createApp({ dataDir: join(root, "quiet"), port: 0 });
28 slowServers = await serve(slow);
29 quietServers = await serve(quiet);
30 });
31 afterAll(() => {
32 slowServers.stop();
33 quietServers.stop();
34 slow.close();
35 quiet.close();
36 rmSync(root, { recursive: true, force: true });
37 });
38
39 test("a slow request on one forge leaves the other's record, loop watch, stall blame and lag minutes empty", async () => {
40 expect((await fetch(`${slowServers.url}/api/v1/health`)).ok).toBe(true);
41 // The loop watcher wakes late across that request, as `main.ts` wires it;
42 // a wake a minute on closes the lag reading.
43 const at = performance.now();
44 noteWake(perfOf(slow), 5_000, at);
45 noteWake(perfOf(slow), 0, at + 60_000);
46
47 const mine = perfOf(slow);
48 expect(mine.perfRecord.traffic("/api/v1/health", 0).length).toBe(1);
49 expect(mine.loopWatch.tally(at).total.length).toBe(1);
50 expect(mine.stallBlame.worst(at, HOUR_MS, 10).length).toBe(1);
51 expect(mine.lagMinutes.readings().length).toBeGreaterThan(0);
52
53 const theirs = perfOf(quiet);
54 expect(theirs.perfRecord.traffic("/api/v1/health", 0)).toEqual([]);
55 expect(theirs.loopWatch.tally(at).total).toEqual([]);
56 expect(theirs.stallBlame.worst(at, HOUR_MS, 10)).toEqual([]);
57 expect(theirs.lagMinutes.readings()).toEqual([]);
58 });
test/perf-server-hook.test.ts +3 −3
@@ -5,7 +5,7 @@ import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { watchStalls } from "../src/kernel/loop_lag.ts";
8 import { perfRecord } from "../src/perf/live.ts";
8 import { perfOf } from "../src/perf/live.ts";
99 import { quietLogs } from "./helpers/globals.ts";
1010
1111 quietLogs();
@@ -25,10 +25,10 @@ afterAll(() => {
2525 });
2626
2727 test("a served request lands in the record under its route pattern; a client label hides nothing", async () => {
28 const before = perfRecord.traffic("/api/v1/health", 0).length;
28 const before = perfOf(app).perfRecord.traffic("/api/v1/health", 0).length;
2929 await fetch(`${servers.url}/api/v1/health`);
3030 await fetch(`${servers.url}/api/v1/health`, { headers: { "x-forge-synthetic": "1" } });
31 const after = perfRecord.traffic("/api/v1/health", 0);
31 const after = perfOf(app).perfRecord.traffic("/api/v1/health", 0);
3232 expect(after.length).toBe(before + 2);
3333 expect(after.at(-1)!.signedIn).toBe(false);
3434 expect(after.at(-1)!.phases.some((p) => p.name === "app")).toBe(true);
test/perf-stall-blame.test.ts +6 −6
@@ -13,7 +13,7 @@ import { createApp, type App } from "../src/app.ts";
1313 import { serve, type Servers } from "../src/http/server.ts";
1414 import { startLoopLag } from "../src/kernel/loop_lag.ts";
1515 import { createJobWatch } from "../src/perf/jobs.ts";
16 import { stallBlame } from "../src/perf/live.ts";
16 import { perfOf } from "../src/perf/live.ts";
1717 import { createLoopWatch, HOUR_MS, LIMIT_MS, type Stall } from "../src/perf/loop.ts";
1818 import { createStallBlame, STALL_KEPT, UNKNOWN, whatOf } from "../src/perf/stall_blame.ts";
1919 import { stallSection, worstStallsTable } from "../src/web/pages/system.ts";
@@ -139,14 +139,14 @@ describe("on /healthz", () => {
139139 });
140140
141141 afterAll(async () => {
142 stallBlame.clear();
142 perfOf(app).stallBlame.clear();
143143 servers.stop();
144144 app.close();
145145 await rm(dataDir, { recursive: true, force: true });
146146 });
147147
148148 test("loopWorstWhat is null with no stall, then names the last 10 s's worst", async () => {
149 stallBlame.clear();
149 perfOf(app).stallBlame.clear();
150150 const ask = async () =>
151151 (await (await fetch(`${servers.url}/healthz`, { headers: { accept: "application/json" } })).json()) as {
152152 ok: boolean;
@@ -159,9 +159,9 @@ describe("on /healthz", () => {
159159 expect(before.loopWorstWhat).toBeNull();
160160
161161 const now = performance.now();
162 stallBlame.note({ at: now - 60_000, lateMs: 900, routes: ["/too-old"], jobs: [] });
163 stallBlame.note({ at: now, lateMs: 300, routes: [], jobs: ["crew-tick"] });
164 stallBlame.note({ at: now, lateMs: 220, routes: ["/explore"], jobs: [] });
162 perfOf(app).stallBlame.note({ at: now - 60_000, lateMs: 900, routes: ["/too-old"], jobs: [] });
163 perfOf(app).stallBlame.note({ at: now, lateMs: 300, routes: [], jobs: ["crew-tick"] });
164 perfOf(app).stallBlame.note({ at: now, lateMs: 220, routes: ["/explore"], jobs: [] });
165165 expect((await ask()).loopWorstWhat).toBe("job:crew-tick");
166166 // A probe asking for nothing still hears the plain `ok` (#2917).
167167 expect(await (await fetch(`${servers.url}/healthz`)).text()).toBe("ok");
test/relay-stall-name.test.ts +3 −3
@@ -30,7 +30,7 @@ import type { Repo } from "../src/core/repos.ts";
3030 import { createUser, type User } from "../src/core/users.ts";
3131 import { serve, type Servers } from "../src/http/server.ts";
3232 import { createJobWatch, jobWatch } from "../src/perf/jobs.ts";
33 import { loopWatch } from "../src/perf/live.ts";
33 import { perfOf } from "../src/perf/live.ts";
3434 import { createLoopWatch, type Stall } from "../src/perf/loop.ts";
3535 import { loopWorst } from "../src/perf/loop_worst.ts";
3636 import { deploySettled } from "./helpers/apps-forge.ts";
@@ -176,8 +176,8 @@ describe("forge-stall on the relayed answer", () => {
176176 loopWorst.note(ms, now);
177177 // A job that ran for a moment was only across the stall (`WITNESS_SHARE`, `perf/loop.ts`):
178178 // what is named is what covered it, so a request that did is noted as the server notes one.
179 loopWatch.finished("/api/v1/health", now - ms, now);
180 const s = loopWatch.stalled(ms, now)!;
179 perfOf(app).loopWatch.finished("/api/v1/health", now - ms, now);
180 const s = perfOf(app).loopWatch.stalled(ms, now)!;
181181 // A route that ran across it outranks the job (setup's requests often do);
182182 // the job's own naming is pinned above, with a stepped clock.
183183 return heldBy([s])[0]!.name;
test/spawn-in-process-visible.test.ts +7 −7
@@ -20,7 +20,7 @@ import {
2020 noteChildRequest,
2121 } from "../src/perf/child_time.ts";
2222 import { during, jobWatch } from "../src/perf/jobs.ts";
23 import { loopWatch } from "../src/perf/live.ts";
23 import { perfOf } from "../src/perf/live.ts";
2424 import { stallLine } from "../src/perf/loop.ts";
2525 import { clientRows, servedWindow } from "../src/spawn/clients.ts";
2626 import { closeHostedChildren, openChildren, provideCellsForTest } from "../src/spawn/host.ts";
@@ -226,12 +226,12 @@ describe("a parent holding a forge in its own process", () => {
226226 });
227227
228228 test("a request it answers is the stall watcher's child:<name>, and is counted against it", async () => {
229 loopWatch.clear();
229 perfOf(parent).loopWatch.clear();
230230 // Open it, so the next request is answered by a forge already in this process.
231231 await (await fetch(`${servers.url}/healthz`, { headers: { host: "homie--forge.test" } })).text();
232232 const child = openChildren(parent).find((c) => c.name === "homie")!.app;
233233 const had = childHours().find((r) => r.name === "homie")?.requests ?? 0;
234 loopWatch.clear();
234 perfOf(parent).loopWatch.clear();
235235 // The child's own request holds the parent's thread: its first statement takes 80 ms of
236236 // synchronous work, as a slow query or a git call of the child's would. A stall is named
237237 // for what held the loop, not for what was only across it (`WITNESS_SHARE`, `perf/loop.ts`).
@@ -244,22 +244,22 @@ describe("a parent holding a forge in its own process", () => {
244244 expect(release()).toBe(true);
245245 // The stall that request made names the child: before, it named the parent's route of the
246246 // same shape.
247 const stall = loopWatch.stalled(250, performance.now());
247 const stall = perfOf(parent).loopWatch.stalled(250, performance.now());
248248 expect(stall?.routes).toContain("child:homie");
249249 expect(stallLine(stall!)).toContain("running then: child:homie");
250250 expect(childHours().find((r) => r.name === "homie")?.requests).toBe(had + 1);
251251 // The parent's own request is still its route's.
252 loopWatch.clear();
252 perfOf(parent).loopWatch.clear();
253253 const mine = holdOnce(parent, 80);
254254 await (
255255 await fetch(`${servers.url}/healthz`, { headers: { host: "forge.test" } })
256256 ).text();
257257 expect(mine()).toBe(true);
258 const own = loopWatch.stalled(250, performance.now());
258 const own = perfOf(parent).loopWatch.stalled(250, performance.now());
259259 expect(own?.routes).toEqual(["/healthz"]);
260260 expect(own?.routes.some((r) => r.startsWith("child:"))).toBe(false);
261261 // The watch is the process's: the two stalls this test made up are not left in its hour.
262 loopWatch.clear();
262 perfOf(parent).loopWatch.clear();
263263 });
264264
265265 test("/forges says so on its row, in plain words", async () => {
test/stall-in-flight.test.ts +4 −4
@@ -10,7 +10,7 @@ import { createUser } from "../src/core/users.ts";
1010 import { serve, type Servers } from "../src/http/server.ts";
1111 import { stallFamilies } from "../src/metrics/stalls.ts";
1212 import { createInFlight } from "../src/perf/in_flight.ts";
13 import { inFlight, loopWatch } from "../src/perf/live.ts";
13 import { inFlight, perfOf } from "../src/perf/live.ts";
1414 import { blamed, createLoopWatch, LIMIT_MS, NO_REQUEST, stallLine } from "../src/perf/loop.ts";
1515 import { whatOf } from "../src/perf/stall_blame.ts";
1616 import { quietLogs } from "./helpers/globals.ts";
@@ -142,7 +142,7 @@ function describe_server() {
142142 };
143143
144144 test("a real request held open across a stall is in MCP `system` `stalls`; one begun after is not", async () => {
145 loopWatch.clear();
145 perfOf(app).loopWatch.clear();
146146 // The suite shares one process: a request another file left open (or its own server's
147147 // background traffic) is in the open set too, and comes and goes on its own. Watch only
148148 // this test's `/mcp`, never the size of the whole set.
@@ -171,11 +171,11 @@ function describe_server() {
171171 await Bun.sleep(LIMIT_MS + 60); // real-timer: the request must be older than the stall limit on the real clock
172172 // The wake: the loop held for longer than the stall limit, beginning after the request did.
173173 const now = performance.now();
174 const stall = loopWatch.stalled(LIMIT_MS + 10, now)!;
174 const stall = perfOf(app).loopWatch.stalled(LIMIT_MS + 10, now)!;
175175 const named = stall.inFlight ?? [];
176176 expect(named).toContain("/mcp");
177177 // A stall shorter than the request's age is charged; one reaching back before it began is not.
178 expect(loopWatch.stalled(60_000, now)!.inFlight ?? []).toEqual(inFlight.since(now - 60_000));
178 expect(perfOf(app).loopWatch.stalled(60_000, now)!.inFlight ?? []).toEqual(inFlight.since(now - 60_000));
179179 push!(new TextEncoder().encode('"id":9,"method":"tools/list"}'));
180180 close!();
181181 await (await held).text();
test/traffic-history.test.ts +2 −2
@@ -25,7 +25,7 @@ import {
2525 signatureOf,
2626 type TrafficClass,
2727 } from "../src/perf/traffic.ts";
28 import { perfRecord } from "../src/perf/live.ts";
28 import { perfOf } from "../src/perf/live.ts";
2929 import { createTrafficWriter, HOUR_TOPS, trafficHistory, windowOf } from "../src/perf/traffic_store.ts";
3030
3131 const quiet = { warn: () => {} };
@@ -171,7 +171,7 @@ test("what a request is sorted by: internal, country and signature", () => {
171171 test("the page offers the three windows, for an admin alone, and a loopback request is the forge's own", async () => {
172172 const cookie = `forge_session=${createSession(app.db, admin.id).token}`;
173173 await fetch(`${servers.url}/`, { redirect: "manual" });
174 const own = perfRecord.ledger.totals(Date.now()).classes.internal.requests;
174 const own = perfOf(app).perfRecord.ledger.totals(Date.now()).classes.internal.requests;
175175 expect(own).toBeGreaterThan(0);
176176 const page = await fetch(`${servers.url}/settings/traffic?window=24h`, { headers: { cookie } });
177177 expect(page.status).toBe(200);

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs