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

Crew: reviews never starve behind builders (reserve review capacity, re-request stale checks) #18269

opened this in answer to

Merged 6h 33m ago, live in production

scout/forge:scout/18249-crew-reviews-never-starve-behind-builder → main 0 commits fork 7 threads · 7 unresolved

  • Merged. scout/18249-crew-reviews-never-starve-behind-builder was merged into main as 076980c.

Review

Sign in to review this change.
14 files changed +354 −10
docs/features/review-never-starves.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Tell the crew
3 row: Reviews never wait behind new builds, and a stale green is checked again
4 ---
5 # Reviews never starve behind builders (#18249)
6
7 A green pull is reviewed and merged without waiting. Reviews take no builder slot, and the forge adds no hold on builders for them. The forge does three things itself:
8
9 - **The owner's own pulls are reviewed first**, after a lane revert and before every other pull; each group is oldest first.
10 - **A green check that ran on an older main is run again** (reason `stale_green`), once per move of main; the review follows when it is green. A pull with a verdict on its head is left alone.
11 - **A new head after changes were requested goes back to the same reviewer**, not the least busy one.
12
13 Measured on the flow page (`/flow`) and in the terminal's Flow screen: **Green to review**, the median from a green check to the first verdict on that head, for pulls reviewed in the last 24 hours; the figure shows once a pull was reviewed, and turns to attention past an hour. The MCP `flow` tool carries each pull's wait.
14
15 - Code: `src/crew/review.ts` (`reviewOrder`), `src/checks/stale_green.ts`, `src/flow/throughput.ts` (`greenToReview`).
src/checks/stale_green.ts added +61
@@ -0,0 +1,61 @@
1 /**
2 * A green pull whose check went stale is checked again, then reviewed (#18249). The check ran on
3 * an older main (`checkStale`): the forge asks for the merge to be re-run by hand, and the
4 * reviewer stood down on a head nobody would land. Here the forge queues the check itself; when
5 * it is green the check event sends the review, as for any green head.
6 *
7 * Read from the run table each tick, so a restart forgets nothing. A pull is rechecked once per
8 * main tip: the new run records the new tip, and only a later move of main makes it stale again.
9 * Not a pull with a verdict on its head, held, or with a check already out.
10 */
11
12 import type { App } from "../app.ts";
13 import { getHold } from "../core/holds.ts";
14 import { listOpenPulls } from "../core/pulls.ts";
15 import type { Repo } from "../core/repos.ts";
16 import { reviewSummary } from "../core/reviews.ts";
17 import { resolveOid } from "../git/merge.ts";
18 import { repoDir } from "../git/repos.ts";
19 import { createLog } from "../kernel/log.ts";
20 import { checksFor } from "./handles.ts";
21 import { checkStale } from "./stale.ts";
22
23 const log = createLog("checks");
24
25 /** The reason of the check this queues. */
26 export const STALE_GREEN_REASON = "stale_green";
27
28 interface Latest {
29 state: string;
outdated

A cap of 3 rechecks a tick. The check queue already has its own depth and batch limits, and each pull is already limited to once per main tip. Remove this constant and the break that uses it.

30 base_oid: string;
31 }
32
33 /** Queue the rechecks; the pull numbers queued. */
34 export async function recheckStaleGreens(app: App, repo: Repo): Promise<number[]> {
35 const checks = checksFor(app);
36 if (checks === undefined) return [];
37 const tip = await resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${repo.defaultBranch}`);
38 if (tip === undefined) return [];
39 const queued: number[] = [];
40 for (const pull of listOpenPulls(app.db, repo.id)) {
41 if (pull.headOid === "" || pull.mergedAt !== null || getHold(app.db, pull.id) !== undefined) continue;
42 const last = app.db
43 .query<Latest, [string, string]>(
44 `SELECT state, base_oid FROM run WHERE kind = 'check' AND issue_id = ?1 AND commit_oid = ?2
45 ORDER BY id DESC LIMIT 1`,
46 )
47 .get(pull.id, pull.headOid);
48 if (last === null || last.state !== "ok" || !checkStale({ baseOid: last.base_oid }, tip)) continue;
49 const seen = reviewSummary(app.db, pull.id, pull.headOid);
50 if (seen.approvals > 0 || seen.changesRequested > 0) continue;
51 const run = await checks.request(repo, `pull-${pull.number}`, pull.headOid, STALE_GREEN_REASON, pull.id);
52 if (run?.reason === STALE_GREEN_REASON) {
53 queued.push(pull.number);
54 log.info("green check is stale; queued again", {
55 repo: `${repo.ownerName}/${repo.name}`,
56 pull: pull.number,
57 });
58 }
59 }
60 return queued;
61 }
src/crew/autonomy_tick.ts +9
@@ -1,6 +1,7 @@
11 /** The loop's tick: every repository that runs on its own, one turn each, and the line it logs. */
22
33 import type { App } from "../app.ts";
4 import { recheckStaleGreens } from "../checks/stale_green.ts";
45 import { measureWhenFull, recheckWhenFull } from "../checks/full_window_recheck.ts";
56 import { batchWords, queueClashes, queueWords } from "../checks/queue.ts";
67 import { listCrewRoles } from "../core/agents.ts";
@@ -138,6 +139,14 @@ export async function autonomyTick(
138139 error: String(error),
139140 });
140141 });
142 // A green pull whose check ran on an older main is checked again, and reviewed when green
143 // (#18249).
144 await recheckStaleGreens(app, current).catch((error) => {
145 log.error("stale green recheck failed", {
146 repo: `${repo.ownerName}/${repo.name}`,
147 error: String(error),
148 });
149 });
141150 // And once a day the full suite on main's head, so the idle week still measures (#15911).
142151 await measureWhenFull(app, current, now).catch((error) => {
143152 log.error("full-window measurement failed", {
src/crew/requested.ts +1 −1
@@ -149,7 +149,7 @@ async function askAgain(
149149 const pull = getPull(app.db, repo.id, requested.number);
150150 if (!pull) return notMoved(requested, "no pull row");
151151 if (!greenHead(app.db, pull)) return notMoved(requested, "the new head is not green yet");
152 const result = await sendToReview(app, repo, pull, now, { stale: true });
152 const result = await sendToReview(app, repo, pull, now, { stale: true, reviewerId: requested.reviewerId });
153153 if (result === "sent") return { pull: requested.number, did: "asked reviewer" };
154154 return notMoved(
155155 requested,
src/crew/review.ts +19 −5
@@ -646,7 +646,7 @@ export async function sendToReview(
646646 repo: Repo,
647647 pull: Pull,
648648 now = new Date(),
649 { stale = false }: { readonly stale?: boolean } = {},
649 { stale = false, reviewerId }: { readonly stale?: boolean; readonly reviewerId?: string } = {},
650650 ): Promise<"none" | "done" | "sent" | "wait" | "lapsed" | "held"> {
651651 if (getHold(app.db, pull.id) !== undefined) return "held";
652652 const reviewers = reviewersOf(app.db, repo.id);
@@ -683,7 +683,7 @@ export async function sendToReview(
683683 (repo.autonomy === "autonomous" || stale);
684684 if (stage === "wait" || (stage === "lapsed" && !unreviewed)) return stage;
685685 const late = stage === "late" || unreviewed;
686 const reviewer = await queueReview(app, repo, pull, reviewers, history);
686 const reviewer = await queueReview(app, repo, pull, reviewers, history, reviewerId);
687687 if (reviewer === undefined) return "wait";
688688 log.info("green; queued for review", {
689689 repo: `${repo.ownerName}/${repo.name}`,
@@ -706,6 +706,10 @@ async function queueReview(
706706 pull: Pull,
707707 reviewers: readonly Agent[],
708708 history: ReviewHistory,
709 /**
710 * The reviewer who asked for changes on an older head: asked again before anyone else (#18249).
711 */
712 same?: string,
709713 ): Promise<Agent | undefined> {
710714 const issue = getIssueById(app.db, pull.id);
711715 if (!issue) return undefined;
@@ -715,7 +719,9 @@ async function queueReview(
715719 const pool = others.length > 0 ? others : reviewers;
716720 // A person's ask may name the reviewer (#4568).
717721 const ask = getReviewRequest(app.db, pull.id);
718 const named = ask?.reviewerId == null ? undefined : pool.find((r) => r.user.id === ask.reviewerId);
722 const named =
723 (same === undefined ? undefined : reviewers.find((r) => r.user.id === same)) ??
724 (ask?.reviewerId == null ? undefined : pool.find((r) => r.user.id === ask.reviewerId));
719725 // A lane revert (`checks/revert_lane.ts`) goes to the least busy reviewer whatever it touches:
720726 // it takes a change back, so it needs no security or design eye, only a quick one.
721727 const reviewer =
@@ -870,6 +876,15 @@ const said = new Map<string, string>();
870876 */
871877 const outage = { down: false, resent: 0 };
872878
879 /**
880 * The order the sweep sends in: a lane revert first (the fix for a red main), then the owner's own
881 * pulls, then the rest; each group keeps the order it came in, oldest first (#18249).
882 */
883 export function reviewOrder<P extends Pick<Pull, "authorId">>(open: readonly P[], repo: Pick<Repo, "ownerId">, isRevert: (p: P) => boolean): P[] {
884 const rank = (p: P) => (isRevert(p) ? 0 : p.authorId === repo.ownerId ? 1 : 2);
885 return open.map((p, i) => ({ p, i, r: rank(p) })).sort((a, b) => a.r - b.r || a.i - b.i).map((x) => x.p);
886 }
887
873888 /** Every open pull of a repository, oldest first, paged past the list cap. */
874889 function openPullsOldestFirst(db: Database, repoId: string): Pull[] {
875890 const all: Pull[] = [];
@@ -918,8 +933,7 @@ export async function sweepReviews(app: App, now = new Date()): Promise<number>
918933 if (!repo) continue;
919934 // A lane revert is the fix for a red main: sent before every other pull (`checks/revert_lane.ts`).
920935 const open = openPullsOldestFirst(app.db, repo.id);
921 const reverts = open.filter((p) => isLaneRevert(app.db, p));
922 for (const pull of reverts.length === 0 ? open : [...reverts, ...open.filter((p) => !reverts.includes(p))]) {
936 for (const pull of reviewOrder(open, repo, (p) => isLaneRevert(app.db, p))) {
923937 if (queued >= SWEEP_SENDS) return forgetSettled(stalled, queued, resent);
924938 // An agent's green pull, or a stranger's the crew filters (#9575).
925939 const owed =
src/flow/numbers.ts +1
@@ -27,6 +27,7 @@ export function flowNumbers(
2727 n["landed.hour"] = count(landed?.hours[0] ?? 0);
2828 n["landed.day"] = count(landed?.items.length ?? 0);
2929 n.median = flow.medianAskToLiveMs === null ? "—" : span(flow.medianAskToLiveMs);
30 n.greenReview = flow.medianGreenToReviewMs === null ? "—" : span(flow.medianGreenToReviewMs);
3031 for (const s of stages) {
3132 const t = out.get(s.key);
3233 n[`stage.${s.key}.waiting`] = count(s.waiting);
src/flow/pages_read.ts +2
@@ -145,6 +145,7 @@ export interface StageFlow extends StageThroughput {
145145 export interface PanelFlow {
146146 readonly stages: readonly StageFlow[];
147147 readonly medianAskToLiveMs: number | null;
148 readonly medianGreenToReviewMs: number | null;
148149 }
outdated

Clean: greenToReview on PanelFlow is not read by the panel, which only draws the median. Remove it from the interface and from panelFlow; the per-pull list already reaches the MCP and telemetry through readThroughput.

149150
150151 /**
@@ -155,6 +156,7 @@ export interface PanelFlow {
155156 export function panelFlow(flow: Throughput, keep: PipelineKey | null): PanelFlow {
156157 return {
157158 medianAskToLiveMs: flow.medianAskToLiveMs,
159 medianGreenToReviewMs: flow.medianGreenToReviewMs,
158160 stages: flow.stages.map((t) => ({
159161 key: t.key,
160162 hours: t.hours,
src/flow/throughput.ts +46 −1
@@ -72,6 +72,19 @@ export interface Throughput {
7272 readonly stages: readonly StageThroughput[];
7373 /** Median ask→live in milliseconds, over what went live in the last 24 hours; null when nothing did. */
7474 readonly medianAskToLiveMs: number | null;
75 /**
76 * Per pull, green to the first verdict on it, for verdicts passed in the last 24 hours (#18249).
77 */
78 readonly greenToReview: readonly GreenToReview[];
79 /** The median of `greenToReview`; null when no pull was reviewed. */
80 readonly medianGreenToReviewMs: number | null;
81 }
82
83 /** One pull's wait from its head going green to the crew's first verdict on that head. */
84 export interface GreenToReview {
85 readonly label: string;
86 readonly href: string;
87 readonly ms: number;
7588 }
7689
7790 /** The columns every query below returns; the page builds the label and link from them. */
@@ -227,9 +240,41 @@ function askToLive(db: Database, now: Date): number[] {
227240 return out;
228241 }
229242
243 /**
244 * Green to first review, per pull (#18249): the crew's first verdict on each head passed in the
245 * last 24 hours, less when that head's check first went green. A pull keeps its slowest head's
246 * wait; an imported verdict (an origin's) and a head with no green check are not counted.
247 */
248 function greenToReview(db: Database, now: Date): GreenToReview[] {
249 const since = new Date(now.getTime() - HOURS * HOUR_MS).toISOString();
250 const rows = db
251 .query<{ at: string; green: string; owner: string; repo: string; number: number; title: string | null; sealed: number }, [string, string]>(
252 `SELECT v.at, g.at AS green, u.username AS owner, r.name AS repo, i.number, i.title, i.sealed
253 FROM (SELECT issue_id, commit_oid, MIN(created_at) AS at FROM review
254 WHERE origin_author IS NULL AND commit_oid != '' GROUP BY issue_id, commit_oid) v
255 JOIN (SELECT issue_id, commit_oid, MIN(finished_at) AS at FROM run
256 WHERE kind = 'check' AND state = 'ok' AND finished_at IS NOT NULL AND issue_id IS NOT NULL
257 GROUP BY issue_id, commit_oid) g ON g.issue_id = v.issue_id AND g.commit_oid = v.commit_oid
258 JOIN issue i ON i.id = v.issue_id JOIN repo r ON r.id = i.repo_id JOIN user u ON u.id = r.owner_id
259 WHERE v.at >= ?1 AND v.at <= ?2 AND v.at >= g.at`,
260 )
261 .all(since, now.toISOString());
262 const byPull = new Map<string, GreenToReview>();
263 for (const row of rows) {
264 const ms = Date.parse(row.at) - Date.parse(row.green);
265 const key = `${row.owner}/${row.repo}#${row.number}`;
266 const label = `${row.repo} #${row.number}${row.sealed === 1 ? " (sealed)" : row.title === null ? "" : ` ${row.title}`}`;
267 if ((byPull.get(key)?.ms ?? -1) < ms) byPull.set(key, { label, href: `/${row.owner}/${row.repo}/pulls/${row.number}`, ms });
268 }
269 return [...byPull.values()].sort((a, b) => b.ms - a.ms);
270 }
271
230272 /** Every stage's outflow over the last 24 hours, left to right, and the median ask→live. */
231273 export function readThroughput(db: Database, keys: readonly PipelineKey[], now = new Date()): Throughput {
274 const reviewed = greenToReview(db, now);
232275 return {
276 greenToReview: reviewed,
277 medianGreenToReviewMs: median(reviewed.map((r) => r.ms)),
233278 stages: keys.map((key) => stageThroughput(db, key, now)),
234279 medianAskToLiveMs: median(askToLive(db, now)),
235280 };
@@ -267,5 +312,5 @@ export const stageOut = (t: StageThroughput): StageOut => ({
267312 export function throughputSays(t: Throughput): string {
268313 const landed = t.stages.find((s) => s.key === "approved");
269314 const median = t.medianAskToLiveMs === null ? "—" : hoursSpan(t.medianAskToLiveMs);
270 return `landed ${landed?.hours[0] ?? 0} in the last hour · ${landed?.items.length ?? 0} in 24 h · median ask→live ${median} (24 h)`;
315 return `landed ${landed?.hours[0] ?? 0} in the last hour · ${landed?.items.length ?? 0} in 24 h · median ask→live ${median} (24 h) · median green→review ${t.medianGreenToReviewMs === null ? "—" : hoursSpan(t.medianGreenToReviewMs)} (24 h)`;
271316 }
src/system/telemetry.ts +2
@@ -146,6 +146,8 @@ function flowBody(x: {
146146 throughput: {
147147 says: throughputSays(flow),
148148 medianAskToLiveMs: flow.medianAskToLiveMs,
149 medianGreenToReviewMs: flow.medianGreenToReviewMs,
150 greenToReview: flow.greenToReview.map((g) => ({ pull: g.label, ms: g.ms })),
149151 stages: flow.stages.map(stageOut),
150152 },
151153 // A private repository's name is not an agent's to read, so its queue line is cut.
src/web/pages/flow-panel.ts +4
@@ -65,6 +65,9 @@ import { slotsBlock } from "../flow_slots.ts";
6565 /** What the panel draws that is read off the thread: the figures, what each stage let out, what reviewers repeated and why ready issues wait. */
6666 export type PanelPicture = Pick<BoardsPicture, "fig" | "flow" | "repeats" | "held">;
6767
68 /** A first verdict later than this after a green check marks the figure. */
69 const SLOW_FIRST_VERDICT_MS = 3_600_000;
70
6871 /**
6972 * The events that move work between stages. The region has no address of its own, so the page's
7073 * script refetches the page for it at most once in 30 s
outdated

Clean: this constant landed between the doc comment of FLOW_LIVE (the events that move work between stages) and FLOW_LIVE itself, so that comment now documents the wrong line. Move SLOW_FIRST_VERDICT_MS and its comment above the FLOW_LIVE doc block.

@@ -160,6 +163,7 @@ export function flowPanel(app: App, reader: Reader, url: URL, base: string, slot
160163 const strip = figures([
outdated

Principles 1 and 8: the caption says the median, the count, the slowest wait and its label in one line, and the figure's label already says what it is. Cut it to one plain sentence, for example 'median wait for the first verdict, last 24 hours'. The slowest pull is in the MCP flow tool already. The 3 600 000 attn threshold is a magic number: name it. Also add a test on /flow for the figure, its attn state and its empty state.

161164 figure("Landed, last hour", html`<span data-landed-hour data-k="landed.hour">${count(landed?.hours[0] ?? 0)}</span>`, html`<span data-landed-day data-k="landed.day">${count(landedDay)}</span> ${landedDay === 1 ? "change" : "changes"} landed on main in 24 hours`, outHref(base, "approved", null), landed === undefined ? null : homeSpark(landed.hours)),
162165 figure("Asked to live", html`<span data-median data-k="median">${flow.medianAskToLiveMs === null ? "—" : span(flow.medianAskToLiveMs)}</span>`, flow.medianAskToLiveMs === null ? "nothing asked for went live in 24 hours" : "median from an ask to it serving, last 24 hours", outHref(base, "live", null)),
166 ...(flow.medianGreenToReviewMs === null ? [] : [figure("Green to review", html`<span data-k="greenReview">${span(flow.medianGreenToReviewMs)}</span>`, "median wait for the first verdict, last 24 hours", outHref(base, "review", null), null, flow.medianGreenToReviewMs > SLOW_FIRST_VERDICT_MS ? "attn" : null)]),
163167 figure("Opened to landed", lead.medianHours === null ? "—" : html`<span data-median-hours>${span(lead.medianHours * 3_600_000)}</span>`, lead.medianHours === null ? "nothing landed in 24 hours" : html`median for a pull; the slowest took <span data-max-hours>${span((lead.maxHours ?? 0) * 3_600_000)}</span>`, outHref(base, "approved", null)),
164168 figure("Waiting to start", count(ready?.waiting ?? 0), ready === undefined || ready.waiting === 0 ? "no ready issue waits for a builder" : `ready ${ready.waiting === 1 ? "issue" : "issues"}; the oldest has waited ${waited(ready, now) ?? "no time"}`, "#held", null, worst?.key === "ready" ? "attn" : null),
165169 figure("Checks passing", checked === 0 ? "—" : `${Math.round((passed / checked) * 100)}%`, checked === 0 ? "no check finished in 24 hours" : `${count(passed)} of ${count(checked)} checks passed in 24 hours`, outHref(base, "checking", null), null, checked > 0 && passed / checked < 0.5 ? "attn" : null),
test/flow-panel-green-review.test.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * The flow panel's Green to review figure: shown once a pull was reviewed, marked when slow
3 * (#18249).
4 */
5 import { afterEach, beforeEach, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { id } from "../src/kernel/id.ts";
12 import { flowPanel } from "../src/web/pages/flow-panel.ts";
13
14 let dir: string;
15 let app: App;
16 let uid: string;
17 let rid: string;
18 let n = 0;
19 const ago = (min: number) => new Date(Date.now() - min * 60_000).toISOString();
20
21 beforeEach(async () => {
22 dir = mkdtempSync(join(tmpdir(), "forge-panel-gr-"));
23 app = createApp({ dataDir: dir, port: 0 });
24 const u = await createUser(app.db, { username: "scout", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
25 if (!u.ok) throw new Error(u.error);
26 uid = u.value.id;
27 rid = id();
28 app.db.query(`INSERT INTO repo (id, owner_id, name, visibility) VALUES (?1, ?2, 'pub', 'public')`).run(rid, uid);
29 });
30 afterEach(() => {
31 app.db.close();
32 rmSync(dir, { recursive: true, force: true });
33 });
34
35 /**
36 * A pull whose check went green `greenMin` minutes ago and whose first verdict came `waitMin`
37 * later.
38 */
39 function reviewed(greenMin: number, waitMin: number): void {
40 const iid = id();
41 const oid = `${"a".repeat(39)}${++n % 10}`;
42 app.db.query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, created_at) VALUES (?1, ?2, ?3, 'pull', 't', '', ?4, ?5)`).run(iid, rid, n, uid, ago(greenMin + 5));
43 app.db.query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', ?2, '', ?3)`).run(iid, `b/${n}`, oid);
44 app.db.query(`INSERT INTO run (id, repo_id, kind, state, issue_id, commit_oid, finished_at) VALUES (?1, ?2, 'check', 'ok', ?3, ?4, ?5)`).run(id(), rid, iid, oid, ago(greenMin));
45 app.db.query(`INSERT INTO review (id, issue_id, author_id, state, commit_oid, created_at) VALUES (?1, ?2, ?3, 'approved', ?4, ?5)`).run(id(), iid, uid, oid, ago(greenMin - waitMin));
46 }
47
48 const draw = () => String(flowPanel(app, { kind: "owner" }, new URL("http://x/flow"), "/flow"));
49 const figure = (html: string) => html.match(/<a [^>]*>(?:(?!<a )[\s\S])*?Green to review[\s\S]*?<\/a>/)?.[0] ?? "";
50
51 test("with no review in the day the figure is not drawn", () => {
52 expect(draw()).not.toContain("Green to review");
53 });
54
55 test("a quick first verdict shows the median, without the attention mark", () => {
56 reviewed(120, 10);
57 const html = draw();
58 expect(html).toContain("Green to review");
59 expect(html).toContain("median wait for the first verdict, last 24 hours");
60 expect(html).toContain('data-k="greenReview"');
61 expect(figure(html)).not.toContain("attn");
62 });
63
64 test("a first verdict over an hour late marks the figure", () => {
65 reviewed(300, 180);
66 const f = figure(draw());
67 expect(f).toContain("Green to review");
68 expect(f).toContain("attn");
69 });
test/flow-throughput.test.ts +3 −3
@@ -185,7 +185,7 @@ describe("/flow: actual throughput per stage", () => {
185185 expect(page).toContain('<span data-landed-day data-k="landed.day">6</span> changes landed on main in 24 hours');
186186 expect(page).toContain('<span data-median data-k="median">3h 30m</span>');
187187 expect(throughputSays(readThroughput(app.db, PIPELINE, new Date(NOW)))).toBe(
188 "landed 2 in the last hour · 6 in 24 h · median ask→live 3.5 h (24 h)",
188 "landed 2 in the last hour · 6 in 24 h · median ask→live 3.5 h (24 h) · median green→review — (24 h)",
189189 );
190190 expect(page).toMatch(/data-out="landed">\s*<a href="\/boards\?out=landed&amp;hour=0#out" data-hour="0"[^>]*>2<\/a>/);
191191 expect(page).toMatch(/data-day="6"[^>]*>6<\/a>/);
@@ -240,7 +240,7 @@ describe("/flow: actual throughput per stage", () => {
240240 stages: { key: string; out: string; lastHour: number; day: number; hours: number[] }[];
241241 };
242242 };
243 expect(read.throughput.says).toBe("landed 2 in the last hour · 6 in 24 h · median ask→live 3.5 h (24 h)");
243 expect(read.throughput.says).toBe("landed 2 in the last hour · 6 in 24 h · median ask→live 3.5 h (24 h) · median green→review — (24 h)");
244244 expect(read.throughput.medianAskToLiveMs).toBeGreaterThan(3.5 * HOUR - MIN);
245245 expect(read.throughput.stages.map((s) => s.key)).toEqual([...PIPELINE]);
246246 const landed = read.throughput.stages.find((s) => s.key === "approved");
@@ -254,7 +254,7 @@ describe("/flow: actual throughput per stage", () => {
254254
255255 test("in the terminal, an admin's Flow dialog says the headline and each stage's last hour and 24 h", () => {
256256 const lines = flowLines(app.db, new Date(NOW));
257 expect(lines.join(" ").replace(/\s+/g, " ")).toContain("landed 2 in the last hour · 6 in 24 h · median ask→live 3.5 h (24 h)");
257 expect(lines.join(" ").replace(/\s+/g, " ")).toContain("landed 2 in the last hour · 6 in 24 h · median ask→live 3.5 h (24 h) · median green→review — (24 h)");
258258 expect(lines.find((l) => l.startsWith("Approved "))).toMatch(/^Approved\s+2\s+6\s+landed$/);
259259 expect(lines.find((l) => l.startsWith("Checking "))).toMatch(/^Checking\s+2\s+3\s+checks finished$/);
260260 expect(lines.find((l) => l.startsWith("Ready "))).toMatch(/^Ready\s+1\s+1\s+issues started$/);
test/requested.test.ts +17
@@ -176,6 +176,23 @@ describe("a pull with changes requested always moves", () => {
176176 clearRuns();
177177 });
178178
179 test("a new head goes back to the reviewer who asked for changes, not the least busy (#18249)", async () => {
180 const agent = await createAgent(app, alice, { username: "reed" });
181 if (!agent.ok) throw new Error(String(agent.error));
182 expect(addToCrew(app, alice, repo, "reed").ok).toBe(true);
183 const reed = getUserByName(app.db, "reed")!;
184 seatAs(app.db, repo.id, reed.id, "reviewer");
185 // The asking reviewer is busier than reed: routing alone would pick reed.
186 const other = await builderPull();
187 createRun(app.db, { repoId: repo.id, kind: "agent", reason: "review", issueId: other.id, actorId: reviewer.id });
188 const pull = await staleShape();
189 await moveRequested(app, fresh(), 0);
190 const sent = runs(pull, "review");
191 expect(sent).toHaveLength(1);
192 expect(sent[0]!.actorId).toBe(reviewer.id);
193 clearRuns();
194 });
195
179196 test("a verdict on an older head whose new head is not green waits for the check", async () => {
180197 const pull = await builderPull();
181198 changesRequested(pull);
test/review-first.test.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * Reviews never starve behind builders (#18249): the owner's pulls are reviewed first, a green
3 * check on an older main is run again, the reviewer who asked for changes is asked again, and
4 * green→review is measured.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { provideChecksForTest } from "../src/checks/handles.ts";
15 import type { ChecksHandle } from "../src/checks/lane_state.ts";
16 import { recheckStaleGreens, STALE_GREEN_REASON } from "../src/checks/stale_green.ts";
17 import { getPull } from "../src/core/pulls.ts";
18 import type { Repo } from "../src/core/repos.ts";
19 import { createRun, setRunBase } from "../src/core/runs.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { readThroughput, throughputSays } from "../src/flow/throughput.ts";
22 import { reviewOrder } from "../src/crew/review.ts";
23 import { resolveOid } from "../src/git/merge.ts";
24 import { repoDir } from "../src/git/repos.ts";
25
26 let dataDir: string;
27 let app: App;
28 let alice: User;
29 let repo: Repo;
30 let n = 0;
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-review-first-"));
34 app = createApp({ dataDir, port: 0 });
35 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
36 if (!a.ok) throw new Error(a.error);
37 alice = a.value;
38 const made = await createRepo(app, alice, { name: "engine", visibility: "private" });
39 if (!made.ok) throw new Error(String(made.error));
40 repo = made.value;
41 await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "a.ts", content: "export {};\n" }] });
42 provideChecksForTest(app, {
43 request: async (r: Repo, env: string, oid: string, reason: string, issueId?: string) =>
44 createRun(app.db, { repoId: r.id, kind: "check", env, commitOid: oid, reason, issueId }),
45 } as unknown as ChecksHandle);
46 });
47 afterAll(async () => {
48 app.db.close();
49 await rm(dataDir, { recursive: true, force: true });
50 });
51
52 async function greenPull(baseOid: string) {
53 const k = ++n;
54 const ask = openIssue(app, alice, repo, { title: `Ask ${k}` });
55 if (!ask.ok) throw new Error(String(ask.error));
56 await commitToBranch(app, alice, repo, { branch: `f/${k}`, base: "main", message: `G${k}`, files: [{ path: `g${k}.ts`, content: `export const g = ${k};\n` }] });
57 const o = await openPull(app, alice, repo, { title: `G${k}`, body: `Closes #${ask.value.number}`, baseBranch: "main", headBranch: `f/${k}` });
58 if (!o.ok) throw new Error(String(o.error));
59 const pull = getPull(app.db, repo.id, o.value.number)!;
60 const run = createRun(app.db, { repoId: repo.id, kind: "check", issueId: pull.id, commitOid: pull.headOid });
61 app.db.query("UPDATE run SET state = 'ok', finished_at = ?2 WHERE id = ?1").run(run.id, new Date(Date.now() - 3_600_000).toISOString());
62 setRunBase(app.db, run.id, baseOid);
63 return pull;
64 }
65
66 const rechecks = (id: string) =>
67 app.db.query<{ n: number }, [string]>(`SELECT COUNT(*) AS n FROM run WHERE issue_id = ? AND reason = '${STALE_GREEN_REASON}'`).get(id)!.n;
68
69 test("a green check of an older main is run again once; one of the current main is not", async () => {
70 const tip = (await resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), "refs/heads/main"))!;
71 const stale = await greenPull("0".repeat(40));
72 const fresh = await greenPull(tip);
73 expect(await recheckStaleGreens(app, repo)).toEqual([stale.number]);
74 expect(rechecks(stale.id)).toBe(1);
75 expect(rechecks(fresh.id)).toBe(0);
76 });
77
78 test("a pull with a verdict on its head is not checked again", async () => {
79 const stale = await greenPull("0".repeat(40));
80 app.db
81 .query("INSERT INTO review (id, issue_id, author_id, state, commit_oid) VALUES ('rv1', ?1, ?2, 'approved', ?3)")
82 .run(stale.id, alice.id, stale.headOid);
83 expect(await recheckStaleGreens(app, repo)).not.toContain(stale.number);
84 });
85
86 test("the sweep reviews a lane revert, then the owner's pulls, then the rest, oldest first", () => {
87 const p = (id: string, authorId: string) => ({ id, authorId });
88 const open = [p("a", "bob"), p("b", alice.id), p("c", "bob"), p("d", alice.id), p("e", "bob")];
89 const order = reviewOrder(open, { ownerId: alice.id }, (x) => x.id === "e").map((x) => x.id);
90 expect(order).toEqual(["e", "b", "d", "a", "c"]);
91 });
92
93 test("green to review is measured per pull and said in the headline", async () => {
94 const pull = await greenPull("0".repeat(40));
95 const green = Date.now() - 3 * 3_600_000;
96 app.db.query("UPDATE run SET finished_at = ?2 WHERE issue_id = ?1 AND kind = 'check'").run(pull.id, new Date(green).toISOString());
97 app.db
98 .query("INSERT INTO review (id, issue_id, author_id, state, commit_oid, created_at) VALUES ('rv2', ?1, ?2, 'approved', ?3, ?4)")
99 .run(pull.id, alice.id, pull.headOid, new Date(green + 2 * 3_600_000).toISOString());
100 const flow = readThroughput(app.db, []);
101 const mine = flow.greenToReview.find((g) => g.href.endsWith(`/pulls/${pull.number}`));
102 expect(mine?.ms).toBe(2 * 3_600_000);
103 expect(flow.medianGreenToReviewMs).not.toBeNull();
104 expect(throughputSays(flow)).toContain("median green→review");
105 });

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

Keyboard shortcuts

Docs