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

The lane is visible: queue depth, the running check and its age, median duration and the time to clear, on the home and in /api/v1/health; the 30-minute card names the cause #1440

Closed opened this in answer to
Closed without merging

scout/forge:scout/1277-the-lane-is-visible-queue-depth-the-runn → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +213 −12
src/kernel/vitals.ts +87 −2
@@ -30,6 +30,17 @@ export interface EnvCount {
3030 readonly state: string;
3131 }
3232
33 /** How many finished checks the median is taken over. */
34 export const MEDIAN_OVER = 20;
35
36 /** The check lane: one at a time, so depth times the median is the wait. */
37 export interface Lane {
38 readonly queued: number;
39 readonly running: { pull: number | null; since: string } | null;
40 readonly medianMinutes: number | null;
41 readonly clearsInMinutes: number | null;
42 }
43
3344 export interface Vitals {
3445 readonly ok: boolean;
3546 readonly needs: string[];
@@ -40,6 +51,7 @@ export interface Vitals {
4051 hostTotalBytes: number;
4152 };
4253 readonly queue: Record<string, number>;
54 readonly lane: Lane;
4355 readonly stuck: {
4456 runId: string;
4557 repo: string;
@@ -60,6 +72,74 @@ export interface VitalsInput {
6072 readonly now?: number;
6173 }
6274
75 /** The lane as one line, or null when nothing is queued. */
76 export function laneLine(lane: Lane, now = Date.now()): string | null {
77 if (lane.queued === 0) return null;
78 const parts = [`${lane.queued} check${lane.queued === 1 ? "" : "s"} queued`];
79 if (lane.running !== null) {
80 const age = Math.max(
81 0,
82 Math.round((now - new Date(lane.running.since).getTime()) / 60_000),
83 );
84 parts.push(
85 `running ${lane.running.pull === null ? "a check" : `#${lane.running.pull}`} for ${age} min`,
86 );
87 }
88 if (lane.medianMinutes !== null) parts.push(`median ${lane.medianMinutes} min`);
89 if (lane.clearsInMinutes !== null)
90 parts.push(
91 `clears in ~${lane.clearsInMinutes >= 120 ? `${Math.round(lane.clearsInMinutes / 60)} h` : `${lane.clearsInMinutes} min`}`,
92 );
93 return `Lane: ${parts.join(" · ")}`;
94 }
95
96 /** Depth, the running check, and the median of the last finished ones. */
97 function readLane(
98 db: Database,
99 running: ReturnType<typeof listRunning>,
100 now: number,
101 ): Lane {
102 const queued =
103 db
104 .query<{ n: number }, []>(
105 "SELECT COUNT(*) AS n FROM run WHERE kind = 'check' AND state = 'queued'",
106 )
107 .get()?.n ?? 0;
108 const first = running.find(
109 (r) => r.run.kind === "check" && !leaseLapsed(r.run, STALE_AFTER_MS, now),
110 );
111 const durations = db
112 .query<{ ms: number }, [number]>(
113 `SELECT (julianday(finished_at) - julianday(started_at)) * 86400000 AS ms
114 FROM run WHERE kind = 'check' AND state IN ('ok','failed')
115 AND started_at IS NOT NULL AND finished_at IS NOT NULL
116 ORDER BY finished_at DESC LIMIT ?1`,
117 )
118 .all(MEDIAN_OVER)
119 .map((r) => r.ms)
120 .sort((a, b) => a - b);
121 const mid = durations.length >> 1;
122 const medianMs =
123 durations.length === 0
124 ? null
125 : durations.length % 2
126 ? durations[mid]!
127 : (durations[mid - 1]! + durations[mid]!) / 2;
128 const medianMinutes = medianMs === null ? null : Math.round(medianMs / 60_000);
129 return {
130 queued,
131 running: first
132 ? {
133 pull: first.issue,
134 since: first.run.startedAt ?? first.run.createdAt,
135 }
136 : null,
137 medianMinutes,
138 clearsInMinutes:
139 medianMinutes === null || queued === 0 ? null : queued * medianMinutes,
140 };
141 }
142
63143 export function vitals(input: VitalsInput): Vitals {
64144 const now = input.now ?? Date.now();
65145 const needs: string[] = [];
@@ -74,17 +154,21 @@ export function vitals(input: VitalsInput): Vitals {
74154 `Disk is nearly full: ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free.`,
75155 );
76156
157 const running = listRunning(input.db);
158 const lane = readLane(input.db, running, now);
77159 const queue: Record<string, number> = {};
78160 for (const row of queueDepth(input.db, now)) {
79161 queue[row.kind] = row.queued;
80162 if (now - new Date(row.oldest).getTime() > QUEUE_WAIT_MAX_MS)
81163 needs.push(
82 `The ${row.kind} queue has waited over ${QUEUE_WAIT_MAX_MS / 60_000} minutes.`,
164 row.kind === "check"
165 ? `The check queue has waited over ${QUEUE_WAIT_MAX_MS / 60_000} minutes. ${laneLine(lane, now) ?? ""}; one lane, checks run one at a time.`
166 : `The ${row.kind} queue has waited over ${QUEUE_WAIT_MAX_MS / 60_000} minutes.`,
83167 );
84168 }
85169
86170 const stuck: Vitals["stuck"] = [];
87 for (const { run, repo, issue } of listRunning(input.db)) {
171 for (const { run, repo, issue } of running) {
88172 const started = new Date(run.startedAt ?? run.createdAt).getTime();
89173 if (leaseLapsed(run, STALE_AFTER_MS, now) || now - started > NO_PROGRESS_MS)
90174 stuck.push({
@@ -128,6 +212,7 @@ export function vitals(input: VitalsInput): Vitals {
128212 hostTotalBytes: totalmem(),
129213 },
130214 queue,
215 lane,
131216 stuck,
132217 apps,
133218 errors: { lastHour: seen.lastHour, latest: seen.latest },
src/web/pages/board.ts +43 −7
@@ -38,7 +38,8 @@ import { readSpend } from "../../actions/spend.ts";
3838 import { spendView } from "./spend.ts";
3939 import { listApps } from "../../core/apps.ts";
4040 import { forgeHealth, rolloutLine } from "../../kernel/guard.ts";
41 import { vitals, type Vitals } from "../../kernel/vitals.ts";
41 import { STALE_AFTER_MS } from "../../runs/lease.ts";
42 import { laneLine, vitals, type Vitals } from "../../kernel/vitals.ts";
4243 import { getIssue, getIssuesByIds, type Issue } from "../../core/issues.ts";
4344 import { looksForApps } from "../../core/looks.ts";
4445 import {
@@ -54,7 +55,7 @@ import {
5455 ownerFactRepoIds,
5556 type Repo,
5657 } from "../../core/repos.ts";
57 import { listActiveRuns, listRuns, type Run } from "../../core/runs.ts";
58 import { leaseLapsed, listActiveRuns, listRunning, listRuns, type Run } from "../../core/runs.ts";
5859 import { getUsersByIds } from "../../core/users.ts";
5960 import {
6061 autonomyStatus,
@@ -101,10 +102,12 @@ function reasonWords(reason: string): string {
101102 }
102103 }
103104
104 type StateWord = "queued" | "working" | "paused";
105 type StateWord = "queued" | "working" | "paused" | "lost";
105106
106 function stateWord(run: Run): StateWord {
107 if (run.state === "running") return "working";
107 /** A running run whose heartbeat has lapsed is not working: its process is gone. */
108 function stateWord(run: Run, now = Date.now()): StateWord {
109 if (run.state === "running")
110 return leaseLapsed(run, STALE_AFTER_MS, now) ? "lost" : "working";
108111 return run.notBefore === null ? "queued" : "paused";
109112 }
110113
@@ -310,6 +313,29 @@ function needHref(need: string, v: Vitals): string | undefined {
310313 return undefined;
311314 }
312315
316 /**
317 * Who is working: a row per running agent run (agent, pull, since, what), and
318 * when none is, why — autonomy off everywhere, or nothing ready.
319 */
320 function crewRows(ctx: Ctx, running: ReturnType<typeof listRunning>): Html {
321 const now = Date.now();
322 const agents = running.filter(
323 (r) => r.run.kind === "agent" && !leaseLapsed(r.run, STALE_AFTER_MS, now),
324 );
325 if (agents.length === 0) {
326 const on = ctx.app.db
327 .query<{ n: number }, []>(
328 "SELECT COUNT(*) AS n FROM repo WHERE autonomy = 'autonomous'",
329 )
330 .get()?.n;
331 return html`<span class="board-forge-crew">Crew idle: ${on ? "nothing ready" : "autonomy off"}</span>`;
332 }
333 return html`${agents.map(
334 ({ run, repo, issue }) =>
335 html`<a class="board-forge-crew" href="/${repo}/runs/${run.id}">agent on ${issue === null ? repo : `${repo}#${issue}`} since ${(run.startedAt ?? run.createdAt).slice(11, 16)}Z</a>`,
336 )}`;
337 }
338
313339 /**
314340 * The forge's health as one line, for a site admin only: *All fine*, or
315341 * each thing that needs them. A live region of its own; nobody else gets
@@ -332,6 +358,8 @@ function forgeStrip(ctx: Ctx): Html | null {
332358 (i) => i.key !== "stuck" && i.key !== "held",
333359 );
334360 const ok = v.ok && fh.ok;
361 const lane = laneLine(v.lane);
362 const crew = crewRows(ctx, listRunning(app.db));
335363 return html`<div
336364 class="board-forge"
337365 id="forge"
@@ -342,6 +370,8 @@ function forgeStrip(ctx: Ctx): Html | null {
342370 >
343371 ${rollout === null ? "" : html`<span class="board-forge-need">${rollout}</span>`}
344372 ${others.map((i) => html`<span class="board-forge-need">${i.key}: ${i.message}</span>`)}
373 ${lane === null ? "" : html`<span class="board-forge-lane">${lane}</span>`}
374 ${crew}
345375 ${
346376 ok
347377 ? html`<span class="board-forge-ok">All fine</span>`
@@ -678,10 +708,14 @@ function working(ctx: Ctx, scope: BoardScope): Html {
678708 >${issue?.title ?? (run.summary || "on the repository")}</span
679709 >
680710 <span class="board-run-meta">
681 <span class="board-state">${word}</span>
711 <span class="board-state">${word === "lost" ? "lost, re-queuing" : word}</span>
682712 <span
683713 >${
684 word === "paused" ? "resumes soon" : reasonWords(run.reason)
714 word === "paused"
715 ? "resumes soon"
716 : word === "lost"
717 ? "its process is gone"
718 : reasonWords(run.reason)
685719 }</span
686720 >
687721 ${when(
@@ -1056,6 +1090,8 @@ ${widths}
10561090 .board-run[data-state="working"] .board-state::before { background: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
10571091 .board-run[data-state="working"] .board-elapsed { color: var(--accent); }
10581092 .board-run[data-state="queued"] .board-elapsed { color: var(--muted-fg); }
1093 .board-run[data-state="lost"] .board-state { color: var(--attn); }
1094 .board-run[data-state="lost"] .board-state::before { background: var(--attn); }
10591095 .board-run[data-state="paused"] .board-state { color: var(--attn); }
10601096 .board-run[data-state="paused"] .board-state::before { background: var(--attn); }
10611097 /* Nothing on the wall animates on its own. A perpetual animation keeps the
test/board.test.ts +41
@@ -456,6 +456,47 @@ describe("the board's forge strip", () => {
456456 expect(other).not.toContain("stuck.");
457457 });
458458
459 test("the home says the lane when checks are queued, and why no crew member is working when none is", async () => {
460 app.db.query("UPDATE run SET state = 'cancelled' WHERE state IN ('queued','running')").run();
461 const idle = await board("root");
462 expect(idle).not.toContain("Lane:");
463 expect(idle).toMatch(/Crew idle: (autonomy off|nothing ready)/);
464 const made = await createRepo(app, admin, { name: "laned" });
465 if (!made.ok) throw new Error(String(made.error));
466 for (let i = 0; i < 3; i++) createRun(app.db, { repoId: made.value.id, kind: "check" });
467 const busy = await board("root");
468 expect(busy).toContain("Lane: 3 checks queued");
469 expect(await board("bob")).not.toContain("Lane:");
470 const agent = createRun(app.db, { repoId: made.value.id, kind: "agent" });
471 claimRun(app.db, agent.id);
472 const working = await board("root");
473 expect(working).toContain("board-forge-crew");
474 expect(working).toContain("root/laned");
475 expect(working).not.toContain("Crew idle");
476 app.db.query("UPDATE run SET state = 'cancelled' WHERE state IN ('queued','running')").run();
477 });
478
479 test("a running run whose heartbeat lapsed reads lost, re-queuing, never working", async () => {
480 app.db.query("UPDATE run SET state = 'cancelled' WHERE state IN ('queued','running')").run();
481 const made = await createRepo(app, admin, { name: "gone" });
482 if (!made.ok) throw new Error(String(made.error));
483 const enabled = await enableApp(app, admin, made.value, { slug: "gone" });
484 if (!enabled.ok) throw new Error(String(enabled.error));
485 const run = createRun(app.db, { repoId: made.value.id, kind: "agent" });
486 claimRun(app.db, run.id);
487 const live = await board("root");
488 expect(live).toContain('data-state="working"');
489 expect(live).not.toContain("lost, re-queuing");
490 app.db
491 .query("UPDATE run SET heartbeat_at = ?1 WHERE id = ?2")
492 .run(new Date(Date.now() - 120_000).toISOString(), run.id);
493 const lost = await board("root");
494 expect(lost).toContain("lost, re-queuing");
495 expect(lost).not.toContain('data-state="working"');
496 expect(lost).not.toContain('class="board-forge-crew" href');
497 app.db.query("UPDATE run SET state = 'cancelled' WHERE id = ?1").run(run.id);
498 });
499
459500 test("a setting that is not the default is no incident: the strip stays fine and the cards render", async () => {
460501 const made = await createRepo(app, admin, { name: "calm" });
461502 if (!made.ok) throw new Error(String(made.error));
test/vitals.test.ts +42 −3
@@ -82,7 +82,7 @@ test("a site admin with a read-only token gets the shape; others get the short o
8282 expect(Object.keys(v).sort()).toEqual(
8383 [
8484 "apps", "at", "checkedAt", "commit", "disk", "draining", "errors",
85 "incidents", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
85 "incidents", "lane", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
8686 "version",
8787 ].sort(),
8888 );
@@ -149,8 +149,8 @@ test("the number of queries does not grow with runs", () => {
149149 if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id);
150150 }
151151 expect(count()).toBe(before);
152 // The queue and the running runs.
153 expect(before).toBe(2);
152 // The queue, the running runs, the lane's depth and its finished checks.
153 expect(before).toBe(4);
154154 });
155155
156156 test("errors are counted, bounded, redacted, and a burst is said", async () => {
@@ -185,6 +185,45 @@ test("errors are counted, bounded, redacted, and a burst is said", async () => {
185185 }
186186 });
187187
188 test("the lane: depth, the running check and its age, the median of the last finished, the time to clear", async () => {
189 const { laneLine } = await import("../src/kernel/vitals.ts");
190 app.db.query("DELETE FROM run").run();
191 const now = Date.now();
192 const iso = (ms: number) => new Date(ms).toISOString();
193 // Empty lane: no line.
194 expect(vitals({ db: app.db, dataDir, now }).lane).toEqual({
195 queued: 0, running: null, medianMinutes: null, clearsInMinutes: null,
196 });
197 expect(laneLine(vitals({ db: app.db, dataDir, now }).lane, now)).toBeNull();
198 // Three finished checks of 10, 20 and 30 minutes: the median is 20.
199 for (const min of [10, 20, 30]) {
200 const r = createRun(app.db, { repoId, kind: "check" });
201 app.db
202 .query("UPDATE run SET state='ok', started_at=?2, finished_at=?3 WHERE id=?1")
203 .run(r.id, iso(now - 3_600_000), iso(now - 3_600_000 + min * 60_000));
204 }
205 const live = createRun(app.db, { repoId, kind: "check" });
206 app.db
207 .query("UPDATE run SET state='running', started_at=?2, heartbeat_at=?3 WHERE id=?1")
208 .run(live.id, iso(now - 6 * 60_000), iso(now));
209 for (let i = 0; i < 6; i++) createRun(app.db, { repoId, kind: "check" });
210 const lane = vitals({ db: app.db, dataDir, now }).lane;
211 expect(lane.queued).toBe(6);
212 expect(lane.running?.since).toBe(iso(now - 6 * 60_000));
213 expect(lane.medianMinutes).toBe(20);
214 expect(lane.clearsInMinutes).toBe(120);
215 expect(laneLine(lane, now)).toBe(
216 "Lane: 6 checks queued · running a check for 6 min · median 20 min · clears in ~2 h",
217 );
218 // The same, in one call for an admin.
219 const body = (await (await health(admin)).json()) as { lane: typeof lane };
220 expect(body.lane.queued).toBe(6);
221 expect(body.lane.medianMinutes).toBe(20);
222 // Waiting past thirty minutes names the cause, not only the symptom.
223 const later = vitals({ db: app.db, dataDir, now: now + 3_600_000 });
224 expect(later.needs.join(" ")).toContain("one lane");
225 });
226
188227 test("an unauthenticated internal call is refused, logged and flagged; the probe is not", async () => {
189228 const { resetRefusedInternal } = await import("../src/kernel/internal_refused.ts");
190229 resetRefusedInternal();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs