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

Main's page budgets are green again: every page over its SQL budget runs within it #15916

Merged opened this

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

Merged

mason/forge:mason/15913-main-s-page-budgets-are-green-again-ever → main 0 commits fork

  • Merged. mason/15913-main-s-page-budgets-are-green-again-ever was merged into main as 1781060.

Review

Sign in to review this change.
16 files changed +184 −45
scripts/unused-exports-allow.json +1
@@ -136,6 +136,7 @@
136136 "src/kernel/result.ts unwrapOr",
137137 "src/looks/main_looks.ts mainLook",
138138 "src/machines/shell.ts liveSessions",
139 "src/maintain/pause.ts dutyState",
139140 "src/maintenance/standby.ts forgetStandby",
140141 "src/origins/ahead.ts aheadBusy",
141142 "src/origins/git-mirror.ts mirrorOutboundForTest",
src/actions/outsider_decision.ts +17 −13
@@ -6,7 +6,7 @@
66 */
77 import type { App } from "../app.ts";
88 import { noteDecline } from "../core/offer_receipt.ts";
9 import { countWaiting, filerWords, reasonOf } from "../core/reports.ts";
9 import { countWaiting, filerWords, listWaiting, reasonOf } from "../core/reports.ts";
1010 import { canWrite, type Repo } from "../core/repos.ts";
1111 import { getPull } from "../core/pulls.ts";
1212 import { mayApproveGuest, outsideAgentWaits } from "../origins/guest.ts";
@@ -15,7 +15,7 @@ import { err, ok, type Result } from "../kernel/result.ts";
1515 import { waitingOffers } from "./offer.ts";
1616 import { setIssueState } from "./issues.ts";
1717 import { approveGuestPull } from "./pulls.ts";
18 import { acceptReport, dismissReport, waitingReports } from "./reports.ts";
18 import { acceptReport, dismissReport } from "./reports.ts";
1919
2020 /** What a decline says when the owner types nothing: a tap is enough. */
2121 export const DEFAULT_DECLINE = "Not something we will take up right now.";
@@ -46,15 +46,15 @@ export interface OutsiderShelf {
4646 const oneLine = (text: string): string => (text.length > ASK_MAX ? `${text.slice(0, ASK_MAX - 1)}…` : text);
4747
4848 /**
49 * The oldest `OUTSIDER_ROWS_MAX` waiting reports and offers, oldest first, and the total; nothing
50 * for anyone who may not decide them. An offer has no sender to name: it is filed with no account,
51 * so the row says so.
49 * The oldest `OUTSIDER_ROWS_MAX` waiting reports and offers, oldest first, and the total. The
50 * caller has already proven the reader may decide them (a person who writes the repository, which
51 * is also `mayApproveGuest`): /next knows that from its own writer check, so the shelf does not ask
52 * again (#15913: the page's statement budget). An offer has no sender to name: it is filed with no
53 * account, so the row says so.
5254 */
53 export function outsiderRows(app: App, actor: User | undefined, repo: Repo): OutsiderShelf {
54 const waiting = waitingReports(app, actor, repo, OUTSIDER_ROWS_MAX);
55 if (!waiting.ok) return { rows: [], total: 0 };
56 const shelf = offerRows(app, actor, repo);
57 const reports = waiting.value.map((r): OutsiderRow => ({
55 export function outsiderShelf(app: App, repo: Repo): OutsiderShelf {
56 const offers = offerShelf(app, repo);
57 const reports = listWaiting(app.db, repo.id, OUTSIDER_ROWS_MAX).map((r): OutsiderRow => ({
5858 kind: "report",
5959 id: r.id,
6060 sender: filerWords(r.filedBy),
@@ -62,8 +62,8 @@ export function outsiderRows(app: App, actor: User | undefined, repo: Repo): Out
6262 createdAt: r.createdAt,
6363 }));
6464 const reportTotal = reports.length < OUTSIDER_ROWS_MAX ? reports.length : countWaiting(app.db, repo.id);
65 const rows = [...reports, ...shelf.rows].sort((x, y) => x.createdAt.localeCompare(y.createdAt)).slice(0, OUTSIDER_ROWS_MAX);
66 return { rows, total: reportTotal + shelf.total };
65 const rows = [...reports, ...offers.rows].sort((x, y) => x.createdAt.localeCompare(y.createdAt)).slice(0, OUTSIDER_ROWS_MAX);
66 return { rows, total: reportTotal + offers.total };
6767 }
6868
6969 /**
@@ -71,7 +71,11 @@ export function outsiderRows(app: App, actor: User | undefined, repo: Repo): Out
7171 * Nothing for anyone who may not approve a guest (`mayApproveGuest`).
7272 */
7373 export function offerRows(app: App, actor: User | undefined, repo: Repo): OutsiderShelf {
74 if (!mayApproveGuest(app.db, repo, actor)) return { rows: [], total: 0 };
74 return mayApproveGuest(app.db, repo, actor) ? offerShelf(app, repo) : { rows: [], total: 0 };
75 }
76
77 /** The waiting offers as rows, for a caller that has proven the reader may approve a guest. */
78 function offerShelf(app: App, repo: Repo): OutsiderShelf {
7579 const { offers, total } = waitingOffers(app, repo);
7680 return {
7781 rows: offers.map((o): OutsiderRow => ({ kind: "offer", id: String(o.number), sender: OFFER_SENDER, ask: oneLine(o.title), createdAt: o.createdAt })),
src/core/capacity.ts +1 −1
@@ -503,7 +503,7 @@ export function storedCapacity(
503503
504504 /**
505505 * What each of `keys` is now, from one read of the settings table: a pick that needs several keys
506 * costs one statement.
506 * costs one statement (#15913: the issue-size limits on every pick).
507507 */
508508 export function capacityValues<K extends CapacityKey>(db: Database, keys: readonly K[]): Record<K, string> {
509509 const stored = new Map(
src/crew/held.ts +4 −3
@@ -76,7 +76,7 @@ import { retryReason } from "./retry.ts";
7676 import { heldFiles, type FileHold } from "./file_holds.ts";
7777 import { expectedFiles, hotFiles, hotOverlap, pullsTouching, relievedFiles } from "./hot_files.ts";
7878 import { coveredByRedFix } from "./red_fix.ts";
79 import { limitsOf, tooLarge } from "./too_large.ts";
79 import { limitsOf, tooLarge, type Limits } from "./too_large.ts";
8080 import { landedUnder } from "./stalls.ts";
8181 import { isShared, sharedTitles, twinOf, type Twin } from "./twin.ts";
8282 import { variantGroupOf } from "../core/runs.ts";
@@ -283,7 +283,8 @@ export function heldBy(
283283 .filter(([, labels]) => labels.some((l) => l.name === ALONE_GREEN_LABEL))
284284 .map(([id]) => id),
285285 );
286 const limits = limitsOf(app.db);
286 // The size limits, read once for the pass when the first issue gets that far.
287 let limits: Limits | undefined;
287288 const holdOf = (issue: Issue): HoldName | null => {
288289 if (busyIssues.has(issue.id)) return "running";
289290 if (reds.has(issue.number)) return "red_thrice";
@@ -297,7 +298,7 @@ export function heldBy(
297298 if (noKey) return NO_KEY_HELD;
298299 if (crewOff) return CREW_OFF_HELD;
299300 if (flakes.has(issue.id)) return "full_suite_flake";
300 if (tooLarge(app.db, repo, issue, limits)) return "too_large";
301 if (tooLarge(app.db, repo, issue, (limits ??= limitsOf(app.db)))) return "too_large";
301302 if (stalled(app, repo, issue, lastRuns)) return "stalled";
302303 if (capped().get(issue.id) ?? atRunCap(app, repo, issue)) return "run_cap";
303304 if (!isGo(repo) && parkedCount(app.db, repo, issue.id) >= PARK_STRIKES && retryReason(app.db, repo, issue, now) === undefined)
src/flow/next_actor.ts +1 −1
@@ -90,7 +90,7 @@ export function nextOfPull(
9090 live: { readonly headOid: string; readonly conflicts: number },
9191 /** The pull's repository; without one, reviews count as asked for. */
9292 repo: Pick<Repo, "id" | "requireReview"> | undefined,
93 /** The head's check, when the caller already read it: not read twice. */
93 /** The head's check, when the caller already read it for `live.headOid`. */
9494 known?: CheckSummary,
9595 ): Next | null {
9696 if (pull.state !== "open" || pull.mergedAt !== null) return null;
src/flow/path.ts +4 −2
@@ -18,7 +18,7 @@ import { holdsFor } from "../core/holds.ts";
1818 import { getPull, type Pull } from "../core/pulls.ts";
1919 import type { Repo } from "../core/repos.ts";
2020 import { reviewSummariesFor, reviewSummary } from "../core/reviews.ts";
21 import { checksForHeads, checkSummary, type RunState } from "../core/runs.ts";
21 import { checksForHeads, checkSummary, type CheckSummary, type RunState } from "../core/runs.ts";
2222 import { reviewsOff } from "../crew/review.ts";
2323 import { isFirstChange } from "../crew/first_change.ts";
2424 import { nextAsking, nextOfPull, type Next } from "./next_actor.ts";
@@ -110,6 +110,8 @@ export function stepOfPull(
110110 pull: Pull,
111111 live: { readonly headOid: string; readonly conflicts: number },
112112 next: Next | null = pull.state === "open" && pull.mergedAt === null ? nextOfPull(db, pull, live, repo) : null,
113 /** The head's check, when the caller already read it for `live.headOid`. */
114 known?: CheckSummary,
113115 ): PathStep | null {
114116 if (pull.mergedAt !== null) {
115117 const deploys = pull.baseBranch === repo.defaultBranch && getAppByRepo(db, repo.id) !== undefined;
@@ -125,7 +127,7 @@ export function stepOfPull(
125127 if (pull.state !== "open") return null;
126128 return pathStep({
127129 state: "open",
128 check: checkSummary(db, pull.id, live.headOid).state,
130 check: (known ?? checkSummary(db, pull.id, live.headOid)).state,
129131 approvals: reviewSummary(db, pull.id, live.headOid).approvals,
130132 next,
131133 });
src/maintain/pause.ts +54 −6
@@ -63,7 +63,15 @@ export function pauseOnErrors(db: Database, name: string, now = new Date()): boo
6363 */
6464 export function failing(db: Database, name: string, fromRun?: number): { since: string; line: string } | undefined {
6565 const from = fromRun ?? stateRow(db, name)?.from_run ?? 0;
66 const rows = db.query("SELECT started, outcome FROM maintenance_run WHERE duty = ?1 AND id > ?2 AND outcome NOT LIKE 'budget:%' ORDER BY id DESC").all(name, from) as { started: string; outcome: string }[];
66 const rows = db.query("SELECT started, outcome FROM maintenance_run WHERE duty = ?1 AND id > ?2 AND outcome NOT LIKE 'budget:%' ORDER BY id DESC").all(name, from) as Streak;
67 return streakOf(rows);
68 }
69
70 /** A duty's non-budget runs, newest first. */
71 type Streak = { started: string; outcome: string }[];
72
73 /** `failing`'s rule over rows already read: the leading errors, when there are enough of them. */
74 function streakOf(rows: Streak): { since: string; line: string } | undefined {
6775 let n = 0;
6876 while (n < rows.length && errored(rows[n]!.outcome)) n++;
6977 if (n < ERRORS_TO_PAUSE) return undefined;
@@ -81,8 +89,16 @@ function pausedWords(by: string, since: string, now: number): string {
8189
8290 export function dutyState(db: Database, name: string, now = Date.now()): DutyState {
8391 const s = stateRow(db, name);
92 const f = failing(db, name, s?.from_run ?? 0);
93 const last = s?.paused === 1 ? undefined : (db.query("SELECT outcome FROM maintenance_run WHERE duty = ?1 ORDER BY id DESC LIMIT 1").get(name) as { outcome: string } | null)?.outcome;
94 return stateWords(name, s, last, f, now);
95 }
96
97 /**
98 * The row in words, from what was read: the state row, the newest outcome and the failing streak.
99 */
100 function stateWords(name: string, s: Row | null, last: string | undefined, f: { since: string; line: string } | undefined, now: number): DutyState {
84101 if (s?.paused === 1) {
85 const f = failing(db, name, s.from_run);
86102 // The runner's own pause reason already carries the last error: add only the time.
87103 const more = f === undefined ? "" : s.by === "the runner" ? `; failing since ${f.since}` : `; failing since ${f.since}: ${f.line}`;
88104 // A person's reason is only "paused by <handle>", which the opening words already say.
@@ -90,13 +106,45 @@ export function dutyState(db: Database, name: string, now = Date.now()): DutySta
90106 const detail = `${pausedWords(s.by, s.since, now)}${why}${more}`;
91107 return { name, paused: true, says: `${name}: ${detail}.`, detail };
92108 }
93 const last = db.query("SELECT outcome FROM maintenance_run WHERE duty = ?1 ORDER BY id DESC LIMIT 1").get(name) as { outcome: string } | null;
94 const f = failing(db, name, s?.from_run ?? 0);
95 const detail = f ? `on; failing since ${f.since}: ${f.line}` : `on${last && errored(last.outcome) ? `; last run errored: ${last.outcome}` : ""}`;
109 const detail = f ? `on; failing since ${f.since}: ${f.line}` : `on${last !== undefined && errored(last) ? `; last run errored: ${last}` : ""}`;
96110 return { name, paused: false, says: `${name}: ${detail}.`, detail };
97111 }
98112
99 export const dutyStates = (db: Database): DutyState[] => registered.map((d) => dutyState(db, d.name));
113 /**
114 * Every registered duty's state in two statements, whatever the number of duties (#15913: three
115 * per duty made each new duty cost /maintenance three more). The streak query reads only the runs
116 * after a duty's newest `ok` (and after its last resume), the only ones `failing` can count.
117 */
118 export function dutyStates(db: Database, now = Date.now()): DutyState[] {
119 const names = JSON.stringify(registered.map((d) => d.name));
120 const heads = db
121 .query(
122 `SELECT d.value AS name, s.paused, s.reason, s.by, s.since, s.from_run,
123 (SELECT outcome FROM maintenance_run r WHERE r.duty = d.value ORDER BY r.id DESC LIMIT 1) AS last
124 FROM json_each(?1) d LEFT JOIN maintenance_duty_state s ON s.duty = d.value`,
125 )
126 .all(names) as (Partial<Row> & { name: string; last: string | null })[];
127 const streaks = new Map<string, Streak>();
128 const runs = db
129 .query(
130 `WITH edge AS (
131 SELECT d.value AS name, MAX(COALESCE(s.from_run, 0),
132 COALESCE((SELECT o.id FROM maintenance_run o WHERE o.duty = d.value AND o.outcome = 'ok' ORDER BY o.id DESC LIMIT 1), 0)) AS after
133 FROM json_each(?1) d LEFT JOIN maintenance_duty_state s ON s.duty = d.value)
134 SELECT edge.name, r.started, r.outcome FROM edge JOIN maintenance_run r ON r.duty = edge.name AND r.id > edge.after
135 WHERE r.outcome NOT LIKE 'budget:%' ORDER BY r.duty, r.id DESC`,
136 )
137 .all(names) as { name: string; started: string; outcome: string }[];
138 for (const r of runs) {
139 const list = streaks.get(r.name) ?? [];
140 list.push({ started: r.started, outcome: r.outcome });
141 streaks.set(r.name, list);
142 }
143 return heads.map((h) => {
144 const s = h.paused === null || h.paused === undefined ? null : (h as Row);
145 return stateWords(h.name, s, h.last ?? undefined, streakOf(streaks.get(h.name) ?? []), now);
146 });
147 }
100148
101149 export const knownDuty = (name: string): boolean => registered.some((d) => d.name === name);
102150
src/perf/page_budgets/next.ts +1 −1
@@ -1,3 +1,3 @@
11 import type { PageBudget } from "../page_budget.ts";
22
3 export const budget: PageBudget = { page: "next up", pattern: "/:owner/:name/next", medianMs: 50, statements: 66 };
3 export const budget: PageBudget = { page: "next up", pattern: "/:owner/:name/next", medianMs: 50, statements: 63 };
src/web/pages/next.ts +6 −4
@@ -7,7 +7,7 @@
77 * beside each action (`j`/`k` choose the row), which post the same form.
88 */
99 import { keyStep } from "./next_keys.ts";
10 import { DEFAULT_DECLINE, decideOffer, decideOutsider, decisionOf, outsiderRows } from "../../actions/outsider_decision.ts";
10 import { DEFAULT_DECLINE, decideOffer, decideOutsider, decisionOf, outsiderShelf } from "../../actions/outsider_decision.ts";
1111 import { REASON_MAX } from "../../core/reports.ts";
1212 import { placeOf, rankIssue, rankedWords, stepTo, type Place } from "../../actions/next.ts";
1313 import { currentByNumber } from "../../core/estimates.ts";
@@ -222,8 +222,10 @@ function walletRow(ctx: Ctx, repo: Repo, base: string): Html | null {
222222 * here. A decline carries one line of why (the sender reads it at their status link); left empty it
223223 * says the default. Writers only.
224224 */
225 function outsiderSection(ctx: Ctx, repo: Repo, base: string, back: string): Html | null {
226 const { rows, total } = ctx.auth.user === undefined || ctx.auth.user.kind === "agent" ? { rows: [], total: 0 } : outsiderRows(ctx.app, ctx.auth.user, repo);
225 function outsiderSection(ctx: Ctx, repo: Repo, base: string, back: string, writer: boolean): Html | null {
226 // The decider is a person who writes the repository; `writer` already proved the write (#15913).
227 if (!writer || ctx.auth.user?.kind !== "user") return null;
228 const { rows, total } = outsiderShelf(ctx.app, repo);
227229 if (rows.length === 0) return null;
228230 const more = total - rows.length;
229231 const form = (kind: string, id: string, decision: string, extra: Html | null, label: Html): Html => html`<form method="post" action="${base}/next" class="form-actions">
@@ -319,7 +321,7 @@ export function nextPage(ctx: Ctx): Response {
319321 ${chapterLine(ctx, repo, chapters)}
320322 ${growthLine(week7, pauseAt(week7, new Date()), writer && canAdmin(ctx.app.db, repo, ctx.auth.user!), base, back)}
321323 <p class="error" id="next-flash" role="alert" hidden></p>
322 ${outsiderSection(ctx, repo, base, back)}
324 ${outsiderSection(ctx, repo, base, back, writer)}
323325 ${writer ? batchForms(base, back, live) : null}
324326 ${rows.length === 0
325327 ? html`<p class="muted">Nothing is ready: everything open waits for something. <a href="${base}/map">See the map</a>. ${undoButton(live)}</p>`
src/web/pages/repo.ts +11 −6
@@ -97,7 +97,7 @@ import { blobHoldsPrivateKey, holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../
9797 import { countLines, highlightPrefix } from "../code.ts";
9898 import { tailOf, tailSentence } from "../log_tail.ts";
9999 import { latestWave } from "../../story/waves.ts";
100 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
100 import { notePhase, takeSessionTime, timePhaseAsync } from "../../core/route_timing.ts";
101101 import { liveClientJs, liveMount } from "../live.ts";
102102 import { appStrip } from "./apps.ts";
103103 import { growthBody, isAdmin } from "./growth_panel.ts";
@@ -1473,8 +1473,9 @@ export async function repoHome(ctx: Ctx): Promise<Response> {
14731473 const repo = loadRepo(ctx);
14741474 if (!repo) return notFoundPage(ctx);
14751475 noteLook(ctx, repo.id);
1476 const looked = performance.now();
14761477 const record = getAppByRepo(ctx.app.db, repo.id);
1477 if (record === undefined) return await codeHome(ctx, repo);
1478 if (record === undefined) return await codeHome(ctx, repo, { isApp: false, ms: performance.now() - looked });
14781479 if (ctx.url.searchParams.has("ref"))
14791480 return redirect(`${repoBase(repo)}/files${ctx.url.search}`);
14801481 return await studioApp(ctx, repo, record);
@@ -1486,9 +1487,10 @@ export async function repoHome(ctx: Ctx): Promise<Response> {
14861487 export async function repoFiles(ctx: Ctx): Promise<Response> {
14871488 const repo = loadRepo(ctx);
14881489 if (!repo) return notFoundPage(ctx);
1490 const looked = performance.now();
14891491 if (getAppByRepo(ctx.app.db, repo.id) === undefined)
14901492 return redirect(`${repoBase(repo)}${ctx.url.search}`);
1491 return await codeHome(ctx, repo);
1493 return await codeHome(ctx, repo, { isApp: true, ms: performance.now() - looked });
14921494 }
14931495
14941496 /** "Moved from <old path> on <date>" for 30 days after a move; one muted line. */
@@ -1535,10 +1537,13 @@ function reportLine(ctx: Ctx, repo: Repo): Html | null {
15351537 }
15361538
15371539 /** The code at a ref: the tree, the README and the About rail — with, in
1538 * the studio, the offer to make a repository that is not an app one. */
1539 async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
1540 * the studio, the offer to make a repository that is not an app one.
1541 * `appOf` is the caller's app lookup and what it took (the `appof` phase),
1542 * so the page reads the app row once (#15913). */
1543 async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean; readonly ms: number }): Promise<Response> {
15401544 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
1541 const isApp = timePhase(ctx.request, "appof", () => getAppByRepo(ctx.app.db, repo.id) !== undefined);
1545 notePhase(ctx.request, "appof", appOf.ms);
1546 const isApp = appOf.isApp;
15421547 const noApp = isApp ? null : noAppCard(ctx, repo);
15431548 const scope = localScope(ctx, repo);
15441549 const cloneUrl = `${ctx.url.origin}/${repo.ownerName}/${repo.name}.git`;
src/web/studio/change.ts +3 −3
@@ -261,13 +261,13 @@ export function changeHead(
261261 // (async: it reads the head's tree when the child attested one, #13645).
262262 proposal: PullProposalAt | undefined,
263263 ): Html {
264 // The head's check is read once for the next actor and for what a green pull waits for.
265 const check = live === null ? undefined : checkSummary(ctx.app.db, pull.id, live.headOid);
264 // The head's check, read once for the next actor, the path step and the waits-for line (#15913).
265 const check = live === null || pull.state !== "open" || pull.mergedAt !== null ? undefined : checkSummary(ctx.app.db, pull.id, live.headOid);
266266 const next = live === null ? null : nextOfPull(ctx.app.db, pull, live, repo, check);
267267 const step =
268268 live === null && pull.mergedAt === null
269269 ? null
270 : stepOfPull(ctx.app.db, repo, pull, live ?? { headOid: pull.headOid, conflicts: 0 }, next);
270 : stepOfPull(ctx.app.db, repo, pull, live ?? { headOid: pull.headOid, conflicts: 0 }, next, check);
271271 const who = toldBy(ctx.app.db, pull);
272272 const accounts = accountsByName(ctx.app.db, [pull.authorName, who ?? ""], repo.id);
273273 const marks = marksOf(accounts);
test/crew-too-large.test.ts +12 −1
@@ -20,7 +20,8 @@ import { createUser, getUserByName, type User } from "../src/core/users.ts";
2020 import { autonomyTick } from "../src/crew/autonomy.ts";
2121 import { heldNow } from "../src/crew/held.ts";
2222 import { readKnobs } from "../src/crew/knobs.ts";
23 import { handedTooLarge, overLimit, sizeOf, TOO_LARGE_NOTE } from "../src/crew/too_large.ts";
23 import { handedTooLarge, limitsOf, overLimit, sizeOf, TOO_LARGE_NOTE } from "../src/crew/too_large.ts";
24 import { once } from "./helpers/statements.ts";
2425 import { serve, type Servers } from "../src/http/server.ts";
2526
2627 let dataDir: string;
@@ -154,4 +155,14 @@ describe("an issue too large for one run", () => {
154155 expect((await setKnob(app, alice, "boxes", "0")).ok).toBe(false);
155156 await setKnob(app, alice, "boxes", "12");
156157 });
158
159 test("both limits are read in one statement, and a stored value out of range is the default", async () => {
160 await setKnob(app, alice, "chars", "5000");
161 // A row no setter could write (the knob refuses 0): read as unset, as `capacityValue` does.
162 app.db.query("UPDATE forge_setting SET value = '0' WHERE key = 'issue.maxBoxes'").run();
163 let limits = limitsOf(app.db);
164 expect(await once(app.db, () => void (limits = limitsOf(app.db)))).toBe(1);
165 expect(limits).toEqual({ boxes: 12, chars: 5000 });
166 await setKnob(app, alice, "boxes", "12");
167 });
157168 });
test/did-you-mean.test.ts +2 −1
@@ -20,7 +20,8 @@ let servers: Awaited<ReturnType<typeof serve>>;
2020 // 41: the repository page reads the repository's wallet cap, one primary-key read, to show the
2121 // wallet line (#13309).
2222 // 42: whether reports are closed, one read per request from the row (#15053).
23 const FOUND_QUERIES = 37;
23 // 36: the repository home reads its app row once, not twice (#15913).
24 const FOUND_QUERIES = 36;
2425 const BARE_404_QUERIES = 0; // a 404 with no owner/name to suggest from
2526 // The same 404 for a mistyped repository (6 since #15940). One of them is the noindex lookup that
2627 // answerGet makes for every /:owner/:name route before its handler runs (1e71740ab, #14305,
test/maintain-duty-states.test.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * `dutyStates` reads every duty in two statements (#15913), and says exactly what `dutyState` says
3 * for each one: paused by a person, paused by the runner, failing, errored once, resumed, budget
4 * stops in a streak, and never run.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtempSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { dutyState, dutyStates, pauseOnErrors, setPaused } from "../src/maintain/pause.ts";
12 import { duties } from "../src/maintain/registry.ts";
13 import { record } from "../src/maintain/runs.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15 import { once } from "./helpers/statements.ts";
16
17 quietLogs();
18 let root = "";
19 let app: App;
20 beforeAll(() => {
21 root = mkdtempSync(join(tmpdir(), "forge-duty-states-"));
22 app = createApp({ dataDir: root, port: 0 });
23 });
24 afterAll(() => rmSync(root, { recursive: true, force: true }));
25
26 let t = Date.parse("2026-11-01T00:00:00Z");
27 const run = (duty: string, outcome: string) => {
28 const at = new Date((t += 60_000));
29 record(app.db, { duty, started: at, finished: at, findings: [], actions: [], outcome });
30 };
31
32 test("every duty's state, batched, is the state read one duty at a time", async () => {
33 expect(duties.length).toBeGreaterThan(7);
34 const [byPerson, byRunner, failingOn, erroredOnce, resumed, budgeted, okAfterErrors] = duties.map((d) => d.name);
35 setPaused(app.db, byPerson!, true, "alice", new Date(t));
36 for (const o of ["ok", "failed: one", "failed: two", "failed: three\nmore"]) run(byRunner!, o);
37 pauseOnErrors(app.db, byRunner!, new Date(t));
38 for (const o of ["failed: a", "failed: b", "failed: c", "failed: d"]) run(failingOn!, o);
39 for (const o of ["ok", "failed: once"]) run(erroredOnce!, o);
40 for (const o of ["failed: x", "failed: y", "failed: z"]) run(resumed!, o);
41 pauseOnErrors(app.db, resumed!, new Date(t));
42 setPaused(app.db, resumed!, false, "alice", new Date(t));
43 run(resumed!, "failed: after resume");
44 for (const o of ["failed: p", "budget: over", "failed: q", "budget: over", "failed: r"]) run(budgeted!, o);
45 for (const o of ["failed: 1", "failed: 2", "failed: 3", "ok"]) run(okAfterErrors!, o);
46
47 const now = t + 3_600_000;
48 const batched = dutyStates(app.db, now);
49 expect(batched).toEqual(duties.map((d) => dutyState(app.db, d.name, now)));
50 const said = new Map(batched.map((s) => [s.name, s.detail]));
51 expect(said.get(failingOn!)).toStartWith("on; failing since ");
52 expect(said.get(budgeted!)).toStartWith("on; failing since ");
53 expect(said.get(erroredOnce!)).toBe("on; last run errored: failed: once");
54 expect(said.get(okAfterErrors!)).toBe("on");
55 expect(said.get(resumed!)).toBe("on; last run errored: failed: after resume");
56 expect(batched.find((s) => s.name === byRunner)?.paused).toBe(true);
57
58 // Constant in the number of duties: adding one costs the board nothing.
59 expect(await once(app.db, () => void dutyStates(app.db, now))).toBe(2);
60 });
test/open-pulls-ceiling.test.ts +5 −1
@@ -25,6 +25,7 @@ import { queueAgentRun } from "../src/crew/dispatch.ts";
2525 import { plannerHeld } from "../src/flow/planner_held.ts";
2626 import { quietLogs } from "./helpers/globals.ts";
2727 import { seatAs } from "./helpers/seat.ts";
28 import { once } from "./helpers/statements.ts";
2829
2930 quietLogs();
3031
@@ -117,7 +118,7 @@ describe("the open-pull ceiling", () => {
117118 expect(queueAgentRun(app, fresh(), issue, builder, "assigned")).toBeDefined();
118119 });
119120
120 test("the kept panel says the paused line from now, not from when it was kept", () => {
121 test("the kept panel says the paused line from now, not from when it was kept", async () => {
121122 setPullsCeiling(app, alice, fresh(), "3");
122123 expect(growthPanelFor(app.db, fresh(), alice, true)?.pullsHeld).toBe("paused: 3 of 3 pulls open");
123124 // a pull closing is no ceiling setter: the kept panel must still follow the count
@@ -125,5 +126,8 @@ describe("the open-pull ceiling", () => {
125126 expect(growthPanelFor(app.db, fresh(), alice, true)?.pullsHeld).toBeNull();
126127 app.db.query("UPDATE issue SET state = 'open' WHERE id = ?1").run(pulls[0]!.id);
127128 expect(growthPanelFor(app.db, fresh(), alice, true)?.pullsHeld).toBe("paused: 3 of 3 pulls open");
129 // The fresh line is one statement on the kept panel, which every repository page asks (#15913).
130 const r = fresh();
131 expect(await once(app.db, () => void growthPanelFor(app.db, r, alice, true))).toBe(1);
128132 });
129133 });
test/pages-budget.test.ts +2 −2
@@ -56,8 +56,8 @@ const DEFAULT = { statements: 60, git: 8 };
5656 const HEAVIER: Record<string, { statements?: number; git?: number }> = {
5757 "/:owner/:name/issues/:number": { statements: 71 }, // +1: whether the repository is archived, so its pages say noindex (#14305)
5858 "/next": { statements: 90 }, // a new page: measured 90 warm over the fixture's repositories, one ranking per administered repository, at most GROUPS_MAX = 5 (#15870)
59 "/:owner/:name/next": { statements: 66 }, // -6 (#15940): the page's repository read once per request, the palette lists skip counts, the runs tab reuses the app read; +2: the waiting offers and the decision check beside the reports (#15887); +1: the size limits of held issues, one read of both (#15845); +2: the waiting outsider reports, the decider check and the list (#15840); +1: whether the repository is archived (#14305); +1: the wallet row, one read of the monthly cap (#13529); +1: the growth line, one read for the week, the open counts and the planner pause (#12290, #12867)
60 "/:owner/:name/pulls/:number": { statements: 116 }, // +1: whether the reports door is closed, one primary-key read per request, never from memory (#15053); +1: whether the repository is archived (#14305); +1: the desk hold on the pull, one read of the notes that link it (#12536); +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
59 "/:owner/:name/next": { statements: 63 }, // -3 (#15913): the waiting offers and outsider reports ride the page's own writer check, the open-pull ceiling and count are one statement; -6 (#15940): the page's repository read once per request, the palette lists skip counts, the runs tab reuses the app read; +2: the waiting offers and the decision check beside the reports (#15887); +1: the size limits of held issues, one read of both (#15845); +2: the waiting outsider reports, the decider check and the list (#15840); +1: whether the repository is archived (#14305); +1: the wallet row, one read of the monthly cap (#13529); +1: the growth line, one read for the week, the open counts and the planner pause (#12290, #12867)
60 "/:owner/:name/pulls/:number": { statements: 115 }, // +1: what a green pull waits for (#15812), and the head's check is read once for it, the next actor and the step (#15913); +1: whether the reports door is closed, one primary-key read per request, never from memory (#15053); +1: whether the repository is archived (#14305); +1: the desk hold on the pull, one read of the notes that link it (#12536); +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
6161 "/api/v1/asks": { statements: 61 }, // +1: the stopped apps someone asked for, one read of the viewer's archived repositories (#12277)
6262 "/board": { statements: 72 }, // +1: the forge-copy read for the tell box (#12037); +1: the vitals read the database's growth (#12025); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps
6363 "/settings/capacity": { statements: 70 },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs