Public: anyone can read this; the crew can change it.
Check slots per repository: each app gets a guaranteed share, the forge borrows what's idle #16946
Check · Review · Land · Live done — Landed and live in production.
check-slots → main 0 commits 4 threads · 4 unresolved
20 files
changed +709
−10
- docs/features/check-slots.md
- scripts/doorless-allow.json
- src/actions/check_slots.ts
- src/checks/check_slots.ts
- src/checks/lane_state.ts
- src/checks/scheduler.ts
- src/checks/service.ts
- src/checks/start.ts
- src/core/migration-pins/20261201121000-repo-check-slots.pin
- src/core/migrations/20261201121000-repo-check-slots.ts
- src/core/repo_fields.ts
- src/core/repos.ts
- src/generated/migrations.ts
- src/http/server.ts
- src/tui/screens/autonomy.ts
- src/web/pages/boards-slots.ts
- src/web/pages/boards-view.ts
- src/web/pages/settings.ts
- test/check-slots.test.ts
- test/tui-autonomy.test.ts
docs/features/check-slots.md added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: How many pull checks each repository is guaranteed at once | |
| 4 | --- | |
| 5 | # Check slots per repository | |
| 6 | ||
| 7 | Every repository is guaranteed some of the forge's check slots (`checks.concurrency`) for its pull checks: 1 by default, more where one repository does most of the work (the forge's own, say 5 of 8). Within its slots a pull's check starts as soon as one is free. Above them a repository borrows a free slot only when more are free than the other waiting repositories are still owed, so an app with one pull waiting gets its slot at the next one that frees, and an idle forge lends every slot. Nothing running is ever stopped to make room; the longest a small app waits is one check. Main's checks, a rebase's check and the verify lane never wait on a grant. | |
| 8 | ||
| 9 | - **Settings** (`src/web/pages/settings.ts`, `#check-slots`): the repository's slots, how many of its pull checks run now and how many wait; shown while it has pull checks running or waiting, once its slots were set, or from /boards' link (`?check-slots`). Its admin may lower them; raising them is a site admin's. The grants above 1 together leave at least one slot for every app at 1 (on 8 slots: 5 for the forge, or 4 and 3, never 4 and 4). | |
| 10 | - **The terminal** (`src/tui/screens/autonomy.ts`): the Autonomy screen says the slots and what runs now; `g` sets them. | |
| 11 | - **Boards** (`src/web/pages/boards-slots.ts`): "Check slots by repository", shown while any pull check runs or waits, lists each such repository: used of its grant, borrowed, waiting. | |
| 12 | - **A held check's log** says why, once: "queued, held: trevato/forge at its grant of 5; tess/app's 1 is reserved". | |
| 13 | ||
| 14 | Proof: `test/check-slots.test.ts` (admission, no starvation with the forge's queue always full, the bounds, who may set them, the Boards rows). The rule is `grantHold` in `src/checks/check_slots.ts`, applied in `src/checks/scheduler.ts`; the setting is `setCheckSlots` (`src/actions/check_slots.ts`). |
scripts/doorless-allow.json −1
src/actions/check_slots.ts added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | /** | |
| 2 | * Set a repository's guaranteed check slots (`checks/check_slots.ts`). A repository's admin may | |
| 3 | * lower its own; raising it is a site admin's, since it takes slots every other app shares. A | |
| 4 | * grant is a whole number from 1 up, and the grants above the default together leave at least one | |
| 5 | * slot of checks.concurrency for every app at 1: on 8 slots the forge may hold 5, two repositories | |
| 6 | * 4 and 3, never 4 and 4. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { capacityCount, capacityDefault } from "../core/capacity.ts"; | |
| 11 | import { getRepoById, writeCheckSlots, type Repo } from "../core/repos.ts"; | |
| 12 | import type { User } from "../core/users.ts"; | |
| 13 | import { CHECKS_CEILING } from "../checks/lane_state.ts"; | |
| 14 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 15 | import { requireRepoAdmin } from "./access.ts"; | |
| 16 | ||
| 17 | /** The forge's check slots, as the scheduler reads them. */ | |
| 18 | export function checkPool(app: App): number { | |
| 19 | return Math.min(CHECKS_CEILING, capacityCount(app.db, "checks.concurrency", Number(capacityDefault("checks.concurrency")) || 1)); | |
| 20 | } | |
| 21 | ||
| 22 | export function setCheckSlots(app: App, actor: User | undefined, repo: Repo, slots: number): Result<Repo, string> { | |
| 23 | const admin = requireRepoAdmin(app, actor, repo); | |
| 24 | if (!admin.ok) return err("not_found"); | |
| 25 | if (!Number.isInteger(slots) || slots < 1) return err("Check slots are a whole number, 1 or more."); | |
| 26 | if (slots > repo.checkSlots && actor?.isAdmin !== true) return err("Raising a repository's check slots is a site admin's: they come out of every app's share."); | |
| 27 | const pool = checkPool(app); | |
| 28 | const others = app.db | |
| 29 | .query<{ n: number | null }, [string]>("SELECT SUM(check_slots) AS n FROM repo WHERE check_slots > 1 AND id != ?1 AND archived_at IS NULL") | |
| 30 | .get(repo.id)?.n ?? 0; | |
| 31 | const granted = others + (slots > 1 ? slots : 0); | |
| 32 | if (slots > 1 && granted > pool - 1) | |
| 33 | return err(`At most ${Math.max(1, pool - 1 - others)} here: grants above 1 already hold ${others} of the forge's ${pool} check slots, and one stays for every app at 1.`); | |
| 34 | if (slots === repo.checkSlots) return ok(repo); | |
| 35 | writeCheckSlots(app.db, repo.id, slots); | |
| 36 | app.bus.append({ | |
| 37 | kind: "repo.settings_updated", | |
| 38 | repoId: repo.id, | |
| 39 | actorId: admin.value.id, | |
| 40 | payload: { changed: { checkSlots: { from: repo.checkSlots, to: slots } } }, | |
| 41 | }); | |
| 42 | return ok(getRepoById(app.db, repo.id)!); | |
| 43 | } |
src/checks/check_slots.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * Per-repository check slots (app-runner-grants.md §3): each repository is guaranteed | |
| 3 | * `repo.checkSlots` of the forge's checks.concurrency for its pull checks (default 1; the forge's | |
| 4 | * own repository more). Within its grant a repository's check starts as before. Above it, it | |
| 5 | * borrows a free slot only when more slots are free than the other waiting repositories are still | |
| 6 | * owed, so a small app's check starts at the next slot that frees, and an idle forge lends all of | |
| 7 | * it. No check is ever stopped to make room. Order inside a repository stays `pick.ts`'s. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import { listActive } from "../core/runs.ts"; | |
| 12 | ||
| 13 | /** A repository's pull checks now. */ | |
| 14 | export interface PullChecks { | |
| 15 | readonly running: number; | |
| 16 | readonly waiting: number; | |
| 17 | } | |
| 18 | ||
| 19 | /** | |
| 20 | * Each repository's pull checks running and waiting now, by id: what the settings row, the | |
| 21 | * terminal's Autonomy screen and the Boards fold say. One read of the active checks. | |
| 22 | */ | |
| 23 | export function pullChecksByRepo(db: Database): Map<string, PullChecks> { | |
| 24 | const out = new Map<string, { running: number; waiting: number }>(); | |
| 25 | for (const run of listActive(db, "check")) { | |
| 26 | if (run.issueId === null || (run.state !== "running" && run.state !== "queued")) continue; | |
| 27 | const c = out.get(run.repoId) ?? { running: 0, waiting: 0 }; | |
| 28 | if (run.state === "running") c.running++; | |
| 29 | else c.waiting++; | |
| 30 | out.set(run.repoId, c); | |
| 31 | } | |
| 32 | return out; | |
| 33 | } | |
| 34 | ||
| 35 | /** One repository's (`pullChecksByRepo`); none running or waiting when it has none. */ | |
| 36 | export const pullChecksOf = (db: Database, repoId: string): PullChecks => pullChecksByRepo(db).get(repoId) ?? { running: 0, waiting: 0 }; | |
| 37 | ||
| 38 | /** What admission reads at one pick: the running pull checks per repository, and who waits. */ | |
| 39 | export interface SlotView { | |
| 40 | /** Pull checks running now, by repository id. */ | |
| 41 | readonly running: ReadonlyMap<string, number>; | |
| 42 | /** A repository's guaranteed slots. */ | |
| 43 | readonly grant: (repoId: string) => number; | |
| 44 | /** The repositories with a pull check queued now. */ | |
| 45 | readonly waiting: ReadonlySet<string>; | |
| 46 | /** Check slots free now. */ | |
| 47 | readonly free: number; | |
| 48 | } | |
| 49 | ||
| 50 | /** Why a repository above its grant waits: what it is at, and who the free slots are kept for. */ | |
| 51 | export interface GrantHold { | |
| 52 | readonly used: number; | |
| 53 | readonly grant: number; | |
| 54 | /** Each waiting repository still owed slots, and how many, most owed first. */ | |
| 55 | readonly owed: readonly { readonly repoId: string; readonly slots: number }[]; | |
| 56 | } | |
| 57 | ||
| 58 | /** Undefined when `repoId` may start a pull check now; else why it waits (`GrantHold`). */ | |
| 59 | export function grantHold(repoId: string, view: SlotView): GrantHold | undefined { | |
| 60 | const used = view.running.get(repoId) ?? 0; | |
| 61 | const grant = view.grant(repoId); | |
| 62 | if (used < grant) return undefined; | |
| 63 | const owed: { repoId: string; slots: number }[] = []; | |
| 64 | for (const other of view.waiting) { | |
| 65 | if (other === repoId) continue; | |
| 66 | const slots = Math.max(0, view.grant(other) - (view.running.get(other) ?? 0)); | |
| 67 | if (slots > 0) owed.push({ repoId: other, slots }); | |
| 68 | } | |
| 69 | const reserved = owed.reduce((n, o) => n + o.slots, 0); | |
| 70 | if (view.free > reserved) return undefined; | |
| 71 | return { used, grant, owed: owed.sort((a, b) => b.slots - a.slots || (a.repoId < b.repoId ? -1 : 1)) }; | |
| 72 | } | |
| 73 | ||
| 74 | /** | |
| 75 | * The queue log's line for a hold: "held: trevato/forge at its grant of 5; tess/app's 1 is | |
| 76 | * reserved". | |
| 77 | */ | |
| 78 | export function holdLine(hold: GrantHold, name: (repoId: string) => string, held: string): string { | |
| 79 | const shown = hold.owed.slice(0, 2).map((o) => `${name(o.repoId)}'s ${o.slots}`); | |
| 80 | const more = hold.owed.length - shown.length; | |
| 81 | const kept = shown.join(", ") + (more > 0 ? ` and ${more} more` : ""); | |
| 82 | const total = hold.owed.reduce((n, o) => n + o.slots, 0); | |
| 83 | return `held: ${held} at its grant of ${hold.grant}; ${kept} ${total === 1 ? "is" : "are"} reserved`; | |
| 84 | } |
src/checks/lane_state.ts +2
| @@ -200,6 +200,8 @@ export interface LaneState { | ||
| 200 | 200 | */ |
| 201 | 201 | readonly diskWaiting: Set<string>; |
| 202 | 202 | readonly memoryWaiting: Set<string>; |
| 203 | /** Queued pull checks their repository's grant holds (`check_slots.ts`), each said once. */ | |
| 204 | readonly grantWaiting: Set<string>; | |
| 203 | 205 | /** The verification-lane run in flight, which holds no check slot. */ |
| 204 | 206 | verifying: string | undefined; |
| 205 | 207 | /** How long main's check after a land waits before it may start. */ |
src/checks/scheduler.ts +67 −5
| @@ -19,6 +19,7 @@ import { slotted, capacity } from "./lane_state.ts"; | ||
| 19 | 19 | import { pickNext, holdsLastSlot } from "./pick.ts"; |
| 20 | 20 | import { start } from "./start.ts"; |
| 21 | 21 | import { startVerify } from "./verify_lane.ts"; |
| 22 | import { grantHold, holdLine, type SlotView } from "./check_slots.ts"; | |
| 22 | 23 | |
| 23 | 24 | /** |
| 24 | 25 | * An account at its concurrent-checks limit (`settings/quotas.ts`) keeps |
| @@ -26,9 +27,7 @@ import { startVerify } from "./verify_lane.ts"; | ||
| 26 | 27 | */ |
| 27 | 28 | function atLimit(lane: LaneState, run: Run): boolean { |
| 28 | 29 | const { app } = lane; |
| 29 | const owner = getRepoById(app.db, run.repoId)?.ownerId; | |
| 30 | if (owner === undefined) return false; | |
| 31 | const full = checkLimitSentence(app.db, owner, lane.inFlight.keys()); | |
| 30 | const full = limitSentence(lane, run); | |
| 32 | 31 | if (full === undefined) return false; |
| 33 | 32 | if (!lane.waiting.has(run.id)) { |
| 34 | 33 | lane.waiting.add(run.id); |
| @@ -37,8 +36,58 @@ function atLimit(lane: LaneState, run: Run): boolean { | ||
| 37 | 36 | return true; |
| 38 | 37 | } |
| 39 | 38 | |
| 39 | /** Why the run's account may start no check now (`settings/quotas.ts`); undefined when it may. */ | |
| 40 | function limitSentence(lane: LaneState, run: Run): string | undefined { | |
| 41 | const owner = getRepoById(lane.app.db, run.repoId)?.ownerId; | |
| 42 | return owner === undefined ? undefined : checkLimitSentence(lane.app.db, owner, lane.inFlight.keys()); | |
| 43 | } | |
| 44 | ||
| 45 | /** `owner/name` of a repository, for a log line; its id when it is gone. */ | |
| 46 | function repoName(lane: LaneState, repoId: string): string { | |
| 47 | const repo = getRepoById(lane.app.db, repoId); | |
| 48 | return repo === undefined ? repoId : `${repo.ownerName}/${repo.name}`; | |
| 49 | } | |
| 50 | ||
| 51 | /** | |
| 52 | * What admission reads now: pull checks running per repository, the repositories with one queued, | |
| 53 | * and the slots free (`check_slots.ts`). A main or rebase check counts as running but is never | |
| 54 | * held: the pipeline does not wait on a grant. | |
| 55 | */ | |
| 56 | function slotView(lane: LaneState, queued: readonly Run[]): SlotView { | |
| 57 | const running = new Map<string, number>(); | |
| 58 | for (const run of listActive(lane.app.db, "check")) | |
| 59 | // A check started this pass is in flight before its claim marks it running. | |
| 60 | if ((run.state === "running" || lane.inFlight.has(run.id)) && !inVerifyLane(run.env)) running.set(run.repoId, (running.get(run.repoId) ?? 0) + 1); | |
| 61 | const grants = new Map<string, number>(); | |
| 62 | const grantOf = (repoId: string): number => { | |
| 63 | const known = grants.get(repoId); | |
| 64 | if (known !== undefined) return known; | |
| 65 | const grant = getRepoById(lane.app.db, repoId)?.checkSlots ?? 1; | |
| 66 | grants.set(repoId, grant); | |
| 67 | return grant; | |
| 68 | }; | |
| 69 | return { | |
| 70 | running, | |
| 71 | grant: grantOf, | |
| 72 | waiting: new Set(queued.filter((run) => run.issueId !== null).map((run) => run.repoId)), | |
| 73 | free: capacity(lane) - gatesInFlight() - slotted(lane), | |
| 74 | }; | |
| 75 | } | |
| 76 | ||
| 77 | /** Whether a pull check waits on its repository's grant; says why in its log once. */ | |
| 78 | function heldByGrant(lane: LaneState, run: Run, view: SlotView): boolean { | |
| 79 | if (run.issueId === null) return false; | |
| 80 | const hold = grantHold(run.repoId, view); | |
| 81 | if (hold === undefined) return false; | |
| 82 | if (!lane.grantWaiting.has(run.id)) { | |
| 83 | lane.grantWaiting.add(run.id); | |
| 84 | appendRunLog(lane.app.config.dataDir, run.id, `queued, ${holdLine(hold, (id) => repoName(lane, id), repoName(lane, run.repoId))}`); | |
| 85 | } | |
| 86 | return true; | |
| 87 | } | |
| 88 | ||
| 40 | 89 | /** `pickNext` among `queued`, passing over any whose account is at its limit. */ |
| 41 | function startable(lane: LaneState, queued: readonly Run[]): Run | undefined { | |
| 90 | function startable(lane: LaneState, queued: readonly Run[], grants = false): Run | undefined { | |
| 42 | 91 | const { app, options } = lane; |
| 43 | 92 | // At 80% used no check starts (#11799): they stay queued, one line each, and the tick asks |
| 44 | 93 | // again. |
| @@ -61,7 +110,16 @@ function startable(lane: LaneState, queued: readonly Run[]): Run | undefined { | ||
| 61 | 110 | } |
| 62 | 111 | return undefined; |
| 63 | 112 | } |
| 113 | // A repository above its grant borrows only what no waiting repository is owed. | |
| 64 | 114 | let rest = queued; |
| 115 | if (grants) { | |
| 116 | // Only a check that could start now is owed a slot, or slots would idle while nothing can | |
| 117 | // take them. `queued` already leaves out what red main, the crew hold and a gate's last slot | |
| 118 | // hold, and disk or memory holds stop everything above; one whose account is at its limit | |
| 119 | // reserves nothing either. | |
| 120 | const view = slotView(lane, queued.filter((run) => limitSentence(lane, run) === undefined)); | |
| 121 | rest = queued.filter((run) => !heldByGrant(lane, run, view)); | |
| 122 | } | |
| 65 | 123 | const isApproved = approvedOnce(app.db); |
| 66 | 124 | const rankOf = rankOnce(app.db); |
| 67 | 125 | const isOutside = outsideOnce(app.db); |
| @@ -123,7 +181,11 @@ export function schedule(lane: LaneState): void { | ||
| 123 | 181 | const waiting = crewHolds |
| 124 | 182 | ? others.filter((run) => run.issueId === null || !lane.pullHold.held(run.id, (options.holdNow ?? Date.now)())) |
| 125 | 183 | : others; |
| 126 | const next = startable(lane, rebases) ?? startable(lane, held ? waiting.filter((run) => run.issueId === null) : waiting); | |
| 184 | // A rebase's check finishes a pull and never waits on a grant; the rest are held to theirs, | |
| 185 | // reckoned over the pull checks that could start now. | |
| 186 | const next = | |
| 187 | startable(lane, rebases) ?? | |
| 188 | startable(lane, held ? waiting.filter((run) => run.issueId === null) : waiting, true); | |
| 127 | 189 | if (!next) return; |
| 128 | 190 | const repo = getRepoById(app.db, next.repoId); |
| 129 | 191 | if (!repo) return; |
src/checks/service.ts +1
src/checks/start.ts +1
| @@ -21,6 +21,7 @@ export function start(lane: LaneState, run: Run, repo: Repo, adopted = false): v | ||
| 21 | 21 | lane.waiting.delete(run.id); |
| 22 | 22 | lane.diskWaiting.delete(run.id); |
| 23 | 23 | lane.memoryWaiting.delete(run.id); |
| 24 | lane.grantWaiting.delete(run.id); | |
| 24 | 25 | const abort = new AbortController(); |
| 25 | 26 | const low = inVerifyLane(run.env); |
| 26 | 27 | if (low) lane.verifying = run.id; |
src/core/migration-pins/20261201121000-repo-check-slots.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 1fa740da6edd935d37364ed6f0dece4381cbee85e82e7e63cfb736943428cad8 |
src/core/migrations/20261201121000-repo-check-slots.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | // A repository's guaranteed check slots (`checks/check_slots.ts`): of the forge's | |
| 2 | // checks.concurrency, how many this repository's pull checks may hold while others wait. Above it | |
| 3 | // a repository borrows only what nobody waiting is owed. Default 1: every app gets its one. | |
| 4 | // Additive. | |
| 5 | export default ` | |
| 6 | ALTER TABLE repo ADD COLUMN check_slots INTEGER NOT NULL DEFAULT 1; | |
| 7 | `; |
src/core/repo_fields.ts +1
src/core/repos.ts +18 −1
| @@ -163,6 +163,12 @@ export interface Repo { | ||
| 163 | 163 | readonly reviewerSlots: number; |
| 164 | 164 | /** Percent of a week's agent spend polish may take, 0 to 50 (#8853). */ |
| 165 | 165 | readonly polishShare: number; |
| 166 | /** | |
| 167 | * Pull-check slots this repository is guaranteed of the forge's checks.concurrency | |
| 168 | * (`checks/check_slots.ts`): default 1; above it, it borrows only what no waiting repository | |
| 169 | * is owed. | |
| 170 | */ | |
| 171 | readonly checkSlots: number; | |
| 166 | 172 | readonly autonomyBy: string | null; |
| 167 | 173 | /** |
| 168 | 174 | * "Outsiders may trigger the crew": whether someone who cannot write here |
| @@ -244,6 +250,7 @@ interface RepoRow { | ||
| 244 | 250 | planner_slots: number; |
| 245 | 251 | reviewer_slots: number; |
| 246 | 252 | polish_share: number; |
| 253 | check_slots: number; | |
| 247 | 254 | autonomy_by: string | null; |
| 248 | 255 | crew_outsiders: number; |
| 249 | 256 | decisions_by: string; |
| @@ -302,6 +309,7 @@ function toRepo(row: RepoRow): Repo { | ||
| 302 | 309 | plannerSlots: row.planner_slots, |
| 303 | 310 | reviewerSlots: row.reviewer_slots, |
| 304 | 311 | polishShare: row.polish_share, |
| 312 | checkSlots: row.check_slots, | |
| 305 | 313 | autonomyBy: row.autonomy_by, |
| 306 | 314 | crewOutsiders: row.crew_outsiders === 1, |
| 307 | 315 | decisionsBy: isDecisionsBy(row.decisions_by) ? row.decisions_by : "me", |
| @@ -1141,7 +1149,7 @@ const SHOWN = [ | ||
| 1141 | 1149 | "repo.id", "repo.owner_id", "user.username", "repo.name", "repo.visibility", "repo.description", |
| 1142 | 1150 | "repo.default_branch", "repo.protect_default", "repo.require_review", "repo.require_checks", |
| 1143 | 1151 | "repo.landing", "repo.autonomy", "repo.autonomy_direction", "repo.autonomy_slots", |
| 1144 | "repo.planner_slots", "repo.reviewer_slots", "repo.polish_share", "repo.autonomy_by", | |
| 1152 | "repo.planner_slots", "repo.reviewer_slots", "repo.polish_share", "repo.check_slots", "repo.autonomy_by", | |
| 1145 | 1153 | "repo.crew_outsiders", "repo.decisions_by", "repo.plans_need_nod", "repo.is_template", "repo.direction_issue_id", |
| 1146 | 1154 | "repo.fork_parent_id", "repo.sealed_for", "repo.archived_at", "repo.origin_id", |
| 1147 | 1155 | "repo.origin_full_name", "repo.origin_html_url", "repo.last_fetch_at", "repo.fetch_error", |
| @@ -1752,6 +1760,15 @@ export function updateRepoSettings( | ||
| 1752 | 1760 | return getRepoById(db, repo.id)!; |
| 1753 | 1761 | } |
| 1754 | 1762 | |
| 1763 | /** | |
| 1764 | * Write a repository's guaranteed check slots. Not a setting `updateRepoSettings` takes: only | |
| 1765 | * `actions/check_slots.ts` writes it, after its bounds and who may raise it. | |
| 1766 | */ | |
| 1767 | export function writeCheckSlots(db: Database, repoId: string, slots: number): void { | |
| 1768 | db.query("UPDATE repo SET check_slots = ?2 WHERE id = ?1").run(repoId, slots); | |
| 1769 | forgetListings(db); | |
| 1770 | } | |
| 1771 | ||
| 1755 | 1772 | /** Each setting `updateRepoSettings` writes, and the column it lives in. */ |
| 1756 | 1773 | const SETTING_COLUMNS: readonly (readonly [keyof Omit<RepoSettings, "archived">, string])[] = [ |
| 1757 | 1774 | ["visibility", "visibility"], |
src/generated/migrations.ts +2
| @@ -443,6 +443,7 @@ import m438 from "../core/migrations/20261130170100-chat-build-lane.ts"; | ||
| 443 | 443 | import m439 from "../core/migrations/20261130235220-run-check-plan.ts"; |
| 444 | 444 | import m440 from "../core/migrations/20261201000000-games.ts"; |
| 445 | 445 | import m441 from "../core/migrations/20261201120000-first-change-forge.ts"; |
| 446 | import m442 from "../core/migrations/20261201121000-repo-check-slots.ts"; | |
| 446 | 447 | |
| 447 | 448 | /** Each migration file's name and its default export, in name order. */ |
| 448 | 449 | export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ |
| @@ -888,4 +889,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ | ||
| 888 | 889 | ["20261130235220-run-check-plan.ts", m439], |
| 889 | 890 | ["20261201000000-games.ts", m440], |
| 890 | 891 | ["20261201120000-first-change-forge.ts", m441], |
| 892 | ["20261201121000-repo-check-slots.ts", m442], | |
| 891 | 893 | ]; |
src/http/server.ts +2
| @@ -492,6 +492,7 @@ import { | ||
| 492 | 492 | appSettingsUpdate, |
| 493 | 493 | autonomySettingsPage, |
| 494 | 494 | autonomySettingsUpdate, |
| 495 | checkSlotsUpdate, | |
| 495 | 496 | settingsPage, |
| 496 | 497 | settingsUpdate, |
| 497 | 498 | waveCut, |
| @@ -1946,6 +1947,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1946 | 1947 | router.add("POST", "/:owner/:name/settings/pillars", pillarUpdate); |
| 1947 | 1948 | router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage); |
| 1948 | 1949 | router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate); |
| 1950 | router.add("POST", "/:owner/:name/settings/check-slots", checkSlotsUpdate); | |
| 1949 | 1951 | router.add("GET", "/:owner/:name/allocation", allocationPage); |
| 1950 | 1952 | router.add("POST", "/:owner/:name/allocation/move", allocationMove); |
| 1951 | 1953 | router.add("POST", "/:owner/:name/allocation/weekly", allocationWeekly); |
src/tui/screens/autonomy.ts +21 −1
| @@ -14,6 +14,8 @@ | ||
| 14 | 14 | * Anyone else gets no palette entry and, if the screen is reached, no values. |
| 15 | 15 | */ |
| 16 | 16 | |
| 17 | import { checkPool, setCheckSlots } from "../../actions/check_slots.ts"; | |
| 18 | import { pullChecksOf } from "../../checks/check_slots.ts"; | |
| 17 | 19 | import { updateRepoSettings } from "../../actions/repos.ts"; |
| 18 | 20 | import { POLISH_SHARE_MAX, validPolishShare } from "../../crew/polish_share.ts"; |
| 19 | 21 | import { weekCardRows } from "../../crew/week.ts"; |
| @@ -42,6 +44,13 @@ import { confirmScreen, promptScreen } from "./common.ts"; | ||
| 42 | 44 | const MODE_LABEL: Record<Autonomy, string> = { off: "Off", assisted: "Assisted", autonomous: "Autonomous" }; |
| 43 | 45 | |
| 44 | 46 | |
| 47 | ||
| 48 | /** The Checks line: the slots this repository is guaranteed, and its pull checks now. */ | |
| 49 | function checksLine(app: Session["app"], repo: Repo): string { | |
| 50 | const now = pullChecksOf(app.db, repo.id); | |
| 51 | const busy = now.running + now.waiting === 0 ? "" : ` · ${now.running} running${now.waiting > 0 ? `, ${now.waiting} waiting` : ""}`; | |
| 52 | return `Checks ${repo.checkSlots} at once guaranteed, of the forge's ${checkPool(app)}${busy}`; | |
| 53 | } | |
| 45 | 54 | /** The card's Week and Pace lines; one plain line while the week is unmeasured. */ |
| 46 | 55 | function weekLines(week: Parameters<typeof weekCardRows>[0]): string[] { |
| 47 | 56 | const rows = weekCardRows(week); |
| @@ -109,7 +118,7 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 109 | 118 | title: "Autonomy", |
| 110 | 119 | get keys() { |
| 111 | 120 | return mayChange() |
| 112 | ? [binding(["m"], "mode"), binding(["p"], "planner"), binding(["s"], "builder"), binding(["r"], "reviewer"), binding(["o"], "polish share")] | |
| 121 | ? [binding(["m"], "mode"), binding(["p"], "planner"), binding(["s"], "builder"), binding(["r"], "reviewer"), binding(["o"], "polish share"), binding(["g"], "check slots")] | |
| 113 | 122 | : []; |
| 114 | 123 | }, |
| 115 | 124 | render(area, s) { |
| @@ -124,6 +133,7 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 124 | 133 | ` ${AUTONOMY_SAID[r.autonomy]}`, |
| 125 | 134 | ...weekLines(crewWeekFor(f.app, r, new Date())), |
| 126 | 135 | `Polish ${r.polishShare}% of the week's spend`, |
| 136 | checksLine(f.app, r), | |
| 127 | 137 | ...seatSlotsOf(f.db, r).map( |
| 128 | 138 | (p) => `${(p.role[0]!.toUpperCase() + p.role.slice(1)).padEnd(9)}${p.slots} at once · ${seatSlotsWords(p)}`, |
| 129 | 139 | ), |
| @@ -173,6 +183,16 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 173 | 183 | }); |
| 174 | 184 | return true; |
| 175 | 185 | } |
| 186 | if (e.key === "g") { | |
| 187 | ask("Check slots", "pull checks guaranteed at once, 1 or more", "1 or more", String(current().checkSlots), (raw) => { | |
| 188 | const n = /^\d{1,2}$/.test(raw) ? Number(raw) : Number.NaN; | |
| 189 | const set = setCheckSlots(f.app, f.user, current(), n); | |
| 190 | ctx.toast(set.ok ? `Check slots: ${set.value.checkSlots}.` : set.error === "not_found" ? "Only an admin of this repository sets its check slots." : set.error, set.ok ? "success" : "danger"); | |
| 191 | ctx.invalidate(); | |
| 192 | return undefined; | |
| 193 | }); | |
| 194 | return true; | |
| 195 | } | |
| 176 | 196 | const seat: Partial<Record<string, CrewRole>> = { p: "planner", s: "builder", r: "reviewer" }; |
| 177 | 197 | const role = seat[e.key]; |
| 178 | 198 | if (role !== undefined) { |
src/web/pages/boards-slots.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * Check slots by repository on /boards (`checks/check_slots.ts`): each repository with a pull check | |
| 3 | * running or waiting, how many of its guaranteed slots it uses, how many it borrows, and how many | |
| 4 | * wait. One read of the active checks and one of the repositories they name. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../../app.ts"; | |
| 8 | import { checkPool } from "../../actions/check_slots.ts"; | |
| 9 | import { getReposByIds } from "../../core/repos.ts"; | |
| 10 | import { pullChecksByRepo } from "../../checks/check_slots.ts"; | |
| 11 | import { fold } from "../figure.ts"; | |
| 12 | import { html, type Html } from "../html.ts"; | |
| 13 | import { row, rowList } from "../ui.ts"; | |
| 14 | ||
| 15 | export interface SlotRow { | |
| 16 | readonly repo: string; | |
| 17 | readonly href: string; | |
| 18 | readonly grant: number; | |
| 19 | readonly running: number; | |
| 20 | readonly waiting: number; | |
| 21 | } | |
| 22 | ||
| 23 | /** The busy repositories, most running first. */ | |
| 24 | export function slotRows(app: App): SlotRow[] { | |
| 25 | const counts = pullChecksByRepo(app.db); | |
| 26 | const repos = getReposByIds(app.db, [...counts.keys()]); | |
| 27 | return [...repos.values()] | |
| 28 | .map((r) => ({ repo: `${r.ownerName}/${r.name}`, href: `/${r.ownerName}/${r.name}/settings?check-slots#check-slots`, grant: r.checkSlots, ...counts.get(r.id)! })) | |
| 29 | .sort((a, b) => b.running - a.running || b.waiting - a.waiting || (a.repo < b.repo ? -1 : 1)); | |
| 30 | } | |
| 31 | ||
| 32 | /** The fold, while a pull check runs or waits; with none there is nothing to say. */ | |
| 33 | export function checkSlotsFold(app: App): Html | null { | |
| 34 | const rows = slotRows(app); | |
| 35 | if (rows.length === 0) return null; | |
| 36 | const pool = checkPool(app); | |
| 37 | const used = rows.reduce((n, r) => n + r.running, 0); | |
| 38 | const body = html`${rowList( | |
| 39 | rows.map((r) => | |
| 40 | row({ | |
| 41 | title: html`<a href="${r.href}">${r.repo}</a>`, | |
| 42 | meta: html`${r.running} of ${r.grant} running${r.running > r.grant ? `, ${r.running - r.grant} borrowed` : ""}${r.waiting > 0 ? ` · ${r.waiting} waiting` : ""}`, | |
| 43 | data: { "check-slots": r.repo }, | |
| 44 | }), | |
| 45 | ), | |
| 46 | { label: "Check slots by repository" }, | |
| 47 | )}`; | |
| 48 | return fold("Check slots by repository", `${used} of ${pool} slots in use by ${rows.length} ${rows.length === 1 ? "repository" : "repositories"}`, body, { id: "check-slots" }); | |
| 49 | } |
src/web/pages/boards-view.ts +2 −1
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | * No client framework. Every form posts to `boards-edit.ts`. Anyone but a |
| 8 | 8 | * person who is an admin gets the not-found page. |
| 9 | 9 | */ |
| 10 | import { checkSlotsFold } from "./boards-slots.ts"; | |
| 10 | 11 | import { CHART_NAMES } from "../../boards/chart.ts"; |
| 11 | 12 | import { isSlug, MAX_H, MAX_PANELS, MAX_TITLE, MAX_W, RANGES, type Board, type Panel } from "../../boards/store.ts"; |
| 12 | 13 | import type { App } from "../../app.ts"; |
| @@ -160,7 +161,7 @@ export async function boardsList(ctx: Ctx): Promise<Response> { | ||
| 160 | 161 | </section>`; |
| 161 | 162 | const drift = driftSection(picture.drifting ?? []); |
| 162 | 163 | const flow = timePhase(ctx.request, "flow", () => |
| 163 | flowPanel(ctx.app, { kind: "owner" }, ctx.url, "/boards", { picture, refetch: false, now: html`${liveLine(ctx.url.searchParams.has("pause"))}${alarmLines(picture.alarms)}`, between: boards, first: drift, last: boardsHoldsCard(ctx.app.db, user, true) })); | |
| 164 | flowPanel(ctx.app, { kind: "owner" }, ctx.url, "/boards", { picture, refetch: false, now: html`${liveLine(ctx.url.searchParams.has("pause"))}${alarmLines(picture.alarms)}`, between: boards, first: drift, last: html`${checkSlotsFold(ctx.app)}${boardsHoldsCard(ctx.app.db, user, true)}` })); | |
| 164 | 165 | const rendering = performance.now(); |
| 165 | 166 | const response = page({ |
| 166 | 167 | ctx, |
src/web/pages/settings.ts +36 −1
| @@ -15,6 +15,8 @@ import { privateDestinationBlocked } from "../../actions/blocked_words.ts"; | ||
| 15 | 15 | import { templateProblem } from "../../apps/template_problem.ts"; |
| 16 | 16 | import { templateSaid } from "../../core/template_words.ts"; |
| 17 | 17 | import { POLISH_SHARE_DEFAULT, POLISH_SHARE_MAX } from "../../crew/polish_share.ts"; |
| 18 | import { checkPool, setCheckSlots } from "../../actions/check_slots.ts"; | |
| 19 | import { pullChecksOf } from "../../checks/check_slots.ts"; | |
| 18 | 20 | import { appLimitWords } from "../../actions/app_limit.ts"; |
| 19 | 21 | import { showProvenance } from "../../actions/provenance.ts"; |
| 20 | 22 | import { getProvenance, parentUrl, sourceLabel } from "../../core/provenance.ts"; |
| @@ -355,6 +357,7 @@ export async function settingsPage( | ||
| 355 | 357 | </form> |
| 356 | 358 | </section>`; |
| 357 | 359 | const secrets = secretsSection(ctx, "repo", `${repo.ownerName}/${repo.name}`); |
| 360 | const slotsBlock = checkSlotsSection(ctx, repo); | |
| 358 | 361 | const upstream = followUpstreamCard(ctx, repo, await followChoiceForm(ctx, repo)); |
| 359 | 362 | const sources = followSourcesCard(ctx, repo); |
| 360 | 363 | const wave = html`<section class="settings-block"> |
| @@ -439,7 +442,7 @@ export async function settingsPage( | ||
| 439 | 442 | repo, |
| 440 | 443 | "general", |
| 441 | 444 | "Settings", |
| 442 | html`${help}${lead}${mirror ? html`<div class="mt">${mirror}</div>` : null}${grantsBlock ? html`<div class="mt">${grantsBlock}</div>` : null}<div class="mt">${body}</div>${trail | |
| 445 | html`${help}${lead}${mirror ? html`<div class="mt">${mirror}</div>` : null}${grantsBlock ? html`<div class="mt">${grantsBlock}</div>` : null}<div class="mt">${body}</div>${slotsBlock === null ? null : html`<div class="mt">${slotsBlock}</div>`}${trail | |
| 443 | 446 | ? html`<div class="mt">${trail}</div>` |
| 444 | 447 | : null}${upstream ? html`<div class="mt">${upstream}</div>` : null}${sources ? html`<div class="mt">${sources}</div>` : null}<div class="mt">${wave}</div><div class="mt">${archive}</div><div class="mt">${move}</div>${proposals |
| 445 | 448 | ? html`<div class="mt">${proposals}</div>` |
| @@ -1588,6 +1591,38 @@ function redeploying(ctx: Ctx, how: string): string { | ||
| 1588 | 1591 | |
| 1589 | 1592 | // ---- autonomy ---- |
| 1590 | 1593 | |
| 1594 | /** The "Check slots" row (`checks/check_slots.ts`): the grant, what it uses now, and its form. */ | |
| 1595 | function checkSlotsSection(ctx: Ctx, repo: Repo): Html | null { | |
| 1596 | const base = repoBase(repo); | |
| 1597 | const now = pullChecksOf(ctx.app.db, repo.id); | |
| 1598 | // Shown where it matters: a repository with pull checks running or waiting, one whose slots | |
| 1599 | // were set, or when asked for (/boards links here with ?check-slots). A quiet one at the | |
| 1600 | // default says nothing; the terminal's Autonomy screen always shows it. | |
| 1601 | if (repo.checkSlots === 1 && now.running === 0 && now.waiting === 0 && !ctx.url.searchParams.has("check-slots")) return null; | |
| 1602 | const pool = checkPool(ctx.app); | |
| 1603 | return html`<section class="settings-block" id="check-slots"> | |
| 1604 | <h2>Check slots</h2> | |
| 1605 | <form method="post" action="${base}/settings/check-slots"> | |
| 1606 | <div class="field"> | |
| 1607 | <label for="f-checkSlots">Pull checks at once, of ${String(pool)}</label> | |
| 1608 | <input class="input input-num mono" id="f-checkSlots" name="checkSlots" type="number" min="1" max="${String(pool)}" step="1" value="${String(repo.checkSlots)}" inputmode="numeric" aria-describedby="why-checkSlots" /> | |
| 1609 | <p class="hint" id="why-checkSlots" data-check-slots>Running ${String(now.running)} of ${String(repo.checkSlots)}${now.waiting > 0 ? `, ${now.waiting} waiting` : ""}.</p> | |
| 1610 | </div> | |
| 1611 | <div class="form-actions">${btn("Save", { variant: "primary" })}</div> | |
| 1612 | </form> | |
| 1613 | </section>`; | |
| 1614 | } | |
| 1615 | ||
| 1616 | // POST /:owner/:name/settings/check-slots | |
| 1617 | export async function checkSlotsUpdate(ctx: Ctx): Promise<Response> { | |
| 1618 | const gate = await adminForm(ctx); | |
| 1619 | if (gate instanceof Response) return gate; | |
| 1620 | const { repo, form } = gate; | |
| 1621 | const to = `${repoBase(repo)}/settings#check-slots`; | |
| 1622 | const set = setCheckSlots(ctx.app, ctx.auth.user, repo, Number(field(form, "checkSlots"))); | |
| 1623 | return flashTo(ctx, to, set.ok ? { message: `Check slots: ${set.value.checkSlots}.` } : { tone: "danger", message: set.error === "not_found" ? "Those settings could not be saved." : set.error }); | |
| 1624 | } | |
| 1625 | ||
| 1591 | 1626 | /** GET /:owner/:name/settings/autonomy */ |
| 1592 | 1627 | // GET /:owner/:name/settings/autonomy — the settings page's own card now. |
| 1593 | 1628 | export function autonomySettingsPage(ctx: Ctx): Response { |
test/check-slots.test.ts added +336
| @@ -0,0 +1,336 @@ | ||
| 1 | /** | |
| 2 | * Per-repository check slots (`checks/check_slots.ts`, app-runner-grants.md §3): a small app always | |
| 3 | * gets its one slot when it has work, the forge borrows every slot nobody waiting is owed, and no | |
| 4 | * repository starves, with no check ever stopped to make room. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, 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 { setCheckSlots } from "../src/actions/check_slots.ts"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { setRole } from "../src/actions/roles.ts"; | |
| 14 | import { grantHold, holdLine, type SlotView } from "../src/checks/check_slots.ts"; | |
| 15 | import { getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 16 | import { setCapacity } from "../src/core/capacity.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { cancelRun, claimRun, createRun, getRun, listActive, type Run } from "../src/core/runs.ts"; | |
| 19 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 20 | import { writeCheckSlots } from "../src/core/repos.ts"; | |
| 21 | import { startChecks, type ChecksHandle } from "../src/checks/service.ts"; | |
| 22 | import { setQuota } from "../src/settings/quotas.ts"; | |
| 23 | import { readRunLog } from "../src/runs/log.ts"; | |
| 24 | import { createIssue } from "../src/core/issues.ts"; | |
| 25 | import { checkSlotsFold, slotRows } from "../src/web/pages/boards-slots.ts"; | |
| 26 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 27 | import { createSession } from "../src/core/sessions.ts"; | |
| 28 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 29 | import { quietLogs } from "./helpers/globals.ts"; | |
| 30 | import { waitFor } from "./helpers/poll.ts"; | |
| 31 | ||
| 32 | quietLogs(); | |
| 33 | ||
| 34 | const grants: Record<string, number> = { forge: 5, app: 1, tool: 1 }; | |
| 35 | const view = (running: Record<string, number>, waiting: string[], free: number): SlotView => ({ | |
| 36 | running: new Map(Object.entries(running)), | |
| 37 | grant: (id) => grants[id] ?? 1, | |
| 38 | waiting: new Set(waiting), | |
| 39 | free, | |
| 40 | }); | |
| 41 | ||
| 42 | describe("admission", () => { | |
| 43 | test("within its grant a repository starts at once; a small app's first check always may", () => { | |
| 44 | expect(grantHold("forge", view({ forge: 4 }, ["forge", "app"], 1))).toBeUndefined(); | |
| 45 | expect(grantHold("app", view({ forge: 7 }, ["forge", "app"], 1))).toBeUndefined(); | |
| 46 | }); | |
| 47 | ||
| 48 | test("the forge borrows idle slots when nobody else waits", () => { | |
| 49 | expect(grantHold("forge", view({ forge: 5 }, ["forge"], 3))).toBeUndefined(); | |
| 50 | expect(grantHold("forge", view({ forge: 7 }, ["forge"], 1))).toBeUndefined(); | |
| 51 | }); | |
| 52 | ||
| 53 | test("above its grant it keeps back what waiting apps are owed, and says who", () => { | |
| 54 | const hold = grantHold("forge", view({ forge: 5, tool: 0 }, ["forge", "app", "tool"], 2)); | |
| 55 | expect(hold).toEqual({ used: 5, grant: 5, owed: [{ repoId: "app", slots: 1 }, { repoId: "tool", slots: 1 }] }); | |
| 56 | expect(holdLine(hold!, (id) => `tess/${id}`, "trevato/forge")).toBe("held: trevato/forge at its grant of 5; tess/app's 1, tess/tool's 1 are reserved"); | |
| 57 | // One more free than owed: it may borrow that one. | |
| 58 | expect(grantHold("forge", view({ forge: 5 }, ["forge", "app", "tool"], 3))).toBeUndefined(); | |
| 59 | // An app already at its grant is owed nothing. | |
| 60 | expect(grantHold("forge", view({ forge: 5, app: 1 }, ["forge", "app"], 1))).toBeUndefined(); | |
| 61 | }); | |
| 62 | ||
| 63 | test("an app at its own grant waits behind another app's first check, as the forge does", () => { | |
| 64 | const hold = grantHold("app", view({ forge: 5, app: 1 }, ["app", "tool"], 1)); | |
| 65 | expect(hold?.owed).toEqual([{ repoId: "tool", slots: 1 }]); | |
| 66 | expect(holdLine(hold!, (id) => id, "app")).toBe("held: app at its grant of 1; tool's 1 is reserved"); | |
| 67 | }); | |
| 68 | ||
| 69 | test("no starvation: with the forge's queue always full, a small app's check starts at the next slot that frees", () => { | |
| 70 | // 8 slots, checks of 6 ticks, the forge with endless work; the app queues one now and then. | |
| 71 | const pool = 8; | |
| 72 | const length = 6; | |
| 73 | let tick = 0; | |
| 74 | const runs: { repo: string; ends: number }[] = []; | |
| 75 | const appWaits: number[] = []; | |
| 76 | let appQueuedAt: number | undefined; | |
| 77 | for (; tick < 600; tick++) { | |
| 78 | for (let i = runs.length - 1; i >= 0; i--) if (runs[i]!.ends <= tick) runs.splice(i, 1); | |
| 79 | if (tick % 37 === 0 && appQueuedAt === undefined) appQueuedAt = tick; | |
| 80 | // Fill free slots, the app's first when it waits (pick order is the scheduler's; any order | |
| 81 | // holds). | |
| 82 | for (;;) { | |
| 83 | const running: Record<string, number> = {}; | |
| 84 | for (const r of runs) running[r.repo] = (running[r.repo] ?? 0) + 1; | |
| 85 | const free = pool - runs.length; | |
| 86 | if (free <= 0) break; | |
| 87 | const waiting = ["forge", ...(appQueuedAt === undefined ? [] : ["app"])]; | |
| 88 | const v = view(running, waiting, free); | |
| 89 | // The forge tries first, the worst case for the app. | |
| 90 | if (grantHold("forge", v) === undefined) { | |
| 91 | runs.push({ repo: "forge", ends: tick + length }); | |
| 92 | continue; | |
| 93 | } | |
| 94 | if (appQueuedAt !== undefined && grantHold("app", v) === undefined) { | |
| 95 | runs.push({ repo: "app", ends: tick + length }); | |
| 96 | appWaits.push(tick - appQueuedAt); | |
| 97 | appQueuedAt = undefined; | |
| 98 | continue; | |
| 99 | } | |
| 100 | break; | |
| 101 | } | |
| 102 | } | |
| 103 | expect(appWaits.length).toBeGreaterThan(10); | |
| 104 | // No preemption, so the worst wait is one check's length. | |
| 105 | expect(Math.max(...appWaits)).toBeLessThanOrEqual(length); | |
| 106 | }); | |
| 107 | }); | |
| 108 | ||
| 109 | describe("setting a grant", () => { | |
| 110 | let dir = ""; | |
| 111 | let app: App; | |
| 112 | let site: User; | |
| 113 | let owner: User; | |
| 114 | let forge: Repo; | |
| 115 | let small: Repo; | |
| 116 | let servers: Servers; | |
| 117 | const cookie: Record<string, string> = {}; | |
| 118 | beforeAll(async () => { | |
| 119 | dir = await mkdtemp(join(tmpdir(), "forge-check-slots-")); | |
| 120 | app = createApp({ dataDir: dir, port: 0 }); | |
| 121 | servers = await serve(app); | |
| 122 | const a = await seedAdmin(app, { username: "ada", email: "[email protected]" }); | |
| 123 | if (!a.ok) throw new Error("admin"); | |
| 124 | site = a.value; | |
| 125 | const o = await createUser(app.db, { origin: "seed", trusted: true, username: "tess", email: "[email protected]", password: "a-good-passphrase" }); | |
| 126 | if (!o.ok) throw new Error("owner"); | |
| 127 | owner = o.value; | |
| 128 | expect(setRole(app, site, "tess", "member").ok).toBe(true); | |
| 129 | const f = await createRepo(app, site, { name: "forge", visibility: "public" }); | |
| 130 | const s = await createRepo(app, owner, { name: "app", visibility: "public" }); | |
| 131 | if (!f.ok || !s.ok) throw new Error(`repos ${JSON.stringify(f.ok ? "" : f.error)} ${JSON.stringify(s.ok ? "" : s.error)}`); | |
| 132 | forge = f.value; | |
| 133 | small = s.value; | |
| 134 | setCapacity(app.db, "checks.concurrency", "8", site.id); | |
| 135 | const m = await createUser(app.db, { origin: "seed", trusted: true, username: "mallory", email: "[email protected]", password: "a-good-passphrase" }); | |
| 136 | if (!m.ok) throw new Error("mallory"); | |
| 137 | for (const u of [site, owner, m.value]) cookie[u.username] = `forge_session=${createSession(app.db, u.id).token}`; | |
| 138 | }); | |
| 139 | afterAll(async () => { | |
| 140 | servers.stop(); | |
| 141 | app.close(); | |
| 142 | await rm(dir, { recursive: true, force: true }); | |
| 143 | }); | |
| 144 | ||
| 145 | test("every repository starts at 1", () => { | |
| 146 | expect(forge.checkSlots).toBe(1); | |
| 147 | expect(small.checkSlots).toBe(1); | |
| 148 | }); | |
| 149 | ||
| 150 | test("a site admin raises a grant; the grants above 1 leave a slot for every app at 1", () => { | |
| 151 | const set = setCheckSlots(app, site, forge, 5); | |
| 152 | expect(set.ok && set.value.checkSlots).toBe(5); | |
| 153 | forge = getRepoById(app.db, forge.id)!; | |
| 154 | // 5 + 3 = 8 of 8 would leave none for the apps at 1. | |
| 155 | const tooMany = setCheckSlots(app, site, small, 3); | |
| 156 | expect(tooMany.ok).toBe(false); | |
| 157 | if (!tooMany.ok) expect(tooMany.error).toContain("At most 2 here"); | |
| 158 | expect(setCheckSlots(app, site, small, 2).ok).toBe(true); | |
| 159 | expect(setCheckSlots(app, site, small, 0).ok).toBe(false); | |
| 160 | }); | |
| 161 | ||
| 162 | test("a repository's own admin may lower its grant, never raise it", () => { | |
| 163 | small = getRepoById(app.db, small.id)!; | |
| 164 | const raise = setCheckSlots(app, owner, small, 3); | |
| 165 | expect(raise.ok).toBe(false); | |
| 166 | if (!raise.ok) expect(raise.error).toContain("site admin"); | |
| 167 | const lower = setCheckSlots(app, owner, small, 1); | |
| 168 | expect(lower.ok && lower.value.checkSlots).toBe(1); | |
| 169 | // Someone who does not administer it hears nothing of it. | |
| 170 | expect(setCheckSlots(app, owner, forge, 1)).toEqual({ ok: false, error: "not_found" }); | |
| 171 | }); | |
| 172 | ||
| 173 | test("/boards says each busy repository's slots: used of its grant, borrowed, and waiting", () => { | |
| 174 | const pull = createIssue(app.db, { repoId: forge.id, authorId: site.id, title: "p", kind: "pull" }); | |
| 175 | if (!pull.ok) throw new Error("pull"); | |
| 176 | const runs = Array.from({ length: 7 }, () => createRun(app.db, { repoId: forge.id, kind: "check", issueId: pull.value.id, reason: "push" })); | |
| 177 | for (const r of runs.slice(0, 6)) claimRun(app.db, r.id); | |
| 178 | const rows = slotRows(app); | |
| 179 | expect(rows).toEqual([{ repo: "ada/forge", href: "/ada/forge/settings?check-slots#check-slots", grant: 5, running: 6, waiting: 1 }]); | |
| 180 | expect(String(checkSlotsFold(app))).toContain("6 of 5 running, 1 borrowed · 1 waiting"); | |
| 181 | }); | |
| 182 | ||
| 183 | /** The settings form as the page posts it: session cookie, same-origin Origin. */ | |
| 184 | const post = (who: string, path: string, form: Record<string, string>, origin = servers.url) => | |
| 185 | fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie: cookie[who]!, origin }, body: new URLSearchParams(form), redirect: "manual" }); | |
| 186 | const flash = (res: Response): string => { | |
| 187 | const raw = /forge_flash=([^;]*)/.exec(res.headers.get("set-cookie") ?? "")?.[1] ?? ""; | |
| 188 | return raw === "" ? "" : (JSON.parse(decodeURIComponent(raw)) as { message: string }).message; | |
| 189 | }; | |
| 190 | const slotsOf = (repo: Repo) => getRepoById(app.db, repo.id)!.checkSlots; | |
| 191 | ||
| 192 | test("the settings form saves a grant, says it, and says a refusal in the page's words", async () => { | |
| 193 | const saved = await post("ada", "/ada/forge/settings/check-slots", { checkSlots: "4" }); | |
| 194 | expect(saved.status).toBe(303); | |
| 195 | expect(saved.headers.get("location")).toBe("/ada/forge/settings#check-slots"); | |
| 196 | expect(flash(saved)).toBe("Check slots: 4."); | |
| 197 | expect(slotsOf(forge)).toBe(4); | |
| 198 | const raise = await post("tess", "/tess/app/settings/check-slots", { checkSlots: "2" }); | |
| 199 | expect(flash(raise)).toContain("site admin"); | |
| 200 | expect(slotsOf(small)).toBe(1); | |
| 201 | }); | |
| 202 | ||
| 203 | test("the form refuses another origin, and someone who does not administer the repository hears nothing of it", async () => { | |
| 204 | const cross = await post("ada", "/ada/forge/settings/check-slots", { checkSlots: "2" }, "https://evil.example"); | |
| 205 | expect(cross.status).not.toBe(303); | |
| 206 | expect((await post("mallory", "/tess/app/settings/check-slots", { checkSlots: "1" })).status).toBe(404); | |
| 207 | expect(slotsOf(forge)).toBe(4); | |
| 208 | }); | |
| 209 | ||
| 210 | test("settings shows Check slots only where it matters: slots set, checks busy, or asked for from /boards", async () => { | |
| 211 | const page = async (who: string, path: string) => (await fetch(`${servers.url}${path}`, { headers: { cookie: cookie[who]! } })).text(); | |
| 212 | // A quiet app at the default says nothing. | |
| 213 | expect(await page("tess", "/tess/app/settings")).not.toContain('id="check-slots"'); | |
| 214 | expect(await page("tess", "/tess/app/settings?check-slots")).toContain('id="check-slots"'); | |
| 215 | // The forge's grant is set, and its checks are busy. | |
| 216 | const forgePage = await page("ada", "/ada/forge/settings"); | |
| 217 | expect(forgePage).toContain('id="check-slots"'); | |
| 218 | expect(forgePage).toContain("Running 6 of 4, 1 waiting."); | |
| 219 | }); | |
| 220 | }); | |
| 221 | ||
| 222 | /** | |
| 223 | * The real scheduler (`checks/scheduler.ts`) on a 3-slot lane whose runner answers only at the | |
| 224 | * end, so what starts stays running and the test reads what admission decided. | |
| 225 | */ | |
| 226 | describe("the scheduler holds to the grants", () => { | |
| 227 | const priorCells = process.env["FORGE_CELLS"]; // env-restored: afterAll | |
| 228 | const open: { app: App; checks: ChecksHandle; dir: string }[] = []; | |
| 229 | // The runner's answers, given only as the lanes stop, so what started stays running till then. | |
| 230 | const answers: { repo: string; answer: () => void }[] = []; | |
| 231 | /** Answers the running check of the repository named `repo`, freeing its slot. */ | |
| 232 | const answer = (repo: string) => answers.splice(answers.findIndex((a) => a.repo === repo), 1)[0]!.answer(); | |
| 233 | beforeAll(() => { | |
| 234 | process.env["FORGE_CELLS"] = "off"; // env-restored: afterAll | |
| 235 | }); | |
| 236 | afterAll(async () => { | |
| 237 | if (priorCells === undefined) delete process.env["FORGE_CELLS"]; | |
| 238 | else process.env["FORGE_CELLS"] = priorCells; | |
| 239 | // Stopped first, so an answered slot starts nothing new; then answered, so the stop can finish. | |
| 240 | const stopping = open.map((o) => o.checks.stop()); | |
| 241 | for (const a of answers) a.answer(); | |
| 242 | await Promise.all(stopping); | |
| 243 | for (const o of open) { | |
| 244 | o.app.close(); | |
| 245 | await rm(o.dir, { recursive: true, force: true }); | |
| 246 | } | |
| 247 | }); | |
| 248 | ||
| 249 | /** A lane of `slots` with the forge (the site admin's) and an app (tess's), each with a commit. */ | |
| 250 | async function lane(slots: number) { | |
| 251 | const dir = await mkdtemp(join(tmpdir(), "forge-check-slots-lane-")); | |
| 252 | const app = createApp({ dataDir: dir, port: 0 }); | |
| 253 | const a = await seedAdmin(app, { username: "ada", email: "[email protected]" }); | |
| 254 | const t = await createUser(app.db, { origin: "seed", trusted: true, username: "tess", email: "[email protected]", password: "a-good-passphrase" }); | |
| 255 | if (!a.ok || !t.ok) throw new Error("users"); | |
| 256 | expect(setRole(app, a.value, "tess", "member").ok).toBe(true); | |
| 257 | const repoWithCommit = async (who: User, name: string) => { | |
| 258 | const made = await createRepo(app, who, { name, visibility: "public" }); | |
| 259 | if (!made.ok) throw new Error(String(made.error)); | |
| 260 | const pushed = await commitToBranch(app, who, made.value, { message: "c", files: [{ path: "forge.json", content: `{"check": {"run": "true", "install": ""}}\n` }] }); | |
| 261 | if (!pushed.ok) throw new Error(JSON.stringify(pushed.error)); | |
| 262 | // Any check with an issue is held as a pull's is; an issue keeps the pull's trust rules | |
| 263 | // (`core/pull_trust.ts`) out of a test of admission. | |
| 264 | const issue = createIssue(app.db, { repoId: made.value.id, authorId: who.id, title: "p", kind: "issue" }); | |
| 265 | if (!issue.ok) throw new Error("issue"); | |
| 266 | return { repo: made.value, oid: pushed.value.commitOid, issueId: issue.value.id }; | |
| 267 | }; | |
| 268 | const forge = await repoWithCommit(a.value, "forge"); | |
| 269 | const small = await repoWithCommit(t.value, "app"); | |
| 270 | // The pushes' main checks are not this test's. | |
| 271 | for (const run of listActive(app.db, "check")) cancelRun(app.db, run.id); | |
| 272 | const queue = (r: typeof forge, n: number): Run[] => | |
| 273 | Array.from({ length: n }, () => createRun(app.db, { repoId: r.repo.id, kind: "check", issueId: r.issueId, commitOid: r.oid, env: "production", reason: "push" })); | |
| 274 | const go = () => { | |
| 275 | const checks = startChecks(app, { | |
| 276 | forgeUrl: "http://forge.test", | |
| 277 | concurrency: slots, | |
| 278 | runTier: (x) => new Promise((resolve) => answers.push({ repo: x.repo.name, answer: () => resolve({ ok: false, error: "stopped" }) })), | |
| 279 | }); | |
| 280 | open.push({ app, checks, dir }); | |
| 281 | }; | |
| 282 | const running = (r: typeof forge) => listActive(app.db, "check").filter((run) => run.repoId === r.repo.id && run.state === "running").length; | |
| 283 | return { app, tess: t.value, forge, small, queue, go, running }; | |
| 284 | } | |
| 285 | ||
| 286 | test("with the forge's queue full, the app's one check takes its slot; the forge's extra checks are held, said once", async () => { | |
| 287 | const l = await lane(3); | |
| 288 | writeCheckSlots(l.app.db, l.forge.repo.id, 2); | |
| 289 | // The app queued first, so the newest-first pick reaches the forge's first: the worst case. | |
| 290 | const appRuns = l.queue(l.small, 2); | |
| 291 | const forgeRuns = l.queue(l.forge, 4); | |
| 292 | const lines = (run: Run) => readRunLog(l.app.config.dataDir, run.id).lines.filter((line) => line.includes("queued, held:")); | |
| 293 | l.go(); | |
| 294 | // Every slot is taken, so nothing more can start; the forge's checks past its grant said why. | |
| 295 | expect(await waitFor(() => l.running(l.forge) + l.running(l.small) === 3 && forgeRuns.some((run) => lines(run).length > 0))).toBe(true); | |
| 296 | expect(l.running(l.small)).toBe(1); | |
| 297 | expect(l.running(l.forge)).toBe(2); | |
| 298 | expect(lines(forgeRuns.find((run) => lines(run).length > 0)!)[0]).toContain("held: ada/forge at its grant of 2; tess/app's 1 is reserved"); | |
| 299 | // The app's check ends: the freed slot is its next check's, and the forge's, held again, do | |
| 300 | // not say so again. | |
| 301 | answer("app"); | |
| 302 | const second = appRuns.find((run) => getRun(l.app.db, run.id)?.state === "queued")!; | |
| 303 | expect(await waitFor(() => getRun(l.app.db, second.id)?.state === "running")).toBe(true); | |
| 304 | expect(l.running(l.forge)).toBe(2); | |
| 305 | for (const run of forgeRuns.filter((r) => lines(r).length > 0)) expect(lines(run)).toHaveLength(1); | |
| 306 | }); | |
| 307 | ||
| 308 | test("a main check is never held to a grant", async () => { | |
| 309 | const l = await lane(3); | |
| 310 | l.queue(l.small, 1); | |
| 311 | l.queue(l.forge, 2); | |
| 312 | // A main check of the forge's, past its grant of 1. | |
| 313 | createRun(l.app.db, { repoId: l.forge.repo.id, kind: "check", commitOid: l.forge.oid, env: "production", reason: "push" }); | |
| 314 | l.go(); | |
| 315 | // Every slot is taken, so nothing more can start. | |
| 316 | expect(await waitFor(() => l.running(l.forge) + l.running(l.small) === 3)).toBe(true); | |
| 317 | expect(l.running(l.small)).toBe(1); | |
| 318 | // Its pull check within the grant, and the main check past it. | |
| 319 | expect(l.running(l.forge)).toBe(2); | |
| 320 | }); | |
| 321 | ||
| 322 | test("an app whose account is at its checks limit reserves nothing: the forge borrows every slot", async () => { | |
| 323 | const l = await lane(3); | |
| 324 | // tess's one concurrent check is taken by another repository of hers. | |
| 325 | setQuota(l.app.db, "checks", 1, l.tess.id); | |
| 326 | const other = await createRepo(l.app, l.tess, { name: "other", visibility: "public" }); | |
| 327 | if (!other.ok) throw new Error(String(other.error)); | |
| 328 | claimRun(l.app.db, createRun(l.app.db, { repoId: other.value.id, kind: "check", env: "production", reason: "push" }).id); | |
| 329 | l.queue(l.small, 1); | |
| 330 | l.queue(l.forge, 4); | |
| 331 | l.go(); | |
| 332 | expect(await waitFor(() => l.running(l.forge) === 3)).toBe(true); | |
| 333 | expect(l.running(l.small)).toBe(0); | |
| 334 | expect(l.running(l.forge)).toBe(3); | |
| 335 | }, 20_000); | |
| 336 | }); |
test/tui-autonomy.test.ts +22
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * in as the page's API lets one; a reader and a writer who is not an admin get |
| 6 | 6 | * no palette entry and see no value. |
| 7 | 7 | */ |
| 8 | import { setCapacity } from "../src/core/capacity.ts"; | |
| 8 | 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 9 | 10 | import { mkdtemp, rm } from "node:fs/promises"; |
| 10 | 11 | import { tmpdir } from "node:os"; |
| @@ -306,4 +307,25 @@ describe("autonomy in the terminal", () => { | ||
| 306 | 307 | expect(saved().autonomySlots).toBe(2); |
| 307 | 308 | h.stop(); |
| 308 | 309 | }); |
| 310 | ||
| 311 | test("the Checks line shows the repository's check slots, and g sets them as the settings page does", async () => { | |
| 312 | setCapacity(forge.db, "checks.concurrency", "8", ada.id); | |
| 313 | const h = boot(ada); | |
| 314 | await h.open(); | |
| 315 | expect(h.text()).toContain("Checks 1 at once guaranteed, of the forge's 8"); | |
| 316 | await h.press("g"); | |
| 317 | for (let i = 0; i < 4; i++) await h.press("backspace"); | |
| 318 | await h.type("2"); | |
| 319 | await h.press("enter"); | |
| 320 | expect(saved().checkSlots).toBe(2); | |
| 321 | expect(h.text()).toContain("Checks 2 at once guaranteed"); | |
| 322 | // More than the pool leaves for the others is refused with the page's sentence. | |
| 323 | await h.press("g"); | |
| 324 | for (let i = 0; i < 4; i++) await h.press("backspace"); | |
| 325 | await h.type("99"); | |
| 326 | await h.press("enter"); | |
| 327 | expect(h.text()).toContain("At most"); | |
| 328 | expect(saved().checkSlots).toBe(2); | |
| 329 | h.stop(); | |
| 330 | }); | |
| 309 | 331 | }); |
new above
offline
Principle 1: this paragraph repeats what the settings hint and the docs say. Reduce it to one line, or drop it and let the rows speak.