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

With the weekly window full, the forge still rechecks stale reds and runs measurements, and /week says what it did #15828

Merged opened this

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

Merged

scout/forge:scout/15821-with-the-weekly-window-full-the-forge-st → main 0 commits fork 6 threads · 6 unresolved

  • Merged. scout/15821-with-the-weekly-window-full-the-forge-st was merged into main as c834aad.

Review

Sign in to review this change.
7 files changed +285 −0
docs/features/week-while-full.md added +14
@@ -0,0 +1,14 @@
1 ---
2 topic: Tell the crew
3 row: When the weekly window is full, red pulls are still checked again
4 ---
5 # When the weekly window is full (#15821)
6
7 With the provider's weekly window used up, no builder starts. The forge still does what needs no model: a pull whose red check is older than main's latest green is checked again, once after each commit of main that checks green, three at a time. The check is the forge's own and costs nothing from the allowance.
8
9 Where to see it: the repository's **The week** page (`/<owner>/<repo>/week`) and the same screen in the terminal (`ssh` in, open the repository, then the week). One line, shown only when something ran in the last seven days: "While the window was full: 6 rechecks, 2 landed." A recheck "landed" when it came back green and the pull was then merged.
10
11 - Code: `src/checks/full_window_recheck.ts` (`recheckWhenFull`, called from the autonomy tick; `whileFullLine` is the one wording both doors print).
12 - Not the same as `crew/stale_reds.ts`, which wakes a builder and needs a free slot.
13 - Held pulls and pulls without a head are skipped.
14 - Model-free measurements while the window is full are #15911.
src/checks/full_window_recheck.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * What the forge does with no model while the weekly window is full (#15821). Not the sweep in
3 * `crew/stale_reds.ts`: that one wakes a builder, reworks, parks or closes a red pull, and a full
4 * window has no slot for it. This one only asks the forge's own check to run again on a pull whose
5 * red is older than main's latest green, so a red that main's fix made stale can turn green and
6 * land.
7 *
8 * Once per green main commit: a pull is rechecked once after each commit of `main` that checked
9 * green, timed by that commit's first green run, so a re-run of one green commit queues nothing.
10 * `/week` reads {@link whileFull} back.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import type { App } from "../app.ts";
15 import { listOpenPulls } from "../core/pulls.ts";
16 import type { Repo } from "../core/repos.ts";
17 import { getHold } from "../core/holds.ts";
18 import { crewWeekFor } from "../crew/week_read.ts";
19 import { checksFor } from "./service.ts";
20
21 /** The reason of the check this queues. */
22 export const STALE_RED_REASON = "stale_red";
23
24 /** Rechecks queued in one tick: a trickle, not a burst on the check queue. */
25 export const STALE_RED_PER_TICK = 3;
26
27 /**
28 * When main's latest green commit first checked green, or undefined when main has none. Keyed on
29 * the commit, so a second green run of one commit does not count as a new green.
30 */
31 function mainGreenAt(db: Database, repo: Repo): string | undefined {
32 const row = db
33 .query<{ at: string | null }, [string, string]>(
34 `SELECT MIN(finished_at) AS at FROM run WHERE repo_id = ?1 AND kind = 'check' AND issue_id IS NULL
35 AND env = ?2 AND state = 'ok'
36 AND commit_oid = (SELECT commit_oid FROM run WHERE repo_id = ?1 AND kind = 'check' AND issue_id IS NULL
37 AND env = ?2 AND state = 'ok' ORDER BY id DESC LIMIT 1)`,
38 )
39 .get(repo.id, repo.defaultBranch);
40 return row?.at ?? undefined;
41 }
42
43 /** Whether this head's newest check is a failure that finished before `green`. */
44 function staleRed(db: Database, issueId: string, oid: string, green: string): boolean {
45 const last = db
46 .query<{ state: string; at: string | null }, [string, string]>(
47 `SELECT state, finished_at AS at FROM run WHERE kind = 'check' AND issue_id = ?1 AND commit_oid = ?2
48 ORDER BY id DESC LIMIT 1`,
49 )
50 .get(issueId, oid);
51 if (last === null || last.state !== "failed" || last.at === null || last.at >= green) return false;
52 const done = db
53 .query<{ n: number }, [string, string]>(
54 `SELECT COUNT(*) AS n FROM run WHERE kind = 'check' AND issue_id = ?1 AND reason = '${STALE_RED_REASON}'
55 AND created_at > ?2`,
56 )
57 .get(issueId, green);
58 return (done?.n ?? 0) === 0;
59 }
60
61 /** Queue the rechecks; the pull numbers queued. Call only while the window is full. */
62 export async function recheckStaleReds(app: App, repo: Repo): Promise<number[]> {
63 const green = mainGreenAt(app.db, repo);
64 const checks = checksFor(app);
65 if (green === undefined || checks === undefined) return [];
66 const queued: number[] = [];
67 for (const pull of listOpenPulls(app.db, repo.id)) {
68 if (queued.length >= STALE_RED_PER_TICK) break;
69 if (pull.headOid === "" || pull.mergedAt !== null || getHold(app.db, pull.id) !== undefined) continue;
70 if (!staleRed(app.db, pull.id, pull.headOid, green)) continue;
71 const run = await checks.request(repo, `pull-${pull.number}`, pull.headOid, STALE_RED_REASON, pull.id);
72 if (run?.reason === STALE_RED_REASON) queued.push(pull.number);
73 }
74 return queued;
75 }
76
77 /** Recheck only when the week leaves no slot; with a free slot the crew's own sweep has it. */
78 export async function recheckWhenFull(app: App, repo: Repo, now: Date): Promise<number[]> {
79 return crewWeekFor(app, repo, now)?.slots === 0 ? recheckStaleReds(app, repo) : [];
80 }
81
82 export interface WhileFull {
83 readonly rechecks: number;
84 readonly landed: number;
85 }
86
87 /**
88 * What the model-free rechecks did in the last seven days: queued, and landed after a green one.
89 */
90 export function whileFull(db: Database, repoId: string, now: Date): WhileFull {
91 const since = new Date(now.getTime() - 7 * 86_400_000).toISOString();
92 const row = db
93 .query<{ n: number; landed: number }, [string, string]>(
94 `SELECT COUNT(*) AS n,
95 COUNT(DISTINCT CASE WHEN r.state = 'ok' AND p.merged_at IS NOT NULL AND p.merged_at >= r.created_at
96 THEN r.issue_id END) AS landed
97 FROM run r LEFT JOIN pull p ON p.issue_id = r.issue_id
98 WHERE r.repo_id = ?1 AND r.kind = 'check' AND r.reason = '${STALE_RED_REASON}' AND r.created_at >= ?2`,
99 )
100 .get(repoId, since);
101 return { rechecks: row?.n ?? 0, landed: row?.landed ?? 0 };
102 }
103
104 /** The `/week` line, or null when nothing ran. */
105 export function whileFullLine(w: WhileFull): string | null {
106 if (w.rechecks === 0) return null;
107 const s = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
108 return `While the window was full: ${s(w.rechecks, "recheck", "rechecks")}, ${w.landed} landed.`;
109 }
src/crew/autonomy.ts +8
@@ -156,6 +156,7 @@ import { sweepRepeats } from "./repeat_checks.ts";
156156 import { breathe } from "../kernel/breathe.ts";
157157 import { keepBatch } from "../flow/red_batches.ts";
158158 import { recordQueueFlakes } from "../checks/flake.ts";
159 import { recheckWhenFull } from "../checks/full_window_recheck.ts";
159160 import { sharedVitals, vitalsMisses, vitalsWords } from "../flow/vitals.ts";
160161 import { moveRequested, tallyRequested, tallyWords } from "./requested.ts";
161162 import { passLanded } from "./box_pass.ts";
@@ -1376,6 +1377,13 @@ export async function autonomyTick(
13761377 error: String(error),
13771378 });
13781379 });
1380 // With the week's window full, stale reds are still checked again: no model runs (#15821).
1381 await recheckWhenFull(app, current, now).catch((error) => {
1382 log.error("stale red recheck failed", {
outdated

Indentation of the catch body is off by two columns from the call. Run the formatter and keep the file's pattern.

1383 repo: `${repo.ownerName}/${repo.name}`,
outdated

Untested branch: slots === 0 is the whole feature. Add a test through autonomyTick (or extract a small predicate) that fails if the guard is removed.

1384 error: String(error),
1385 });
1386 });
13791387 // What reviewers keep asking for becomes an issue to automate it (#8716).
13801388 try {
13811389 await sweepRepeats(app, current, now);
src/tui/screens/week.ts +8
@@ -9,6 +9,7 @@
99 * updates the screen here.
1010 */
1111
12 import { whileFull, whileFullLine } from "../../checks/full_window_recheck.ts";
1213 import { takeProposal } from "../../actions/week.ts";
1314 import { canRead, canWrite, getRepoById, type Repo } from "../../core/repos.ts";
1415 import { polishSpend, polishWords } from "../../crew/polish_share.ts";
@@ -45,6 +46,12 @@ export function polishLine(f: Session, repo: Repo): string {
4546 return polishWords(polishSpend(f.db, now.id, now.polishShare, new Date()));
4647 }
4748
49 /** The page's line of what ran with no model while the window was full; empty when nothing did. */
50 export function fullWindowLines(f: Pick<Session, "db">, repo: Repo): string[] {
51 const line = whileFullLine(whileFull(f.db, repo.id, new Date()));
52 return line === null ? [] : [line];
53 }
54
4855 export function weekScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4956 const state = new ListState();
5057 let retro: Retro | undefined;
@@ -103,6 +110,7 @@ export function weekScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
103110 ? ["The forge writes this when the weekly window closes. None has closed yet."]
104111 : summaryLines(retro)),
105112 polishLine(f, repo),
113 ...fullWindowLines(f, repo),
106114 ];
107115 const [head, list] = split(area, "v", [len(lines.length + 1), fill(1)]);
108116 lines.forEach((line, i) =>
src/web/pages/week.ts +8
@@ -5,6 +5,7 @@
55 * and nothing else on the page changes anything.
66 */
77 import { takeProposal } from "../../actions/week.ts";
8 import { whileFull, whileFullLine } from "../../checks/full_window_recheck.ts";
89 import { polishSpend } from "../../crew/polish_share.ts";
910 import { canWrite, type Repo } from "../../core/repos.ts";
1011 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -84,6 +85,12 @@ function polishBlock(ctx: Ctx, repo: Repo): Html {
8485 )}</div>`;
8586 }
8687
88 /** What ran with no model while the window was full, in one line; nothing when nothing did. */
89 function fullLine(ctx: Ctx, repo: Repo): Html | null {
90 const line = whileFullLine(whileFull(ctx.app.db, repo.id, new Date()));

The terminal /week screen (src/tui/screens/week.ts) lacks this line; both doors must show it. Principle 1/8: the wording is plain, good.

91 return line === null ? null : html`<p data-while-full class="muted">${line}</p>`;
92 }
93
8794 export function weekPage(ctx: Ctx): Response {
8895 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
8996 const repo = loadRepo(ctx);
@@ -100,6 +107,7 @@ export function weekPage(ctx: Ctx): Response {
100107 : `Written when the window ended ${retro.weekEnd.slice(0, 10)}, once, and never edited.`} <a href="${base}/next">Next up</a></p>
101108 </div>
102109 ${polishBlock(ctx, repo)}
110 ${fullLine(ctx, repo)}
103111 ${retro === undefined ? null : screen(base, retro, takenOf(ctx.app.db, repo.id, retro.weekEnd), writer)}`;
104112 const response = page({ ctx, title: `The week · ${repo.name}`, crumbs: crumbsFor(repo), palette: repoPalette(ctx, repo), body });
105113 notePhase(ctx.request, "render", performance.now() - rendering);
test/full-window-recheck.test.ts added +128
@@ -0,0 +1,128 @@
1 /**
2 * With the window full, a red older than main's latest green is checked again once; a fresh red is
3 * not (#15821).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { openIssue } from "../src/actions/issues.ts";
11 import { openPull } from "../src/actions/pulls.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { provideChecksForTest, type ChecksHandle } from "../src/checks/service.ts";
14 import { recheckStaleReds, recheckWhenFull, STALE_RED_REASON, whileFull, whileFullLine } from "../src/checks/full_window_recheck.ts";
15 import { getPull } from "../src/core/pulls.ts";
16 import type { Repo } from "../src/core/repos.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { noteMeasure } from "../src/core/measure.ts";
19 import { PLATFORM } from "../src/core/subscriptions.ts";
20 import { forgetWeek } from "../src/crew/week_read.ts";
21 import { fullWindowLines } from "../src/tui/screens/week.ts";
22 import { createRun } from "../src/core/runs.ts";
23
24 let dataDir: string;
25 let app: App;
26 let alice: User;
27 let repo: Repo;
28 let n = 0;
29 const T = Date.now();
30 const at = (m: number) => new Date(T + m * 60_000).toISOString();
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-stale-red-"));
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 function finish(id: string, state: string, minutes: number) {
53 app.db.query("UPDATE run SET state = ?2, created_at = ?3, finished_at = ?3 WHERE id = ?1").run(id, state, at(minutes));
54 }
55
56 async function redPull(redAt: number) {
57 const k = ++n;
58 const ask = openIssue(app, alice, repo, { title: `Ask ${k}` });
59 if (!ask.ok) throw new Error(String(ask.error));
60 await commitToBranch(app, alice, repo, { branch: `f/${k}`, base: "main", message: `R${k}`, files: [{ path: `r${k}.ts`, content: `export const r = ${k};\n` }] });
61 const o = await openPull(app, alice, repo, { title: `R${k}`, body: `Closes #${ask.value.number}`, baseBranch: "main", headBranch: `f/${k}` });
62 if (!o.ok) throw new Error(String(o.error));
63 const pull = getPull(app.db, repo.id, o.value.number)!;
64 finish(createRun(app.db, { repoId: repo.id, kind: "check", issueId: pull.id, commitOid: pull.headOid }).id, "failed", redAt);
65 return pull;
66 }
67
68 const rechecks = (id: string) =>
69 app.db.query<{ n: number }, [string]>(`SELECT COUNT(*) AS n FROM run WHERE issue_id = ?1 AND reason = '${STALE_RED_REASON}'`).get(id)!.n;
70
71 test("nothing is queued before main has a green", async () => {
72 const p = await redPull(-60);
73 expect(await recheckStaleReds(app, repo)).toEqual([]);
74 expect(rechecks(p.id)).toBe(0);
75 });
76
77 test("a stale red is queued once, a fresh red is not", async () => {
78 const stale = await redPull(-50);
79 const fresh = await redPull(10);
80 finish(createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "g1" }).id, "ok", 0);
81 const first = await recheckStaleReds(app, repo);
82 expect(first).toContain(stale.number);
83 expect(first).not.toContain(fresh.number);
84 expect(rechecks(fresh.id)).toBe(0);
85 const again = await recheckStaleReds(app, repo);
86 expect(again).not.toContain(stale.number);
87 expect(rechecks(stale.id)).toBe(1);
88 // A second green run of the same main commit is not a new green: nothing is queued again.
89 finish(createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "g1" }).id, "ok", 5);
90 expect(await recheckStaleReds(app, repo)).not.toContain(stale.number);
91 expect(rechecks(stale.id)).toBe(1);
92 });
93
94 const spendWeek = (usedPct: number) => {
95 noteMeasure(app.db, PLATFORM, {
96 window: "week",
97 usedPct,
98 resetsAt: new Date(Date.now() + 6 * 86_400_000).toISOString(),
99 observedAt: new Date().toISOString(),
100 });
101 forgetWeek();
102 };
103
104 test("rechecks run only when the week has no slot, never with one free", async () => {
105 const p = await redPull(-40);
106 spendWeek(10);
107 expect(await recheckWhenFull(app, repo, new Date())).toEqual([]);
108 expect(rechecks(p.id)).toBe(0);
109 spendWeek(100);
110 expect(await recheckWhenFull(app, repo, new Date())).toContain(p.number);
111 expect(rechecks(p.id)).toBe(1);
112 });
113
114 test("the line counts rechecks and the one that landed, on the page's wording and the terminal's", () => {
115 const rows = app.db.query<{ id: string; issue_id: string }, []>(`SELECT id, issue_id FROM run WHERE reason = '${STALE_RED_REASON}' ORDER BY id`).all();
116 const landed = rows[0]!;
117 finish(landed.id, "ok", 20);
118 app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(landed.issue_id, at(30));
119 const w = whileFull(app.db, repo.id, new Date(T + 3_600_000));
120 expect(w.rechecks).toBe(rows.length);
121 expect(w.landed).toBe(1);
122 const line = `While the window was full: ${rows.length} rechecks, 1 landed.`;
123 expect(whileFullLine(w)).toBe(line);
124 expect(whileFullLine({ rechecks: 1, landed: 0 })).toBe("While the window was full: 1 recheck, 0 landed.");
125 expect(whileFullLine({ rechecks: 0, landed: 0 })).toBeNull();
126 // Both doors print the same words: the terminal's lines are the line.
127 expect(fullWindowLines({ db: app.db }, repo)).toEqual([line]);
128 });
test/week-doors.test.ts +10
@@ -326,6 +326,15 @@ describe("the week's doors", () => {
326326 expect(nextUp(forge.db, repo).rows.map((r) => r.issue.number)).not.toContain(latestRetro(forge.db, repo.id)!.proposals[0]!.number);
327327 });
328328
329 test("the page says what ran with no model while the window was full, and says nothing before it did", async () => {
330 const get = async () => (await fetch(`${base}/alice/plan/week`, { headers: { cookie: aliceCookie } })).text();
331 expect(await get()).not.toContain("data-while-full");
332 createRun(forge.db, { repoId: repo.id, kind: "check", reason: "stale_red" });
333 const body = await get();
334 expect(body).toContain("data-while-full");
335 expect(body).toContain("While the window was full: 1 recheck, 0 landed.");
336 });
337
329338 test("the terminal shows the retrospective and a reader's key takes nothing", async () => {
330339 const heard = latestRetro(forge.db, repo.id)!;
331340 expect(heard.proposals.length).toBeGreaterThan(1);
@@ -343,6 +352,7 @@ describe("the week's doors", () => {
343352 send("enter");
344353 await settleApp(app);
345354 expect(app.screen.toText()).toContain("shipped");
355 expect(app.screen.toText()).toContain("While the window was full: 1 recheck, 0 landed.");
346356 send("j");
347357 send("a");
348358 await settleApp(app);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs