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

/flow: the forge shows its own bottleneck — every stage from ready to live with its queue, wait and capacity, the knob beside it, machine use, and 24 h throughput #1570

Closed opened this in answer to
Closed without merging

mason/forge:mason/1554-flow-the-forge-shows-its-own-bottleneck → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +1445 −2
docs/APPS.md +11
@@ -1077,6 +1077,17 @@ made it, when, and from what to what (`core/capacity.ts`). The shard count
10771077 reaches a check's commands and an agent's shell as `FORGE_CHECK_SHARDS`,
10781078 from the setting, never from the forge's own environment.
10791079
1080 **`/flow`** (first in the header for a forge admin) puts those knobs beside
1081 the stages they limit: ready → building → check queue → checking → review
1082 queue → reviewing → approved → landed → releasing → live, each with what is
1083 in it, how long its oldest has waited, and a link to the list it counts
1084 (`/flow/:stage`). The stage whose oldest *waiting* item has waited longest
1085 is drawn as the bottleneck, with the sentence that says why. Beside them:
1086 each autonomous repository's slots and ceiling, each one's check cell
1087 (cpus, memory, from its `forge.json`), the pod's and node's CPU and memory,
1088 the last 24 hours in and out of each stage per hour, and the median ask →
1089 live (`core/flow.ts`, `core/machine.ts`, `web/pages/flow.ts`).
1090
10801091 ## What is deliberately not here
10811092
10821093 Containers. A cell (rule 9) is namespaces and a watch, not an image: an
scripts/gate.ts +1
@@ -88,6 +88,7 @@ export const GATE: readonly string[] = [
8888 "test/decide.test.ts",
8989 "test/ledger.test.ts",
9090 "test/capacity.test.ts",
91 "test/flow.test.ts",
9192 "test/guard-new-accounts.test.ts",
9293 "test/checks.test.ts",
9394 "test/dependencies.test.ts",
src/core/flow.ts added +417
@@ -0,0 +1,417 @@
1 /**
2 * The forge's pipeline as stages, read from what it already keeps (runs,
3 * pulls, reviews, autonomy): what is in each stage now, since when, and
4 * how much went in and out of it per hour over the last day (#1554). The
5 * stage whose oldest waiting item has waited longest is the bottleneck.
6 *
7 * A stage holds items that are *waiting* (queued for the next worker) and
8 * items that are *active* (being worked). Only waiting items can make a
9 * stage the bottleneck: a check that takes twenty minutes is working, a
10 * check that waits twenty minutes to start is the limit.
11 *
12 * Pure data, forge-wide, no authorization: `/flow` is a forge admin's.
13 */
14
15 import type { Database } from "bun:sqlite";
16
17 export const STAGES = [
18 "ready",
19 "building",
20 "check-queue",
21 "checking",
22 "review-queue",
23 "reviewing",
24 "approved",
25 "landed",
26 "released",
27 "live",
28 ] as const;
29 export type StageKey = (typeof STAGES)[number];
30
31 export const STAGE_LABEL: Record<StageKey, string> = {
32 ready: "Ready",
33 building: "Building",
34 "check-queue": "Check queue",
35 checking: "Checking",
36 "review-queue": "Review queue",
37 reviewing: "Reviewing",
38 approved: "Approved",
39 landed: "Landed",
40 released: "Releasing",
41 live: "Live",
42 };
43
44 /** What each stage holds, in one line under its name. */
45 export const STAGE_HOLDS: Record<StageKey, string> = {
46 ready: "Open, unblocked issues in autonomous repositories with nothing in flight on them",
47 building: "Agent runs (not reviews), queued for a builder or running",
48 "check-queue": "Checks queued to start",
49 checking: "Checks running",
50 "review-queue": "Review runs queued",
51 reviewing: "Review runs running",
52 approved: "Open pulls whose latest verdict is an approval, waiting to land",
53 landed: "Pulls merged into an app's default branch with no production deploy since",
54 released: "Production deploys queued or starting",
55 live: "Production deploys that went live in the last 24 hours",
56 };
57
58 export function isStage(s: string): s is StageKey {
59 return (STAGES as readonly string[]).includes(s);
60 }
61
62 export interface FlowItem {
63 /** `owner/name`. */
64 readonly repo: string;
65 /** The issue or pull number, when the item is about one. */
66 readonly number: number | null;
67 readonly title: string;
68 /** When it entered this stage (queued, started, approved, merged…). */
69 readonly since: string;
70 /** Queued for the next worker, rather than being worked. */
71 readonly waiting: boolean;
72 /** Where the item lives. */
73 readonly href: string;
74 }
75
76 export interface Stage {
77 readonly key: StageKey;
78 readonly items: readonly FlowItem[];
79 readonly waiting: number;
80 readonly active: number;
81 /** The oldest waiting item's entry, or null when nothing waits. */
82 readonly oldestWaiting: string | null;
83 }
84
85 /** Most items a stage reads; a count past it reads as "N+". */
86 export const STAGE_LIMIT = 1000;
87
88 const DAY_MS = 24 * 3_600_000;
89
90 interface Row {
91 repo: string;
92 number: number | null;
93 title: string | null;
94 since: string;
95 waiting: number;
96 run_id: string | null;
97 kind: string | null;
98 }
99
100 function toItem(r: Row): FlowItem {
101 const path = r.kind === "pull" ? "pulls" : "issues";
102 return {
103 repo: r.repo,
104 number: r.number,
105 title: r.title ?? "",
106 since: r.since,
107 waiting: r.waiting !== 0,
108 href:
109 r.run_id !== null
110 ? `/runs/${r.run_id}`
111 : r.number === null
112 ? `/${r.repo}`
113 : `/${r.repo}/${path}/${r.number}`,
114 };
115 }
116
117 const SLUG = `u.username || '/' || r.name`;
118 const REPO_JOIN = `JOIN repo r ON r.id = i.repo_id JOIN user u ON u.id = r.owner_id`;
119
120 function readyItems(db: Database): FlowItem[] {
121 return db
122 .query<Row, [number]>(
123 `SELECT ${SLUG} AS repo, i.number, i.title, i.created_at AS since,
124 1 AS waiting, NULL AS run_id, i.kind
125 FROM issue i ${REPO_JOIN}
126 WHERE i.kind = 'issue' AND i.state = 'open' AND r.autonomy != 'off'
127 AND (r.direction_issue_id IS NULL OR r.direction_issue_id != i.id)
128 AND NOT EXISTS (SELECT 1 FROM issue_dependency d JOIN issue b ON b.id = d.blocked_by_id
129 WHERE d.issue_id = i.id AND b.state = 'open')
130 AND NOT EXISTS (SELECT 1 FROM run x WHERE x.issue_id = i.id AND x.kind = 'agent'
131 AND x.state IN ('queued','running'))
132 AND NOT EXISTS (SELECT 1 FROM run x JOIN pull p ON p.head_branch = x.branch
133 JOIN issue pi ON pi.id = p.issue_id AND pi.repo_id = x.repo_id
134 WHERE x.issue_id = i.id AND x.kind = 'agent' AND x.branch != ''
135 AND pi.state = 'open')
136 ORDER BY i.created_at LIMIT ?1`,
137 )
138 .all(STAGE_LIMIT)
139 .map(toItem);
140 }
141
142 /** Runs of `kind` in flight; queued ones paused on a limit (`not_before` ahead) are not waiting for a worker. */
143 function runItems(
144 db: Database,
145 kind: "agent" | "check" | "deploy",
146 where: string,
147 now: string,
148 ): FlowItem[] {
149 return db
150 .query<Row, [string, string, number]>(
151 `SELECT ${SLUG} AS repo, i.number, COALESCE(i.title, x.reason) AS title,
152 CASE WHEN x.state = 'queued' THEN x.created_at
153 ELSE COALESCE(x.started_at, x.created_at) END AS since,
154 x.state = 'queued' AS waiting, x.id AS run_id, i.kind
155 FROM run x JOIN repo r ON r.id = x.repo_id JOIN user u ON u.id = r.owner_id
156 LEFT JOIN issue i ON i.id = x.issue_id
157 WHERE x.kind = ?1 AND x.state IN ('queued','running')
158 AND (x.state = 'running' OR x.not_before IS NULL OR x.not_before <= ?2)
159 AND ${where}
160 ORDER BY since LIMIT ?3`,
161 )
162 .all(kind, now, STAGE_LIMIT)
163 .map(toItem);
164 }
165
166 function approvedItems(db: Database): FlowItem[] {
167 return db
168 .query<Row, [number]>(
169 `SELECT ${SLUG} AS repo, i.number, i.title, v.created_at AS since,
170 1 AS waiting, NULL AS run_id, i.kind
171 FROM issue i JOIN pull p ON p.issue_id = i.id ${REPO_JOIN}
172 JOIN review v ON v.id = (SELECT id FROM review WHERE issue_id = i.id
173 AND state != 'commented'
174 ORDER BY created_at DESC, id DESC LIMIT 1)
175 WHERE i.state = 'open' AND v.state = 'approved'
176 ORDER BY v.created_at LIMIT ?1`,
177 )
178 .all(STAGE_LIMIT)
179 .map(toItem);
180 }
181
182 function landedItems(db: Database, now: Date): FlowItem[] {
183 const week = new Date(now.getTime() - 7 * DAY_MS).toISOString();
184 return db
185 .query<Row, [string, number]>(
186 `SELECT ${SLUG} AS repo, i.number, i.title, p.merged_at AS since,
187 1 AS waiting, NULL AS run_id, i.kind
188 FROM pull p JOIN issue i ON i.id = p.issue_id ${REPO_JOIN}
189 JOIN app a ON a.repo_id = r.id
190 WHERE p.merged_at >= ?1 AND p.base_branch = r.default_branch
191 AND NOT EXISTS (SELECT 1 FROM run d WHERE d.repo_id = r.id AND d.kind = 'deploy'
192 AND d.env = 'production' AND d.created_at >= p.merged_at)
193 ORDER BY p.merged_at LIMIT ?2`,
194 )
195 .all(week, STAGE_LIMIT)
196 .map(toItem);
197 }
198
199 function liveItems(db: Database, now: Date): FlowItem[] {
200 const day = new Date(now.getTime() - DAY_MS).toISOString();
201 return db
202 .query<Row, [string, number]>(
203 `SELECT ${SLUG} AS repo, NULL AS number, substr(x.commit_oid, 1, 10) AS title,
204 x.serving_at AS since, 0 AS waiting, x.id AS run_id, NULL AS kind
205 FROM run x JOIN repo r ON r.id = x.repo_id JOIN user u ON u.id = r.owner_id
206 WHERE x.kind = 'deploy' AND x.env = 'production' AND x.serving_at >= ?1
207 ORDER BY x.serving_at DESC LIMIT ?2`,
208 )
209 .all(day, STAGE_LIMIT)
210 .map(toItem);
211 }
212
213 /** The items in one stage now, oldest first (live: newest first). */
214 export function stageItems(
215 db: Database,
216 key: StageKey,
217 now = new Date(),
218 ): FlowItem[] {
219 const iso = now.toISOString();
220 switch (key) {
221 case "ready":
222 return readyItems(db);
223 case "building":
224 return runItems(db, "agent", "x.reason != 'review'", iso);
225 case "check-queue":
226 return runItems(db, "check", "x.state = 'queued'", iso);
227 case "checking":
228 return runItems(db, "check", "x.state = 'running'", iso);
229 case "review-queue":
230 return runItems(db, "agent", "x.reason = 'review' AND x.state = 'queued'", iso);
231 case "reviewing":
232 return runItems(db, "agent", "x.reason = 'review' AND x.state = 'running'", iso);
233 case "approved":
234 return approvedItems(db);
235 case "landed":
236 return landedItems(db, now);
237 case "released":
238 return runItems(
239 db,
240 "deploy",
241 "x.env = 'production' AND x.serving_at IS NULL",
242 iso,
243 ).map((i) => ({ ...i, waiting: false }));
244 case "live":
245 return liveItems(db, now);
246 }
247 }
248
249 export function readStage(db: Database, key: StageKey, now = new Date()): Stage {
250 const items = stageItems(db, key, now);
251 const waiting = items.filter((i) => i.waiting);
252 let oldest: string | null = null;
253 for (const i of waiting) if (oldest === null || i.since < oldest) oldest = i.since;
254 return {
255 key,
256 items,
257 waiting: waiting.length,
258 active: items.length - waiting.length,
259 oldestWaiting: oldest,
260 };
261 }
262
263 /** Every stage, left to right. */
264 export function readStages(db: Database, now = new Date()): Stage[] {
265 return STAGES.map((k) => readStage(db, k, now));
266 }
267
268 /** The stage whose oldest waiting item has waited longest; undefined when nothing waits. */
269 export function bottleneck(stages: readonly Stage[]): Stage | undefined {
270 let worst: Stage | undefined;
271 for (const s of stages)
272 if (
273 s.oldestWaiting !== null &&
274 (worst?.oldestWaiting == null || s.oldestWaiting < worst.oldestWaiting)
275 )
276 worst = s;
277 return worst;
278 }
279
280 // ---- throughput ----
281
282 export interface Throughput {
283 readonly key: StageKey;
284 /** Items in, per hour, oldest hour first: 24 numbers. */
285 readonly in: readonly number[];
286 /** Items out, per hour; empty for live, which nothing leaves. */
287 readonly out: readonly number[];
288 }
289
290 interface RunTimes {
291 kind: string;
292 reason: string;
293 env: string;
294 created_at: string;
295 started_at: string | null;
296 finished_at: string | null;
297 serving_at: string | null;
298 }
299
300 /** Which runs a run-made stage counts, and the instant it is entered or left at. */
301 type Pick = (r: RunTimes) => string | null;
302 const isBuild = (r: RunTimes) => r.kind === "agent" && r.reason !== "review";
303 const isReview = (r: RunTimes) => r.kind === "agent" && r.reason === "review";
304 const isCheck = (r: RunTimes) => r.kind === "check";
305 const isRelease = (r: RunTimes) => r.kind === "deploy" && r.env === "production";
306
307 const RUN_ENTERS: Partial<Record<StageKey, Pick>> = {
308 building: (r) => (isBuild(r) ? r.created_at : null),
309 "check-queue": (r) => (isCheck(r) ? r.created_at : null),
310 checking: (r) => (isCheck(r) ? r.started_at : null),
311 "review-queue": (r) => (isReview(r) ? r.created_at : null),
312 reviewing: (r) => (isReview(r) ? r.started_at : null),
313 released: (r) => (isRelease(r) ? r.created_at : null),
314 live: (r) => (isRelease(r) ? r.serving_at : null),
315 };
316
317 /** Where work ends inside a stage (a run finishing) rather than in the next one. */
318 const RUN_LEAVES: Partial<Record<StageKey, Pick>> = {
319 building: (r) => (isBuild(r) ? r.finished_at : null),
320 checking: (r) => (isCheck(r) ? r.finished_at : null),
321 reviewing: (r) => (isReview(r) ? r.finished_at : null),
322 };
323
324 /** The stages entered by something other than a run: SQL selecting `t` since ?1. */
325 const ROW_ENTERS: Partial<Record<StageKey, string>> = {
326 ready: `SELECT i.created_at AS t FROM issue i JOIN repo r ON r.id = i.repo_id
327 WHERE i.kind = 'issue' AND r.autonomy != 'off' AND i.created_at >= ?1`,
328 approved: `SELECT created_at AS t FROM review WHERE state = 'approved' AND created_at >= ?1`,
329 landed: `SELECT merged_at AS t FROM pull WHERE merged_at >= ?1`,
330 };
331
332 function bin(times: Iterable<string | null>, start: number): number[] {
333 const bins = Array.from({ length: 24 }, () => 0);
334 for (const t of times) {
335 if (t === null) continue;
336 const n = Math.floor((Date.parse(t) - start) / 3_600_000);
337 if (n >= 0 && n < 24) bins[n] = (bins[n] ?? 0) + 1;
338 }
339 return bins;
340 }
341
342 /**
343 * Per hour, over the last 24, what entered and left each stage. A stage's
344 * out is the next stage's in, except where work ends inside the stage
345 * (a run finishing): ready's out is building's in, and so on to live.
346 * Runs are read once, those made in the last three days (a run started
347 * today was made at most a little before; `run_created` keeps it cheap).
348 */
349 export function throughput(db: Database, now = new Date()): Throughput[] {
350 const start = Math.floor(now.getTime() / 3_600_000) * 3_600_000 - 23 * 3_600_000;
351 const since = new Date(start).toISOString();
352 const runs = db
353 .query<RunTimes, [string]>(
354 `SELECT kind, reason, env, created_at, started_at, finished_at, serving_at
355 FROM run WHERE created_at >= ?1`,
356 )
357 .all(new Date(start - 2 * DAY_MS).toISOString());
358 const series = (pick: Pick) => bin(runs.map(pick), start);
359 const ins = STAGES.map((k) => {
360 const pick = RUN_ENTERS[k];
361 if (pick !== undefined) return series(pick);
362 const sql = ROW_ENTERS[k] ?? "";
363 return bin(
364 db.query<{ t: string }, [string]>(sql).all(since).map((r) => r.t),
365 start,
366 );
367 });
368 return STAGES.map((key, n) => {
369 const own = RUN_LEAVES[key];
370 return {
371 key,
372 in: ins[n] ?? [],
373 out:
374 own !== undefined
375 ? series(own)
376 : key === "live"
377 ? []
378 : (ins[n + 1] ?? []),
379 };
380 });
381 }
382
383 /**
384 * The median, in milliseconds, from an ask to it being live, over what
385 * went live in the last 24 hours: a merged pull's ask is the issue its
386 * agent run worked (else the pull itself), and live is the first
387 * production deploy of its repository serving after the merge. Null when
388 * nothing went live.
389 */
390 export function medianAskToLive(db: Database, now = new Date()): number | null {
391 const day = new Date(now.getTime() - DAY_MS).toISOString();
392 const week = new Date(now.getTime() - 7 * DAY_MS).toISOString();
393 const rows = db
394 .query<{ asked: string; live: string | null }, [string]>(
395 `SELECT COALESCE(
396 (SELECT MIN(a.created_at) FROM run x JOIN issue a ON a.id = x.issue_id
397 WHERE x.repo_id = i.repo_id AND x.kind = 'agent' AND x.branch = p.head_branch
398 AND a.kind = 'issue'),
399 i.created_at) AS asked,
400 (SELECT MIN(d.serving_at) FROM run d
401 WHERE d.repo_id = i.repo_id AND d.kind = 'deploy' AND d.env = 'production'
402 AND d.serving_at >= p.merged_at) AS live
403 FROM pull p JOIN issue i ON i.id = p.issue_id
404 WHERE p.merged_at >= ?1`,
405 )
406 .all(week);
407 const spans = rows
408 .filter((r): r is { asked: string; live: string } => r.live !== null && r.live >= day)
409 .map((r) => Date.parse(r.live) - Date.parse(r.asked))
410 .filter((n) => Number.isFinite(n) && n >= 0)
411 .sort((a, b) => a - b);
412 if (spans.length === 0) return null;
413 const mid = Math.floor(spans.length / 2);
414 return spans.length % 2 === 1
415 ? (spans[mid] ?? 0)
416 : ((spans[mid - 1] ?? 0) + (spans[mid] ?? 0)) / 2;
417 }
src/core/machine.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * What the machine is using now, so a raised knob is visibly safe or not
3 * (#1554): the forge pod's CPU and memory from its cgroup (v2, then v1),
4 * and the node's load and memory from the kernel. Read on every call; the
5 * pod's CPU is a rate, so it is measured between this read and the last
6 * one (the first read of a process has nothing to measure against).
7 */
8
9 import { readFileSync } from "node:fs";
10 import { availableParallelism, freemem, loadavg, totalmem } from "node:os";
11 import { memoryLimitBytes } from "./capacity.ts";
12
13 export interface MachineUse {
14 /** Cores the pod may use: its cgroup quota, else every core it sees. */
15 readonly podCpus: number;
16 /** Cores the pod used since the last read; null on the first. */
17 readonly podCpuUsed: number | null;
18 readonly podMemoryBytes: number | null;
19 readonly podMemoryLimitBytes: number;
20 readonly nodeCpus: number;
21 /** The node's one-minute load average. */
22 readonly nodeLoad: number;
23 readonly nodeMemoryBytes: number;
24 readonly nodeMemoryFreeBytes: number;
25 }
26
27 function read(path: string): string | undefined {
28 try {
29 return readFileSync(path, "utf8").trim();
30 } catch {
31 return undefined;
32 }
33 }
34
35 /** `cpu.max` ("max 100000" or "400000 100000"), then v1's quota and period. */
36 function podCpus(cores: number): number {
37 const max = read("/sys/fs/cgroup/cpu.max")?.split(/\s+/);
38 let quota = Number(max?.[0]);
39 let period = Number(max?.[1]);
40 if (max === undefined) {
41 quota = Number(read("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"));
42 period = Number(read("/sys/fs/cgroup/cpu/cpu.cfs_period_us"));
43 }
44 return quota > 0 && period > 0 ? Math.min(cores, quota / period) : cores;
45 }
46
47 /** Microseconds of CPU the pod has used, ever. */
48 function podCpuMicros(): number | undefined {
49 const stat = read("/sys/fs/cgroup/cpu.stat")?.match(/^usage_usec (\d+)$/m);
50 if (stat?.[1] !== undefined) return Number(stat[1]);
51 const v1 = Number(read("/sys/fs/cgroup/cpuacct/cpuacct.usage"));
52 return Number.isFinite(v1) && v1 > 0 ? v1 / 1000 : undefined;
53 }
54
55 function podMemory(): number | null {
56 for (const f of [
57 "/sys/fs/cgroup/memory.current",
58 "/sys/fs/cgroup/memory/memory.usage_in_bytes",
59 ]) {
60 const n = Number(read(f));
61 if (Number.isFinite(n) && n > 0) return n;
62 }
63 return null;
64 }
65
66 let last: { at: number; micros: number } | undefined;
67
68 export function machineUse(): MachineUse {
69 const cores = availableParallelism();
70 const micros = podCpuMicros();
71 const at = performance.now();
72 let used: number | null = null;
73 if (micros !== undefined) {
74 if (last !== undefined && at - last.at > 100)
75 used = (micros - last.micros) / 1000 / (at - last.at);
76 last = { at, micros };
77 }
78 return {
79 podCpus: podCpus(cores),
80 podCpuUsed: used,
81 podMemoryBytes: podMemory(),
82 podMemoryLimitBytes: memoryLimitBytes(),
83 nodeCpus: cores,
84 nodeLoad: loadavg()[0] ?? 0,
85 nodeMemoryBytes: totalmem(),
86 nodeMemoryFreeBytes: freemem(),
87 };
88 }
89
90 /**
91 * Whether there is room to raise concurrency, in one sentence: the pod's
92 * CPU and memory against their limits, the busier of the two deciding.
93 */
94 export function headroom(m: MachineUse): { room: boolean; words: string } {
95 const cpu = m.podCpuUsed === null ? null : m.podCpuUsed / m.podCpus;
96 const mem =
97 m.podMemoryBytes === null ? null : m.podMemoryBytes / m.podMemoryLimitBytes;
98 const load = m.nodeLoad / m.nodeCpus;
99 const worst = Math.max(cpu ?? 0, mem ?? 0, load);
100 if (worst >= 0.8)
101 return {
102 room: false,
103 words: `Near the limit (${Math.round(worst * 100)}% used): raising concurrency here will make work contend, not finish sooner.`,
104 };
105 return {
106 room: true,
107 words: `Room to raise: the busiest of pod CPU, pod memory and node load is at ${Math.round(worst * 100)}%.`,
108 };
109 }
src/core/reserved.ts +1
@@ -66,6 +66,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6666 "events",
6767 "explore",
6868 "fleet",
69 "flow",
6970 "front",
7071 "go",
7172 "icons",
src/core/schema.ts +4
@@ -1595,6 +1595,10 @@ export const migrations: readonly string[] = [
15951595 PRIMARY KEY (repo_id, parent_id, issue_id)
15961596 );
15971597 `,
1598 // 76 — /flow reads the last day's runs by when they were made (#1554).
1599 `
1600 CREATE INDEX IF NOT EXISTS run_created ON run(created_at);
1601 `,
15981602 ];
15991603
16001604 /**
src/http/server.ts +11
@@ -7,6 +7,12 @@
77
88 import { unsealReleased } from "../actions/sealed.ts";
99 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
10 import {
11 flowAutonomySet,
12 flowCapacitySet,
13 flowPage,
14 flowStagePage,
15 } from "../web/pages/flow.ts";
1016 import {
1117 closeStreamsOf,
1218 closeStreamsOfSession,
@@ -602,6 +608,11 @@ export function buildRouter(): Router<Handler> {
602608 router.add("GET", "/migrate/jobs/:job", migrationJobPage);
603609 // Every app on one canvas; a literal route, so it must sit above /:owner.
604610 router.add("GET", "/map", globalMapPage);
611 // The pipeline and its knobs, for a forge admin (#1554); literal, above /:owner.
612 router.add("GET", "/flow", flowPage);
613 router.add("GET", "/flow/:stage", flowStagePage);
614 router.add("POST", "/flow/capacity", flowCapacitySet);
615 router.add("POST", "/flow/autonomy", flowAutonomySet);
605616 // A selection's spend and runs over time; literal, above /:owner.
606617 router.add("GET", "/fleet/graph", fleetGraphPage);
607618 router.add("GET", "/fleet/graph/live", fleetGraphLive);
src/web/layout.ts +16 −2
@@ -327,7 +327,10 @@ function paletteIndex(ctx: Ctx, extra: PaletteItem[]): Html {
327327 ? [{ t: "New forge", h: "/forges/new", c: "Create" }]
328328 : []),
329329 ...(ctx.auth.user?.isAdmin
330 ? [{ t: "Forges you sent", h: "/forges", c: "Go to" }]
330 ? [
331 { t: "Flow", h: "/flow", c: "Go to" },
332 { t: "Forges you sent", h: "/forges", c: "Go to" },
333 ]
331334 : []),
332335 ];
333336 // `studio` rides along so the palette's *remote* rows — what the search
@@ -448,7 +451,18 @@ function topbar(
448451 )}
449452 <span class="spacer"></span>
450453 <span class="topbar-tools">
451 ${searchBar()}<span class="hide-sm">${helpButton()}</span>${asksLink(
454 ${when(
455 user?.isAdmin === true,
456 () =>
457 html`<a
458 id="flow-link"
459 class="btn"
460 data-size="sm"
461 href="/flow"
462 title="The pipeline, its bottleneck and its knobs"
463 >${icon("activity")}<span class="hide-sm">Flow</span></a
464 >`,
465 )}${searchBar()}<span class="hide-sm">${helpButton()}</span>${asksLink(
452466 ctx,
453467 )}${themeMenu(theme)}
454468 ${user
src/web/pages/flow.ts added +638
@@ -0,0 +1,638 @@
1 /**
2 * /flow, for a forge admin: the pipeline from a ready issue to a live
3 * deploy as stages, left to right, each with what is in it now, how long
4 * the oldest has waited, and the knob that sets its capacity beside it
5 * (#1554). The stage whose oldest waiting item has waited longest is drawn
6 * as the bottleneck, with the one sentence that says why. Beside the knobs,
7 * what the machine is using, so a raise is visibly safe or not; below, the
8 * last 24 hours in and out of each stage, and the median ask → live.
9 *
10 * Every count links to the list it counts (`/flow/:stage`). The knobs are
11 * the capacity settings (`actions/capacity.ts`, the same change and the same
12 * record as Settings → Capacity) and each autonomous repository's slots and
13 * ceiling (`updateRepoSettings`, as its settings page does); the check
14 * cell's CPUs and memory are its `forge.json`'s, shown with a link to edit.
15 */
16
17 import { changeCapacity, listCapacity } from "../../actions/capacity.ts";
18 import { updateRepoSettings } from "../../actions/repos.ts";
19 import { readFileAt } from "../../apps/checkout.ts";
20 import { resolveLimits } from "../../apps/contain.ts";
21 import { parseCheck } from "../../apps/manifest.ts";
22 import type { CapacityKey } from "../../core/capacity.ts";
23 import {
24 bottleneck,
25 isStage,
26 medianAskToLive,
27 readStage,
28 readStages,
29 STAGE_HOLDS,
30 STAGE_LABEL,
31 STAGE_LIMIT,
32 throughput,
33 type Stage,
34 type StageKey,
35 type Throughput,
36 } from "../../core/flow.ts";
37 import { headroom, machineUse, type MachineUse } from "../../core/machine.ts";
38 import { getRepoById, listAutonomousRepos, type Repo } from "../../core/repos.ts";
39 import { resolveOid } from "../../git/merge.ts";
40 import { repoDir } from "../../git/repos.ts";
41 import type { Ctx } from "../../http/context.ts";
42 import { notFoundPage, signInFirst } from "../chrome.ts";
43 import { field, readForm } from "../form.ts";
44 import { html, raw, when, type Html } from "../html.ts";
45 import { flashTo, page } from "../layout.ts";
46 import { btn, card, empty, icon, row, time } from "../ui.ts";
47
48 function requireAdmin(ctx: Ctx): Response | undefined {
49 if (!ctx.auth.user) return signInFirst(ctx);
50 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
51 return undefined;
52 }
53
54 /** A span of milliseconds as a person reads it: 45s, 12m, 3h 5m, 2d 4h. */
55 export function span(ms: number): string {
56 const s = Math.max(0, Math.round(ms / 1000));
57 if (s < 60) return `${s}s`;
58 const m = Math.floor(s / 60);
59 if (m < 60) return `${m}m`;
60 const h = Math.floor(m / 60);
61 if (h < 48) return m % 60 === 0 ? `${h}h` : `${h}h ${m % 60}m`;
62 return `${Math.floor(h / 24)}d ${h % 24}h`;
63 }
64
65 const plural = (n: number, one: string, many: string) =>
66 `${n} ${n === 1 ? one : many}`;
67 const count = (n: number) => (n >= STAGE_LIMIT ? `${n}+` : String(n));
68
69 /** The numbers the sentences and the stage cards quote. */
70 interface Knobs {
71 readonly values: ReadonlyMap<CapacityKey, string>;
72 readonly repos: readonly Repo[];
73 }
74 const knob = (k: Knobs, key: CapacityKey) => {
75 const v = k.values.get(key) ?? "";
76 return v === "" ? "auto" : v;
77 };
78 const slots = (k: Knobs) => k.repos.reduce((n, r) => n + r.autonomySlots, 0);
79
80 /** Why a stage holds what waits in it, in one sentence. */
81 export function why(s: Stage, k: Knobs): string {
82 const n = s.waiting;
83 switch (s.key) {
84 case "ready":
85 return `${plural(n, "ready issue waits", "ready issues wait")} for a builder; slots = ${slots(k)} across ${plural(k.repos.length, "autonomous repository", "autonomous repositories")}, crew runs at once = ${knob(k, "crew.concurrency")}.`;
86 case "building":
87 return `${plural(n, "run waits", "runs wait")} for a builder; crew runs at once = ${knob(k, "crew.concurrency")}.`;
88 case "check-queue":
89 return `${plural(n, "check waits", "checks wait")} to start; checks at once = ${knob(k, "checks.concurrency")}, shards = ${knob(k, "checks.shards")}.`;
90 case "review-queue":
91 return `${plural(n, "pull waits", "pulls wait")} for a reviewer; crew runs at once = ${knob(k, "crew.concurrency")}.`;
92 case "approved":
93 return `${plural(n, "approved pull waits", "approved pulls wait")} to land; a person lands it, or autonomy does on green.`;
94 case "landed":
95 return `${plural(n, "merged pull waits", "merged pulls wait")} for a production deploy.`;
96 default:
97 return `${plural(n, "item waits", "items wait")} in ${STAGE_LABEL[s.key].toLowerCase()}.`;
98 }
99 }
100
101 /** The capacity a stage card states under its count. */
102 function capacityLine(key: StageKey, k: Knobs): string {
103 switch (key) {
104 case "ready":
105 return `slots ${slots(k)} in ${plural(k.repos.length, "repository", "repositories")}`;
106 case "building":
107 case "review-queue":
108 case "reviewing":
109 return `crew runs at once ${knob(k, "crew.concurrency")}`;
110 case "check-queue":
111 case "checking":
112 return `checks at once ${knob(k, "checks.concurrency")} × shards ${knob(k, "checks.shards")}`;
113 default:
114 return "";
115 }
116 }
117
118 /** Which capacity settings sit beside which stage. */
119 const STAGE_KNOBS: Partial<Record<StageKey, readonly CapacityKey[]>> = {
120 building: ["crew.concurrency"],
121 checking: ["checks.concurrency", "checks.shards"],
122 };
123
124 function capacityForm(key: CapacityKey, label: string, value: string): Html {
125 return html`<form class="flow-knob" method="post" action="/flow/capacity">
126 <input type="hidden" name="key" value="${key}" />
127 <label class="small muted"
128 >${label}
129 <input
130 class="input mono"
131 data-size="sm"
132 type="number"
133 name="value"
134 min="1"
135 value="${value}"
136 placeholder="auto"
137 aria-label="${label}"
138 /></label>
139 ${btn("Set", { size: "sm", label: `Set ${label}` })}
140 </form>`;
141 }
142
143 interface CellLimits {
144 readonly repo: Repo;
145 readonly cpus: number | null;
146 readonly memoryMiB: number | null;
147 }
148
149 /** Each autonomous repository's check cell, from `forge.json` on its default branch. */
150 async function cellLimits(ctx: Ctx, repos: readonly Repo[]): Promise<CellLimits[]> {
151 return Promise.all(
152 repos.map(async (repo) => {
153 const bare = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
154 const tip = await resolveOid(bare, `refs/heads/${repo.defaultBranch}`);
155 const none = { repo, cpus: null, memoryMiB: null };
156 if (tip === undefined) return none;
157 const [forgeJson, packageJson] = await Promise.all([
158 readFileAt(bare, tip, "forge.json"),
159 readFileAt(bare, tip, "package.json"),
160 ]);
161 const check = parseCheck(forgeJson, packageJson);
162 if (!check.ok || check.value === undefined) return none;
163 const limits = resolveLimits("step", check.value.limits);
164 return { repo, cpus: limits.cpus, memoryMiB: limits.memoryMiB };
165 }),
166 );
167 }
168
169 function stageCard(
170 s: Stage,
171 k: Knobs,
172 worst: boolean,
173 now: number,
174 cells: readonly CellLimits[],
175 ): Html {
176 const cap = capacityLine(s.key, k);
177 const keys = STAGE_KNOBS[s.key] ?? [];
178 return html`<li
179 class="flow-stage"
180 id="stage-${s.key}"
181 ${worst ? raw('data-bottleneck="true"') : null}
182 >
183 <h3 class="flow-stage-name">${STAGE_LABEL[s.key]}</h3>
184 <a class="flow-count" href="/flow/${s.key}" title="${STAGE_HOLDS[s.key]}"
185 >${count(s.items.length)}</a
186 >
187 <p class="small muted">
188 ${s.key === "live"
189 ? "in 24 h"
190 : html`${count(s.waiting)} waiting · ${count(s.active)} active`}
191 </p>
192 ${when(cap !== "", () => html`<p class="small mono">${cap}</p>`)}
193 ${when(
194 s.oldestWaiting,
195 (at) =>
196 html`<p class="small">oldest waited ${span(now - Date.parse(at))}</p>`,
197 )}
198 ${keys.map((key) =>
199 capacityForm(
200 key,
201 key === "checks.shards"
202 ? "Shards"
203 : key === "checks.concurrency"
204 ? "At once"
205 : "Runs at once",
206 k.values.get(key) ?? "",
207 ),
208 )}
209 ${when(
210 s.key === "ready",
211 () => html`<a class="small" href="#autonomy">Slots and ceilings ↓</a>`,
212 )}
213 ${when(
214 s.key === "checking" && cells.length > 0,
215 () =>
216 html`<ul class="flow-cells small">
217 ${cells.map(
218 (c) =>
219 html`<li>
220 <span class="mono">${c.repo.name}</span>
221 ${c.cpus === null
222 ? "no check"
223 : html`${String(c.cpus)} cpu · ${String(c.memoryMiB)} MiB`}
224 <a
225 href="/${c.repo.ownerName}/${c.repo.name}/edit/${c.repo
226 .defaultBranch}/forge.json"
227 title="Edit forge.json"
228 >edit</a
229 >
230 </li>`,
231 )}
232 </ul>`,
233 )}
234 </li>`;
235 }
236
237 /** 24 hourly bars, in above and out below the line: plain SVG, no script. */
238 function spark(t: Throughput): Html {
239 const peak = Math.max(1, ...t.in, ...t.out);
240 const bars = (xs: readonly number[], up: boolean, cls: string) =>
241 xs
242 .map((n, i) => {
243 const h = Math.round((n / peak) * 20);
244 return h === 0
245 ? ""
246 : `<rect class="${cls}" x="${i * 5}" y="${up ? 20 - h : 21}" width="4" height="${h}"><title>${n}</title></rect>`;
247 })
248 .join("");
249 return raw(
250 `<svg class="flow-spark" viewBox="0 0 120 42" width="120" height="42" role="img" aria-label="per hour, last 24 hours">${bars(t.in, true, "in")}${bars(t.out, false, "out")}</svg>`,
251 );
252 }
253
254 function machineCard(m: MachineUse, k: Knobs): Html {
255 const gib = (b: number) => `${(b / 1024 ** 3).toFixed(1)} GiB`;
256 const room = headroom(m);
257 return card(
258 html`<div class="card-body">
259 <p class="small" id="headroom" data-room="${room.room ? "yes" : "no"}">
260 ${room.words}
261 </p>
262 <dl class="flow-machine small">
263 <dt>Pod CPU</dt>
264 <dd class="mono">
265 ${m.podCpuUsed === null
266 ? "measuring — reload"
267 : m.podCpuUsed.toFixed(1)}
268 of ${m.podCpus.toFixed(1)} cores
269 </dd>
270 <dt>Pod memory</dt>
271 <dd class="mono">
272 ${m.podMemoryBytes === null ? "?" : gib(m.podMemoryBytes)} of
273 ${gib(m.podMemoryLimitBytes)}
274 </dd>
275 <dt>Node load</dt>
276 <dd class="mono">
277 ${m.nodeLoad.toFixed(1)} over ${String(m.nodeCpus)} cores
278 </dd>
279 <dt>Node memory</dt>
280 <dd class="mono">
281 ${gib(m.nodeMemoryBytes - m.nodeMemoryFreeBytes)} of
282 ${gib(m.nodeMemoryBytes)}
283 </dd>
284 </dl>
285 ${capacityForm(
286 "children.max",
287 "Forges this one may send",
288 k.values.get("children.max") ?? "",
289 )}
290 </div>`,
291 {
292 head: html`${icon("activity")}
293 <h2>Machine</h2>`,
294 pad: false,
295 },
296 );
297 }
298
299 function autonomyCard(repos: readonly Repo[]): Html {
300 return card(
301 repos.length === 0
302 ? html`<div class="card-body">
303 <p class="muted small">
304 No repository runs on its own; turn autonomy on in a repository's
305 settings.
306 </p>
307 </div>`
308 : html`<ul class="list">
309 ${repos.map((r) =>
310 row({
311 lead: icon("bot"),
312 title: html`<a href="/${r.ownerName}/${r.name}/settings#autonomy"
313 >${r.ownerName}/${r.name}</a
314 >
315 <span class="muted small">${r.autonomy}</span>`,
316 trail: html`<form
317 class="row-actions"
318 method="post"
319 action="/flow/autonomy"
320 >
321 <input type="hidden" name="repo" value="${r.id}" />
322 <label class="small muted"
323 >Slots
324 <input
325 class="input mono"
326 data-size="sm"
327 type="number"
328 name="slots"
329 min="1"
330 max="8"
331 value="${String(r.autonomySlots)}"
332 aria-label="Slots for ${r.name}"
333 /></label>
334 <label class="small muted"
335 >Ceiling $
336 <input
337 class="input mono"
338 data-size="sm"
339 type="number"
340 name="ceiling"
341 min="0"
342 step="any"
343 value="${String(r.autonomyCeilingUsd)}"
344 aria-label="Daily ceiling for ${r.name}"
345 /></label>
346 ${btn("Set", { size: "sm", label: `Set autonomy for ${r.name}` })}
347 </form>`,
348 }),
349 )}
350 </ul>`,
351 {
352 head: html`${icon("bot")}
353 <h2 id="autonomy">Autonomy: builder slots and daily ceilings</h2>`,
354 pad: false,
355 },
356 );
357 }
358
359 // GET /flow
360 export async function flowPage(ctx: Ctx): Promise<Response> {
361 const denied = requireAdmin(ctx);
362 if (denied) return denied;
363 const listed = listCapacity(ctx.app, ctx.auth.user);
364 if (!listed.ok) return notFoundPage(ctx);
365 const now = new Date();
366 const db = ctx.app.db;
367 const repos = listAutonomousRepos(db);
368 const k: Knobs = {
369 values: new Map(listed.value.settings.map((s) => [s.key, s.value])),
370 repos,
371 };
372 const stages = readStages(db, now);
373 const worst = bottleneck(stages);
374 const flows = throughput(db, now);
375 const median = medianAskToLive(db, now);
376 const cells = await cellLimits(ctx, repos);
377 const t = now.getTime();
378
379 const verdict =
380 worst === undefined
381 ? html`<p class="flow-verdict" id="bottleneck">
382 Nothing is waiting anywhere: the pipeline is clear.
383 </p>`
384 : html`<p class="flow-verdict" id="bottleneck" data-stage="${worst.key}">
385 <strong>Bottleneck: ${STAGE_LABEL[worst.key]}.</strong>
386 ${why(worst, k)} The oldest has waited
387 ${span(t - Date.parse(worst.oldestWaiting ?? now.toISOString()))}.
388 <a href="/flow/${worst.key}">See them</a>
389 </p>`;
390
391 const changes = listed.value.changes.slice(0, 8).map((c) =>
392 row({
393 lead: icon("history"),
394 title: html`<span class="mono">${c.key}</span>
395 <span class="mono">${c.from === "" ? "auto" : c.from}</span> →
396 <span class="mono">${c.to === "" ? "auto" : c.to}</span>`,
397 meta: html`${c.actorName === "" ? "someone" : c.actorName} ·
398 ${time(c.at)}`,
399 trail: html`<form method="post" action="/flow/capacity">
400 <input type="hidden" name="key" value="${c.key}" />
401 <input type="hidden" name="value" value="${c.from}" />
402 ${when(
403 c.from === "",
404 () => html`<input type="hidden" name="reset" value="1" />`,
405 )}
406 ${btn("Undo", {
407 size: "sm",
408 label: `Set ${c.key} back to ${c.from === "" ? "auto" : c.from}`,
409 })}
410 </form>`,
411 }),
412 );
413
414 const body = html`<div class="page-head">
415 <h1>Flow</h1>
416 <p class="muted">
417 From a ready issue to a live deploy. Every count opens the list it
418 counts; every knob takes effect on the next pick, without a restart.
419 </p>
420 </div>
421 ${verdict}
422 <ol class="flow-stages" aria-label="Pipeline stages">
423 ${stages.map((s) => stageCard(s, k, s === worst, t, cells))}
424 </ol>
425 <div class="flow-grid">
426 ${machineCard(machineUse(), k)}
427 ${card(
428 changes.length === 0
429 ? html`<div class="card-body">
430 <p class="muted small">No capacity change yet.</p>
431 </div>`
432 : html`<ul class="list">
433 ${changes}
434 </ul>`,
435 {
436 head: html`${icon("history")}
437 <h2>Changes</h2>
438 <a class="small" href="/settings/capacity">All capacity</a>`,
439 pad: false,
440 },
441 )}
442 </div>
443 ${autonomyCard(repos)}
444 ${card(
445 html`<div class="card-body">
446 <p class="small" id="ask-to-live">
447 Median ask → live, over what went live in the last 24 h:
448 <strong class="mono"
449 >${median === null ? "nothing went live" : span(median)}</strong
450 >
451 </p>
452 </div>
453 <table class="flow-table small">
454 <thead>
455 <tr>
456 <th scope="col">Stage</th>
457 <th scope="col">Per hour (in ▲ / out ▼)</th>
458 <th scope="col">In</th>
459 <th scope="col">Out</th>
460 </tr>
461 </thead>
462 <tbody>
463 ${flows.map(
464 (f) =>
465 html`<tr>
466 <th scope="row">
467 <a href="/flow/${f.key}">${STAGE_LABEL[f.key]}</a>
468 </th>
469 <td>${spark(f)}</td>
470 <td class="mono">
471 ${String(f.in.reduce((a, b) => a + b, 0))}
472 </td>
473 <td class="mono">
474 ${f.key === "live"
475 ? "—"
476 : String(f.out.reduce((a, b) => a + b, 0))}
477 </td>
478 </tr>`,
479 )}
480 </tbody>
481 </table>`,
482 {
483 head: html`${icon("clock")}
484 <h2>Last 24 hours</h2>`,
485 pad: false,
486 },
487 )}`;
488 return page({ ctx, title: "Flow", wide: true, body });
489 }
490
491 // GET /flow/:stage
492 export function flowStagePage(ctx: Ctx): Response {
493 const denied = requireAdmin(ctx);
494 if (denied) return denied;
495 const stage = ctx.params.stage ?? "";
496 if (!isStage(stage)) return notFoundPage(ctx);
497 const now = Date.now();
498 const s = readStage(ctx.app.db, stage);
499 const rows = s.items.map((i) =>
500 row({
501 lead: icon(i.waiting ? "clock" : "play"),
502 title: html`<a href="${i.href}"
503 >${i.repo}${i.number === null ? "" : `#${i.number}`}
504 ${i.title}</a
505 >`,
506 meta: html`${i.waiting ? "waiting" : "active"}
507 ${span(now - Date.parse(i.since))} · since ${time(i.since)}`,
508 }),
509 );
510 return page({
511 ctx,
512 title: `${STAGE_LABEL[stage]} · Flow`,
513 crumbs: [
514 { label: "Flow", href: "/flow" },
515 { label: STAGE_LABEL[stage], href: `/flow/${stage}` },
516 ],
517 body: html`<div class="page-head">
518 <h1>${STAGE_LABEL[stage]}</h1>
519 <p class="muted">${STAGE_HOLDS[stage]}.</p>
520 </div>
521 ${rows.length === 0
522 ? empty({ icon: "check", title: "Nothing here now." })
523 : card(
524 html`<ul class="list" id="stage-items">
525 ${rows}
526 </ul>`,
527 {
528 head: html`<h2>
529 ${count(s.items.length)} · ${count(s.waiting)} waiting ·
530 ${count(s.active)} active
531 </h2>`,
532 pad: false,
533 },
534 )}
535 <p><a href="/flow">← Flow</a></p>`,
536 });
537 }
538
539 const ERRORS: Record<string, string> = {
540 no_such_setting: "There is no such setting.",
541 invalid_value: "That value is outside what this setting takes.",
542 };
543
544 // POST /flow/capacity
545 export async function flowCapacitySet(ctx: Ctx): Promise<Response> {
546 const denied = requireAdmin(ctx);
547 if (denied) return denied;
548 const form = await readForm(ctx, "admin");
549 if (form instanceof Response) return form;
550 const key = field(form, "key");
551 const value = field(form, "value").trim();
552 const reset = field(form, "reset") === "1" || value === "";
553 const changed = changeCapacity(ctx.app, ctx.auth.user, key, reset ? null : value);
554 if (!changed.ok && changed.error === "not_found") return notFoundPage(ctx);
555 return flashTo(
556 ctx,
557 "/flow",
558 changed.ok
559 ? {
560 message:
561 changed.value.from === changed.value.to
562 ? `${key} is already ${changed.value.to || "auto"}.`
563 : `${key}: ${changed.value.from || "auto"} → ${changed.value.to || "auto"}, from the next pick on. Undo it under Changes.`,
564 }
565 : {
566 tone: "danger",
567 message: ERRORS[changed.error] ?? "That could not be set.",
568 },
569 );
570 }
571
572 // POST /flow/autonomy
573 export async function flowAutonomySet(ctx: Ctx): Promise<Response> {
574 const denied = requireAdmin(ctx);
575 if (denied) return denied;
576 const form = await readForm(ctx, "admin");
577 if (form instanceof Response) return form;
578 const repo = getRepoById(ctx.app.db, field(form, "repo"));
579 if (repo === undefined) return notFoundPage(ctx);
580 const slots = Number(field(form, "slots"));
581 const ceiling = Number(field(form, "ceiling"));
582 if (
583 !Number.isInteger(slots) ||
584 slots < 1 ||
585 slots > 8 ||
586 !Number.isFinite(ceiling) ||
587 ceiling < 0 ||
588 field(form, "ceiling").trim() === ""
589 )
590 return flashTo(ctx, "/flow#autonomy", {
591 tone: "danger",
592 message: "Slots are 1 to 8; the ceiling is a number of dollars.",
593 });
594 const before = { slots: repo.autonomySlots, ceiling: repo.autonomyCeilingUsd };
595 const updated = await updateRepoSettings(ctx.app, ctx.auth.user, repo, {
596 autonomySlots: slots,
597 autonomyCeilingUsd: ceiling,
598 });
599 if (!updated.ok)
600 return flashTo(ctx, "/flow#autonomy", {
601 tone: "danger",
602 message: "Those settings could not be saved.",
603 });
604 return flashTo(ctx, "/flow#autonomy", {
605 message: `${repo.ownerName}/${repo.name}: slots ${before.slots} → ${slots}, ceiling $${before.ceiling} → $${ceiling}. To undo, set them back to ${before.slots} and $${before.ceiling}.`,
606 });
607 }
608
609
610 /**
611 * The flow page's own components, assembled into the served stylesheet by
612 * `web/style.ts` (as the board's are): every rule is a `.flow-*` selector
613 * nothing else in the sheet mentions.
614 */
615 export const flowCss = /* css */ `
616 @layer components {
617 .flow-verdict { padding: 12px 14px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--card); margin-bottom: 14px; }
618 .flow-verdict[data-stage] { border-color: var(--danger); }
619 .flow-stages { list-style: none; margin: 0 0 18px; padding: 0 0 6px; display: grid; grid-auto-flow: column; grid-auto-columns: minmax(150px, 1fr); gap: 8px; overflow-x: auto; }
620 .flow-stage { border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--card); padding: 10px; display: flex; flex-direction: column; gap: 4px; min-width: 0; }
621 .flow-stage p { margin: 0; }
622 .flow-stage[data-bottleneck] { border-color: var(--danger); box-shadow: inset 0 3px 0 var(--danger); }
623 .flow-stage-name { font-size: 13px; margin: 0; color: var(--muted-fg); }
624 .flow-count { font-size: 28px; font-weight: 600; font-variant-numeric: tabular-nums; color: var(--fg); }
625 .flow-count:hover { color: var(--accent); }
626 .flow-knob { display: flex; align-items: end; gap: 6px; margin-top: 4px; }
627 .flow-knob .input { width: 5em; display: block; }
628 .flow-cells { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; }
629 .flow-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; }
630 .flow-machine { display: grid; grid-template-columns: auto 1fr; gap: 2px 12px; margin: 8px 0; }
631 .flow-machine dd { margin: 0; }
632 .flow-table { width: 100%; border-collapse: collapse; }
633 .flow-table th, .flow-table td { padding: 4px 12px; text-align: left; border-top: 1px solid var(--border); font-variant-numeric: tabular-nums; }
634 .flow-spark { display: block; }
635 .flow-spark .in { fill: var(--accent); }
636 .flow-spark .out { fill: var(--muted-fg); }
637 }
638 `;
src/web/style.ts +2
@@ -24,6 +24,7 @@
2424
2525 import { swatchCss, themeCss } from "../design/themes.ts";
2626 import { boardCss } from "./pages/board.ts";
27 import { flowCss } from "./pages/flow.ts";
2728 import { base, layers, reset, utilities } from "./style/base.ts";
2829 import { components } from "./style/components.ts";
2930 import { content } from "./style/content.ts";
@@ -48,6 +49,7 @@ export const css = [
4849 avatarHues,
4950 studioCss,
5051 boardCss,
52 flowCss,
5153 content,
5254 utilities,
5355 swatchCss,
test/flow.test.ts added +235
@@ -0,0 +1,235 @@
1 /**
2 * /flow shows the forge's own bottleneck (#1554): from a seeded forge —
3 * checks queued for hours, a builder run queued for minutes — the page
4 * names the check queue as the bottleneck with the sentence that says why,
5 * every count opens the list it counts, a knob changed there is recorded
6 * and undoable, and nobody but a forge admin sees any of it.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { openIssue } from "../src/actions/issues.ts";
15 import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
16 import { capacityValue, setCapacity } from "../src/core/capacity.ts";
17 import {
18 bottleneck,
19 medianAskToLive,
20 readStages,
21 throughput,
22 } from "../src/core/flow.ts";
23 import { getRepoById, type Repo } from "../src/core/repos.ts";
24 import { createRun } from "../src/core/runs.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import { serve, type Servers } from "../src/http/server.ts";
27
28 const HOUR = 3_600_000;
29 const ago = (ms: number) => new Date(Date.now() - ms).toISOString();
30
31 describe("/flow: the forge shows its own bottleneck", () => {
32 let dataDir: string;
33 let app: App;
34 let servers: Servers;
35 let alice: User;
36 let repo: Repo;
37 let checkIds: string[] = [];
38
39 const login = async (username: string): Promise<string> => {
40 const res = await fetch(`${servers.url}/signin`, {
41 method: "POST",
42 redirect: "manual",
43 headers: {
44 "content-type": "application/x-www-form-urlencoded",
45 origin: servers.url,
46 },
47 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
48 });
49 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
50 };
51 const get = (path: string, cookie: string) =>
52 fetch(`${servers.url}${path}`, { headers: { cookie }, redirect: "manual" });
53 const post = (path: string, cookie: string, body: Record<string, string>) =>
54 fetch(`${servers.url}${path}`, {
55 method: "POST",
56 redirect: "manual",
57 headers: {
58 cookie,
59 "content-type": "application/x-www-form-urlencoded",
60 origin: servers.url,
61 },
62 body: new URLSearchParams(body),
63 });
64
65 beforeAll(async () => {
66 dataDir = await mkdtemp(join(tmpdir(), "forge-flow-"));
67 app = createApp({ dataDir, port: 0 });
68 servers = await serve(app);
69 const a = await createUser(app.db, {
70 trusted: true,
71 username: "alice",
72 email: "[email protected]",
73 password: "a-good-passphrase",
74 adminIfFirst: true,
75 });
76 if (!a.ok) throw new Error(a.error);
77 alice = a.value;
78 const b = await createUser(app.db, {
79 trusted: true,
80 username: "bob",
81 email: "[email protected]",
82 password: "a-good-passphrase",
83 });
84 if (!b.ok) throw new Error(b.error);
85 const made = await createRepo(app, alice, { name: "shop" });
86 if (!made.ok) throw new Error(String(made.error));
87 const set = await updateRepoSettings(app, alice, made.value, {
88 autonomy: "assisted",
89 autonomyDirection: "keep the shop open",
90 autonomySlots: 2,
91 autonomyCeilingUsd: 15,
92 autonomyBy: alice.id,
93 });
94 if (!set.ok) throw new Error(String(set.error));
95 repo = set.value;
96 setCapacity(app.db, "checks.concurrency", "1", alice.id);
97
98 // Two ready issues, opened an hour ago: they wait, but not the longest.
99 for (const title of ["Add a cart", "Show the prices"]) {
100 const issue = openIssue(app, alice, repo, { title });
101 if (!issue.ok) throw new Error(String(issue.error));
102 app.db
103 .query("UPDATE issue SET created_at = ?1 WHERE id = ?2")
104 .run(ago(HOUR), issue.value.id);
105 }
106 // Three checks queued three hours ago, one running: the bottleneck.
107 for (let n = 0; n < 4; n++) {
108 const run = createRun(app.db, { repoId: repo.id, kind: "check", reason: "push" });
109 app.db
110 .query("UPDATE run SET created_at = ?1, state = ?2, started_at = ?3 WHERE id = ?4")
111 .run(ago(3 * HOUR), n === 0 ? "running" : "queued", n === 0 ? ago(HOUR) : null, run.id);
112 if (n > 0) checkIds.push(run.id);
113 }
114 // A builder run queued ten minutes ago.
115 const build = createRun(app.db, { repoId: repo.id, kind: "agent", reason: "assigned" });
116 app.db
117 .query("UPDATE run SET created_at = ?1 WHERE id = ?2")
118 .run(ago(10 * 60_000), build.id);
119 });
120
121 afterAll(async () => {
122 servers.stop();
123 app.close();
124 await rm(dataDir, { recursive: true, force: true });
125 });
126
127 test("the stages hold what the forge holds, and the longest wait is the bottleneck", () => {
128 const stages = readStages(app.db);
129 const by = new Map(stages.map((s) => [s.key, s]));
130 expect(by.get("ready")?.waiting).toBe(2);
131 expect(by.get("check-queue")?.waiting).toBe(3);
132 expect(by.get("checking")?.active).toBe(1);
133 expect(by.get("building")?.waiting).toBe(1);
134 expect(bottleneck(stages)?.key).toBe("check-queue");
135 });
136
137 test("an admin reads the bottleneck sentence, the knobs and the machine", async () => {
138 const cookie = await login("alice");
139 const res = await get("/flow", cookie);
140 expect(res.status).toBe(200);
141 const page = await res.text();
142 expect(page).toContain('id="bottleneck" data-stage="check-queue"');
143 expect(page).toContain("3 checks wait to start; checks at once = 1");
144 expect(page).toContain('data-bottleneck="true"');
145 // Every count is a link to the list it counts.
146 expect(page).toContain('href="/flow/check-queue"');
147 expect(page).toContain('href="/flow/ready"');
148 // The knobs beside their stages, and the machine beside the knobs.
149 expect(page).toContain('name="key" value="checks.concurrency"');
150 expect(page).toContain('name="key" value="crew.concurrency"');
151 expect(page).toContain('value="' + repo.id + '"');
152 expect(page).toContain('id="headroom"');
153 expect(page).toContain('id="ask-to-live"');
154 // Linked first in the header, for an admin.
155 expect(page).toContain('id="flow-link"');
156 expect(page.indexOf('id="flow-link"')).toBeLessThan(page.indexOf('class="topbar-search'));
157 });
158
159 test("a count opens the list it counts", async () => {
160 const cookie = await login("alice");
161 const res = await get("/flow/check-queue", cookie);
162 expect(res.status).toBe(200);
163 const page = await res.text();
164 for (const id of checkIds) expect(page).toContain(`/runs/${id}`);
165 expect((await get("/flow/nonsense", cookie)).status).toBe(404);
166 });
167
168 test("a knob changed on /flow says what it changed and is undone from there", async () => {
169 const cookie = await login("alice");
170 const set = await post("/flow/capacity", cookie, {
171 key: "checks.concurrency",
172 value: "4",
173 });
174 expect(set.status).toBe(303);
175 expect(set.headers.get("location")).toStartWith("/flow");
176 expect(capacityValue(app.db, "checks.concurrency")).toBe("4");
177 const page = await (await get("/flow", cookie)).text();
178 expect(page.replace(/\s+/g, " ")).toContain(
179 '<span class="mono">checks.concurrency</span> <span class="mono">1</span> → <span class="mono">4</span>',
180 );
181 // The newest change's Undo sets it back to what it was.
182 expect(page).toContain('name="value" value="1"');
183 await post("/flow/capacity", cookie, { key: "checks.concurrency", value: "1" });
184 expect(capacityValue(app.db, "checks.concurrency")).toBe("1");
185 const bad = await post("/flow/capacity", cookie, {
186 key: "checks.concurrency",
187 value: "99999",
188 });
189 expect(bad.status).toBe(303);
190 expect(capacityValue(app.db, "checks.concurrency")).toBe("1");
191 });
192
193 test("slots and ceiling change in place and leave the direction alone", async () => {
194 const cookie = await login("alice");
195 const res = await post("/flow/autonomy", cookie, {
196 repo: repo.id,
197 slots: "4",
198 ceiling: "30",
199 });
200 expect(res.status).toBe(303);
201 const now = getRepoById(app.db, repo.id);
202 expect(now?.autonomySlots).toBe(4);
203 expect(now?.autonomyCeilingUsd).toBe(30);
204 expect(now?.autonomyDirection).toBe("keep the shop open");
205 expect(now?.autonomy).toBe("assisted");
206 await post("/flow/autonomy", cookie, { repo: repo.id, slots: "9", ceiling: "30" });
207 expect(getRepoById(app.db, repo.id)?.autonomySlots).toBe(4);
208 });
209
210 test("nobody but a forge admin reads or changes it", async () => {
211 const bob = await login("bob");
212 expect((await get("/flow", bob)).status).toBe(404);
213 expect((await get("/flow/check-queue", bob)).status).toBe(404);
214 expect(
215 (await post("/flow/capacity", bob, { key: "checks.concurrency", value: "9" })).status,
216 ).toBe(404);
217 expect(
218 (await post("/flow/autonomy", bob, { repo: repo.id, slots: "8", ceiling: "1" })).status,
219 ).toBe(404);
220 expect(capacityValue(app.db, "checks.concurrency")).toBe("1");
221 expect(await (await get("/", bob)).text()).not.toContain('id="flow-link"');
222 expect((await get("/flow", "")).status).not.toBe(200);
223 });
224
225 test("throughput counts per hour, and ask → live is a median", () => {
226 const flows = new Map(throughput(app.db).map((f) => [f.key, f]));
227 const sum = (xs: readonly number[] | undefined) => (xs ?? []).reduce((a, b) => a + b, 0);
228 expect(sum(flows.get("check-queue")?.in)).toBe(4);
229 expect(sum(flows.get("checking")?.in)).toBe(1);
230 expect(sum(flows.get("check-queue")?.out)).toBe(1);
231 expect(sum(flows.get("ready")?.in)).toBe(2);
232 expect(flows.get("live")?.out).toEqual([]);
233 expect(medianAskToLive(app.db)).toBeNull();
234 });
235 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs