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

The owner's own pulls are checked ahead of the crew's (behind approved ones; crew checks past 20 min still go first) #16932

Merged opened this

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

Merged

checks/own-first → main 0 commits 3 threads · 3 unresolved

  • Merged. checks/own-first was merged into main as 6c5b982.

Review

Sign in to review this change.
9 files changed +302 −72
docs/features/ranked-checks.md +15 −3
@@ -11,15 +11,27 @@ first, not only which issue the crew starts.
1111 has waited `STARVATION_MS` (half the lane budget), then an approved pull's
1212 check, then the rest. Inside each tier the check whose issue stands highest
1313 on the list goes first, the unranked last, newest first as the tie-break.
14 - **The owner's own pulls** (`checks/own_first.ts`). While one is queued, the order is: a check
15 that has waited `CREW_WAIT_CAP_MS` (twice the lane budget, beside `STARVATION_MS` in
16 `kernel/budgets.ts`), then an approved pull's check, then the owner's own pull, then the rest.
17 An own pull is one opened by a person, not an agent, who owns the repository: Talk's direct
18 lane opens pulls as them, and the pulls a conductor opens as the owner count too, which is
19 intended, since they are the owner's work. A collaborator's pull, or a person's on someone
20 else's forge, gets no place ahead. The five-minute starvation rule gives way to it (with a
21 backlog of crew checks it would always take the oldest, which is how #16913 waited 26 minutes);
22 the 20-minute cap keeps the crew's share, and among the owner's own pulls the starvation rule
23 still holds. The pull's checks line and its run log say "queued ahead of the crew's checks:
24 your own pull (behind approved ones)".
1425 - **Rework and re-checks** (`crew/requested.ts`, `crew/stale_reds.ts`) are
1526 taken in the same rank order, the unranked after, each group as it came.
1627 - **Home lane.** The checks lane lists waiting checks in the order they will
17 start, by the same three tiers, so the tile saying "next in line" names the
18 check that starts next. Approval is read in one batch per lane read; the
28 start: `pickOrder` (`checks/pick.ts`), the scheduler's own `pickNext` taken one
29 pick after another, so the tile saying "next in line" names the check that
30 starts next, the owner's own tier included. Approval is read in one batch per lane read; the
1931 database orders by rank before the 40-row bound, so a ranked check is never
2032 cut off behind newer unranked ones.
2133 - **Across repositories.** Ranks are per repository. Equal places in two
2234 repositories fall to the same tie-break (newest check first); nothing
2335 interleaves them by any other rule.
2436
25 Tests: `test/checks-ranked.test.ts`.
37 Tests: `test/checks-ranked.test.ts`, `test/checks-own-first.test.ts`.
src/checks/own_first.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * The owner's own pulls go ahead of the crew's checks (tonight's #16913 waited 26 minutes behind
3 * them, twice). A check is the owner's own when its pull was opened by a person, not an agent, who
4 * owns the repository: a pull Talk's direct lane opened is the owner's (it opens as them), and so
5 * is one the conductor opens as the owner, which is intended, since it is the owner's work. A
6 * collaborator's pull, or a person's on someone else's forge, is not: nobody jumps another owner's
7 * crew. Approved pulls still go first, and the crew keeps its share: a crew check that has waited
8 * `CREW_WAIT_CAP_MS` takes the next slot (`checks/pick.ts`). Plain data in, a run out.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import type { Run } from "../core/runs.ts";
13
14 /**
15 * What the pull page's checks line (`queuePlace`'s `own`) and the run log say of a check that goes
16 * ahead.
17 */
18 export const OWN_FIRST_WORDS = "queued ahead of the crew's checks: your own pull (behind approved ones)";
19
20 /**
21 * The one rule, as SQL, for an issue `i` joined to its repository `r` and author `u` by
22 * `OWN_PULL_JOINS`: a pull whose author is a person, not an agent, who owns the repository. Both
23 * `ownPull` and the pull page's place in line (`checks/place.ts`, inside its one statement) read
24 * it.
25 */
26 export const OWN_PULL_JOINS = "JOIN repo r ON r.id = i.repo_id JOIN user u ON u.id = i.author_id";
27 export const OWN_PULL_WHERE = "i.kind = 'pull' AND i.author_id = r.owner_id AND u.is_agent = 0";
28
29 /** Whether the run is the check of the repository owner's own pull, a person's: one statement. */
30 export function ownPull(db: Database, run: Pick<Run, "issueId" | "repoId" | "kind">): boolean {
31 if (run.kind !== "check" || run.issueId === null) return false;
32 return db.query(`SELECT 1 FROM issue i ${OWN_PULL_JOINS} WHERE i.id = ?1 AND i.repo_id = ?2 AND ${OWN_PULL_WHERE}`).get(run.issueId, run.repoId) !== null;
33 }
34
35 /** `ownPull`, asked at most once per run for as long as the predicate lives. */
36 export function ownOnce(db: Database): (run: Run) => boolean {
37 const known = new Map<string, boolean>();
38 return (run) => {
39 let yes = known.get(run.id);
40 if (yes === undefined) known.set(run.id, (yes = ownPull(db, run)));
41 return yes;
42 };
43 }
src/checks/pick.ts +40 −2
@@ -1,7 +1,7 @@
11
22 import type { Run } from "../core/runs.ts";
33 import { ownersFirst } from "./outside_lane.ts";
4 import { STARVATION_MS } from "../kernel/budgets.ts";
4 import { CREW_WAIT_CAP_MS, STARVATION_MS } from "../kernel/budgets.ts";
55
66
77 /**
@@ -26,6 +26,12 @@ export function holdsLastSlot(free: number, gateWaits: boolean): boolean {
2626 * the pull whose issue stands highest on the owner's ranked list (`rank`,
2727 * 1 at the top) goes first, the unranked last, newest first only as the
2828 * tie-break (#12230).
29 *
30 * The owner's own pulls (`own`, `checks/own_first.ts`) go ahead of everything but approved pulls,
31 * and ahead of a crew check the five-minute starvation rule would take, which with a backlog of
32 * crew checks would otherwise always be the oldest (the rule still holds among the owner's own);
outdated

This comment line runs far past the wrap width. Run bun scripts/gate.ts --fix and commit the rewrap.

33 * the crew keeps its share, since a check that has waited `CREW_WAIT_CAP_MS` takes the next slot.
34 * With no own check queued, the order is as above.
2935 */
3036 export function pickNext(
3137 queued: readonly Run[],
@@ -33,6 +39,7 @@ export function pickNext(
3339 approved: (run: Run) => boolean = () => false,
3440 rank: (run: Run) => number | undefined = () => undefined,
3541 outside: (run: Run) => boolean = () => false,
42 own: (run: Run) => boolean = () => false,
3643 ): Run | undefined {
3744 // An unapproved outside contributor's check goes after everyone else's (`outside_lane.ts`).
3845 queued = ownersFirst(queued, outside);
@@ -44,12 +51,43 @@ export function pickNext(
4451 const better = (a: Run, b: Run): boolean => place(a) < place(b) || (place(a) === place(b) && newer(a, b));
4552 let newest: Run | undefined;
4653 let newestApproved: Run | undefined;
54 let newestOwn: Run | undefined;
4755 for (const run of queued) {
4856 if (newer(oldest, run)) oldest = run;
4957 if (newest === undefined || better(run, newest)) newest = run;
5058 if (approved(run) && (newestApproved === undefined || better(run, newestApproved)))
5159 newestApproved = run;
60 if (own(run) && (newestOwn === undefined || better(run, newestOwn))) newestOwn = run;
5261 }
53 if (now - Date.parse(oldest.createdAt) >= STARVATION_MS) return oldest;
62 const waited = now - Date.parse(oldest.createdAt);
63 if (newestOwn !== undefined) {
64 // The cap is the crew's share; the starvation rule still holds among the owner's own pulls.
65 if (waited >= CREW_WAIT_CAP_MS || (waited >= STARVATION_MS && own(oldest))) return oldest;
66 return newestApproved ?? newestOwn;
67 }
68 if (waited >= STARVATION_MS) return oldest;
5469 return newestApproved ?? newest;
5570 }
71
72 /**
73 * Every queued check in the order `pickNext` takes them, one pick after another from what is left:
74 * the one ordering the scheduler and the home checks lane (`flow/lanes_read.ts`) both read, so
75 * "next in line" names the check that starts next. Approximate in one way only: the scheduler
76 * passes over a check whose account is at its limit, a live state this does not read.
77 */
78 export function pickOrder(
79 queued: readonly Run[],
80 now: number = Date.now(),
81 approved: (run: Run) => boolean = () => false,
82 rank: (run: Run) => number | undefined = () => undefined,
83 outside: (run: Run) => boolean = () => false,
84 own: (run: Run) => boolean = () => false,
85 ): Run[] {
86 const left = [...queued];
87 const out: Run[] = [];
88 for (let next = pickNext(left, now, approved, rank, outside, own); next !== undefined; next = pickNext(left, now, approved, rank, outside, own)) {
89 out.push(next);
90 left.splice(left.indexOf(next), 1);
91 }
92 return out;
93 }
src/checks/place.ts +12 −3
@@ -8,20 +8,29 @@
88
99 import type { Database } from "bun:sqlite";
1010 import type { Run } from "../core/runs.ts";
11 import { OWN_PULL_JOINS, OWN_PULL_WHERE } from "./own_first.ts";
1112
1213 export interface Place {
1314 readonly place: number;
1415 readonly of: number;
16 /**
17 * The check is of the repository owner's own pull, a person's: it goes ahead of the crew's
18 * checks (`checks/own_first.ts`). Read in the same statement, so the pull page pays nothing for
19 * it.
20 */
21 readonly own?: boolean;
1522 }
1623
1724 export function queuePlace(db: Database, run: Pick<Run, "id" | "state" | "kind">): Place | undefined {
1825 if (run.kind !== "check" || run.state !== "queued") return undefined;
1926 const row = db
20 .query<{ before: number; total: number }, [string]>(
21 `SELECT COALESCE(SUM(id <= ?1), 0) AS before, COUNT(*) AS total FROM run WHERE kind = 'check' AND state = 'queued'`,
27 .query<{ before: number; total: number; own: number | null }, [string]>(
outdated

This repeats the ownPull predicate from own_first.ts. Keep one definition: call ownPull from here or share the SQL fragment, so the two cannot disagree.

28 `SELECT COALESCE(SUM(id <= ?1), 0) AS before, COUNT(*) AS total,
29 (SELECT 1 FROM run x JOIN issue i ON i.id = x.issue_id ${OWN_PULL_JOINS} WHERE x.id = ?1 AND ${OWN_PULL_WHERE}) AS own
30 FROM run WHERE kind = 'check' AND state = 'queued'`,
2231 )
2332 .get(run.id);
24 return row === null || row.before === 0 ? undefined : { place: row.before, of: row.total };
33 return row === null || row.before === 0 ? undefined : { place: row.before, of: row.total, own: row.own === 1 };
2534 }
2635
2736 /** `place 3 of 12`, or empty when the check is not waiting in line. */
src/checks/scheduler.ts +6 −2
@@ -4,6 +4,7 @@ import { getRepoById } from "../core/repos.ts";
44 import { listActive, type Run } from "../core/runs.ts";
55 import { approvedOnce } from "./approved_first.ts";
66 import { outsideOnce } from "./outside_lane.ts";
7 import { OWN_FIRST_WORDS, ownOnce } from "./own_first.ts";
78 import { redMain, unheld } from "./red_main.ts";
89 import { rebasesFirst } from "./finishing_first.ts";
910 import { inVerifyLane } from "./verify.ts";
@@ -64,12 +65,15 @@ function startable(lane: LaneState, queued: readonly Run[]): Run | undefined {
6465 const isApproved = approvedOnce(app.db);
6566 const rankOf = rankOnce(app.db);
6667 const isOutside = outsideOnce(app.db);
67 let next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside);
68 const isOwn = ownOnce(app.db);
69 let next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside, isOwn);
6870 while (next !== undefined && atLimit(lane, next)) {
6971 const held = next;
7072 rest = rest.filter((run) => run !== held);
71 next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside);
73 next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside, isOwn);
7274 }
75 // Its log says why it went ahead of the crew's checks.
76 if (next !== undefined && isOwn(next) && !isApproved(next)) appendRunLog(app.config.dataDir, next.id, `started: ${OWN_FIRST_WORDS}`);
7377 return next;
7478 }
7579
src/flow/lanes_read.ts +27 −60
@@ -21,8 +21,12 @@ import type { App } from "../app.ts";
2121 import { nextUp, type NextRow } from "../core/next_up.ts";
2222 import { idleReason, type IdleReason } from "../crew/idle_reason.ts";
2323 import { listAutonomousRepos } from "../core/repos.ts";
24 import { STARVATION_MS } from "../kernel/budgets.ts";
25 import { reviewSummariesFor } from "../core/reviews.ts";
24 import { listActive } from "../core/runs.ts";
25 import { approvedOnce } from "../checks/approved_first.ts";
26 import { outsideOnce } from "../checks/outside_lane.ts";
27 import { ownOnce } from "../checks/own_first.ts";
28 import { pickOrder } from "../checks/pick.ts";
29 import { rankOnce } from "../checks/ranked_first.ts";
2630 import { weekShare } from "../crew/week_read.ts";
2731 import { FORGE_BROKEN, firedAlarms } from "./alarms.ts";
2832 import { readBuilders, readKpis } from "./kpis.ts";
@@ -171,10 +175,8 @@ interface Raw {
171175 /** Place of the row's issue on the owner's ranked list, 1 at the top; null when unranked. */
172176 rk?: number | null;
173177 run_id?: string;
174 /** Checks lane: an approved pull's check, which `pickNext` takes before the rest. */
175 approved?: boolean;
176 /** Checks lane: the check that has waited so long `pickNext` takes it before all. */
177 starved?: boolean;
178 /** Checks lane: the check's place in the order `pickOrder` takes them, from 0. */
179 pos?: number;
178180 total: number;
179181 }
180182
@@ -186,15 +188,14 @@ const BUILD_WORDS: Record<string, string> = {
186188
187189 /**
188190 * The waiting rows in the order the next worker takes them (#12230): for
189 * checks, as `pickNext` does, a starved one first, then an approved pull's,
190 * then the rest; within each, the rank of the row's issue on the owner's list
191 * first, the unranked last; then `newestFirst` (checks: the order `pickNext`
192 * breaks ties in) or oldest first. Ranks are per repository, so equal places
191 * checks, their place in `pickOrder` (`checks/pick.ts`), the scheduler's own order; otherwise,
192 * and for a check `pickOrder` did not see, the rank of the row's issue on the owner's list first,
193 * the unranked last; then `newestFirst` or oldest first. Ranks are per repository, so equal places
193194 * in two repositories fall to the same tie-break: the newest (or oldest) first.
194195 */
195196 function takenOrder(rows: readonly Raw[], newestFirst: boolean): Raw[] {
196197 const place = (r: Raw) => r.rk ?? Number.MAX_SAFE_INTEGER;
197 const tier = (r: Raw) => (r.starved ? 0 : r.approved ? 1 : 2);
198 const tier = (r: Raw) => r.pos ?? Number.MAX_SAFE_INTEGER;
198199 const by = (a: Raw, b: Raw) => (a.since < b.since ? -1 : a.since > b.since ? 1 : 0) * (newestFirst ? -1 : 1);
199200 return rows
200201 .filter((x) => x.state === "queued")
@@ -260,12 +261,11 @@ function runRows(
260261 now: string,
261262 newestFirst = false,
262263 ): Raw[] {
263 // For checks, the order `pickNext` takes them is settled before the scan
264 // bound, so the check that starts next is never cut off the window: the
265 // starved one, then approved pulls', then rank, then age.
266 const tiers = kind === "check" ? checkTiers(db, now) : { starved: null, approved: [] as string[] };
264 // For checks, the order the scheduler takes them (`pickOrder`) is settled before the scan bound,
265 // so the check that starts next is never cut off the window.
266 const order = kind === "check" ? checkOrder(db, now) : [];
267267 const rows = db
268 .query<Raw, [string, string, number, string | null, string]>(
268 .query<Raw, [string, string, number, string]>(
269269 `SELECT COALESCE(i.id, x.id) AS id, x.repo_id, i.number, CASE WHEN i.id IS NULL THEN 'main' ELSE i.kind END AS kind, i.title, i.sealed,
270270 u.username AS who, CASE WHEN x.state = 'running' THEN COALESCE(x.started_at, x.created_at) ELSE x.created_at END AS since,
271271 x.state, x.reason, x.attempt, x.env, x.heartbeat_at AS beat, i.id AS issue_id, i.created_at AS born, k.pos AS rk, x.id AS run_id, COUNT(*) OVER () AS total
@@ -273,59 +273,26 @@ function runRows(
273273 LEFT JOIN issue_rank k ON k.issue_id = x.issue_id
274274 WHERE x.kind = ?1 AND x.state IN ('queued','running') AND ${where}
275275 AND (x.state = 'running' OR x.not_before IS NULL OR x.not_before <= ?2)
276 ORDER BY x.state DESC, (x.id = ?4) DESC, (x.id IN (SELECT value FROM json_each(?5))) DESC, (k.pos IS NULL), k.pos,
276 ORDER BY x.state DESC, COALESCE((SELECT CAST(o.key AS INTEGER) FROM json_each(?4) o WHERE o.value = x.id), 1000000000), (k.pos IS NULL), k.pos,
277277 x.created_at ${newestFirst ? "DESC" : "ASC"}, x.id ${newestFirst ? "DESC" : "ASC"} LIMIT ?3`,
278278 )
279 .all(kind, now, SCAN, tiers.starved, JSON.stringify(tiers.approved));
279 .all(kind, now, SCAN, JSON.stringify(order));
280280 if (kind === "check") {
281 const approved = new Set(tiers.approved);
282 for (const r of rows)
283 if (r.state === "queued") {
284 r.starved = r.run_id === tiers.starved;
285 r.approved = approved.has(r.run_id!);
286 }
281 const at = new Map(order.map((id, i) => [id, i]));
282 for (const r of rows) if (r.state === "queued" && at.has(r.run_id!)) r.pos = at.get(r.run_id!)!;
287283 }
288284 return rows;
289285 }
290286
291287 /**
292 * Which queued checks `pickNext` takes first, read over the whole queued set
293 * (small: checks waiting for a slot) rather than the scanned window: the
294 * starved one — the oldest, once it has waited `STARVATION_MS` — and the
295 * approved pulls' (an approval on the check's own commit, no change
296 * requested, the rule of `approvedForCheck`), in one batch per round, never
297 * one query per row. The starved one is approximate: `pickNext` passes over a
298 * check whose repository is at its concurrency limit and takes the next, a
299 * live state the lane does not read.
288 * The queued checks' ids in the order the scheduler takes them: `pickOrder` over the whole queued
289 * set (small: checks waiting for a slot), with the scheduler's own predicates (the starved, the
290 * approved, the owner's own, rank, outside contributors), so the lane and the scheduler read one
291 * ordering, never two copies.
300292 */
301 function checkTiers(db: Database, now: string): { starved: string | null; approved: string[] } {
302 const queued = db
303 .query<{ id: string; at: string; issue_id: string | null; oid: string | null }, [string]>(
304 `SELECT id, created_at AS at, issue_id, commit_oid AS oid FROM run
305 WHERE kind = 'check' AND state = 'queued' AND (not_before IS NULL OR not_before <= ?1)
306 ORDER BY created_at ASC, id ASC`,
307 )
308 .all(now);
309 const o = queued[0];
310 const starved = o !== undefined && Date.parse(now) - Date.parse(o.at) >= STARVATION_MS ? o.id : null;
311 const approved: string[] = [];
312 const left = queued.filter((r) => r.issue_id !== null && r.oid !== null);
313 // One summary per issue and commit; a second commit of the same issue waits for the next round.
314 while (left.length > 0) {
315 const round = new Map<string, (typeof left)[number]>();
316 for (let i = left.length - 1; i >= 0; i--) {
317 const r = left[i]!;
318 if (round.has(r.issue_id!)) continue;
319 round.set(r.issue_id!, r);
320 left.splice(i, 1);
321 }
322 const sums = reviewSummariesFor(db, [...round].map(([id, r]) => ({ id, headOid: r.oid! })));
323 for (const [id, r] of round) {
324 const seen = sums.get(id);
325 if (seen !== undefined && seen.approvals > 0 && seen.changesRequested === 0) approved.push(r.id);
326 }
327 }
328 return { starved, approved };
293 function checkOrder(db: Database, now: string): string[] {
294 const queued = listActive(db, "check").filter((r) => r.state === "queued" && (r.notBefore === null || r.notBefore <= now));
295 return pickOrder(queued, Date.parse(now), approvedOnce(db), rankOnce(db), outsideOnce(db), ownOnce(db)).map((r) => r.id);
329296 }
330297
331298 /** Approved pulls waiting for a person, oldest approval first. */
src/kernel/budgets.ts +8
@@ -46,6 +46,14 @@ export const BUDGETS = {
4646 */
4747 export const STARVATION_MS = BUDGETS.laneWait / 2;
4848
49 /**
50 * How long any queued check may wait before it goes ahead of the owner's own pulls
51 * (`checks/own_first.ts`): twice the lane's budget. The owner's own work (their pulls, the
52 * conductor's and Talk's direct lane's among them) jumps the crew's queue; past this the oldest
53 * check takes the next slot, so a busy owner never starves the crew.
54 */
55 export const CREW_WAIT_CAP_MS = 2 * BUDGETS.laneWait;
56
4957 /** The run limits, in ms, a budget kill is measured against today. */
5058 export type BudgetLimits = {
5159 readonly gate: number;
src/web/pages/pull.ts +9 −2
@@ -14,7 +14,8 @@ import { pullRoster } from "../studio/pull_roster.ts";
1414 import { originCheckLead, originCheckOf } from "../../origins/pull-check.ts";
1515 import { askCheck, askedWords } from "../../checks/again.ts";
1616 import { isPileChoice, pileWords, takePileChoice } from "../../crew/stuck_pile.ts";
17 import { placeWords, queuePlace } from "../../checks/place.ts";
17 import { placeWords, queuePlace, type Place } from "../../checks/place.ts";
18 import { OWN_FIRST_WORDS } from "../../checks/own_first.ts";
1819 import { addCommentThrough } from "../../actions/issues.ts";
1920 import { COMMENT_EMPTY, COMMENT_NOT_POSTED } from "../../actions/comment_words.ts";
2021 import { PULL_GONE } from "../../actions/pull_words.ts";
@@ -484,6 +485,12 @@ async function tierOf(
484485
485486 // ---- the merge box ----
486487
488 /**
489 * Where a queued check stands, and when it is the owner's own pull, that it goes ahead of the
490 * crew's.
491 */
492 const placeAndOwn = (p: Place | undefined): string => (p === undefined ? "" : p.own ? `${placeWords(p)}, ${OWN_FIRST_WORDS}` : placeWords(p));
493
487494 /**
outdated

This const now sits between the docblock above ("address answers it ... check's counts come from its own log") and pullChecksLine, which it describes. Move it above that docblock so the docblock stays attached to its function.

488495 * The checks line of a pull, as the merge box shows it and as its live
489496 * address answers it: one function, so the two never disagree. A running
@@ -518,7 +525,7 @@ function pullChecksLine(
518525 stale,
519526 progress,
520527 `${thread}/checks-line`,
521 placeWords(check.run === null ? undefined : queuePlace(ctx.app.db, check.run)),
528 placeAndOwn(check.run === null ? undefined : queuePlace(ctx.app.db, check.run)),
522529 );
523530 const found = !isApp ? null : pullPreviewFindings(ctx.app.db, repo.id, previewEnv(pull.number));
524531 const red = redAloneLine(redMark(repo.id, pull.id, status.headOid));
test/checks-own-first.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * The owner's own pulls go ahead of the crew's checks (`checks/own_first.ts`): tonight's #16913
3 * waited 26 minutes behind them, because the five-minute starvation rule always took the oldest
4 * crew check. An approved pull still goes first, a check that has waited `CREW_WAIT_CAP_MS` takes
5 * the next slot, and only a person who owns the repository counts: an agent's pull, or another
6 * person's, gets no place ahead. The home checks lane reads the same order (`pickOrder`).
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createAgent } from "../src/actions/crew.ts";
14 import { openPull } from "../src/actions/pulls.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import type { Pull } from "../src/core/pulls.ts";
17 import type { Repo } from "../src/core/repos.ts";
18 import { submitReview } from "../src/core/reviews.ts";
19 import { createRun, type Run } from "../src/core/runs.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { ownOnce, ownPull } from "../src/checks/own_first.ts";
22 import { queuePlace } from "../src/checks/place.ts";
23 import { approvedOnce } from "../src/checks/approved_first.ts";
24 import { pickNext } from "../src/checks/service.ts";
25 import { pickOrder } from "../src/checks/pick.ts";
26 import { outsideOnce } from "../src/checks/outside_lane.ts";
27 import { rankOnce } from "../src/checks/ranked_first.ts";
28 import { listActive } from "../src/core/runs.ts";
29 import { readFast } from "../src/flow/lanes_read.ts";
30 import { CREW_WAIT_CAP_MS, STARVATION_MS } from "../src/kernel/budgets.ts";
31
32 let dataDir: string;
33 let app: App;
34 let alice: User;
35 let bob: User;
36 let bot: User;
37 let repo: Repo;
38 let n = 0;
39
40 /** A pull in Alice's repository, opened by Alice and then said to be `author`'s. */
41 async function pull(author: User): Promise<Pull> {
42 const i = ++n;
43 const branch = await commitToBranch(app, alice, repo, { branch: `f/${i}`, base: "main", message: `Change ${i}`, files: [{ path: `f${i}.ts`, content: `export const f = ${i};\n` }] });
44 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
45 const opened = await openPull(app, alice, repo, { title: `Change ${i}`, body: "", baseBranch: "main", headBranch: `f/${i}` });
46 if (!opened.ok) throw new Error(String(opened.error));
47 app.db.query("UPDATE issue SET author_id = ?2 WHERE id = ?1").run(opened.value.id, author.id);
48 return opened.value;
49 }
50
51 /** Its check, queued `ago` ms before now. */
52 const check = (p: Pull, ago: number): Run => {
53 const run = createRun(app.db, { repoId: repo.id, kind: "check", env: `pull-${p.number}`, issueId: p.id, commitOid: p.headOid });
54 return { ...run, createdAt: new Date(Date.now() - ago).toISOString() };
55 };
56
57 beforeAll(async () => {
58 dataDir = await mkdtemp(join(tmpdir(), "forge-own-first-"));
59 app = createApp({ dataDir, port: 0 });
60 const mk = async (username: string, first = false) => {
61 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
62 if (!u.ok) throw new Error(u.error);
63 return u.value;
64 };
65 alice = await mk("alice", true);
66 bob = await mk("bob");
67 const made = await createRepo(app, alice, { name: "game", visibility: "private" });
68 if (!made.ok) throw new Error(String(made.error));
69 repo = made.value;
70 const seeded = await commitToBranch(app, alice, repo, { branch: "main", message: "Start", files: [{ path: "README.md", content: "game\n" }] });
71 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
72 const agent = await createAgent(app, alice, { username: "builderbot" });
73 if (!agent.ok) throw new Error(String(agent.error));
74 bot = agent.value.user;
75 }, 30_000);
76
77 afterAll(async () => {
78 app.close();
79 await rm(dataDir, { recursive: true, force: true });
80 });
81
82 test("only the repository owner's own pull, a person's, counts", async () => {
83 const mine = await pull(alice);
84 const crews = await pull(bot);
85 const bobs = await pull(bob);
86 expect(ownPull(app.db, check(mine, 0))).toBe(true);
87 expect(ownPull(app.db, check(crews, 0))).toBe(false);
88 expect(ownPull(app.db, check(bobs, 0))).toBe(false);
89 });
90
91 test("the owner's pull goes ahead of crew checks past the starvation rule; an approved pull still goes first", async () => {
92 const crewOld = check(await pull(bot), STARVATION_MS * 2);
93 const crewNew = check(await pull(bot), 1_000);
94 const mine = check(await pull(alice), 0);
95 const own = ownOnce(app.db);
96 // Without the rule the oldest crew check (past five minutes) would take the slot.
97 expect(pickNext([crewOld, crewNew, mine], Date.now(), approvedOnce(app.db))?.id).toBe(crewOld.id);
98 expect(pickNext([crewOld, crewNew, mine], Date.now(), approvedOnce(app.db), undefined, undefined, own)?.id).toBe(mine.id);
99 // An approved crew pull is the last thing before a landing: it still goes first.
100 const approvedPull = await pull(bot);
101 const approved = check(approvedPull, 2_000);
102 const r = submitReview(app.db, { issueId: approvedPull.id, authorId: alice.id, state: "approved", commitOid: approvedPull.headOid });
103 if (!r.ok) throw new Error(r.error);
104 expect(pickNext([crewOld, approved, mine], Date.now(), approvedOnce(app.db), undefined, undefined, own)?.id).toBe(approved.id);
105 });
106
107 test("the crew keeps its share: a check that has waited the cap takes the next slot", async () => {
108 const starved = check(await pull(bot), CREW_WAIT_CAP_MS + 60_000);
109 const mine = check(await pull(alice), 0);
110 expect(pickNext([starved, mine], Date.now(), undefined, undefined, undefined, ownOnce(app.db))?.id).toBe(starved.id);
111 });
112
113 test("an agent's or another person's pull gets no place ahead", async () => {
114 const crewOld = check(await pull(bot), STARVATION_MS * 2);
115 const bobs = check(await pull(bob), 0);
116 expect(pickNext([crewOld, bobs], Date.now(), undefined, undefined, undefined, ownOnce(app.db))?.id).toBe(crewOld.id);
117 });
118
119 test("the checks line's place says it goes ahead, read in the place's own statement, only for the owner's queued check", async () => {
120 const mine = check(await pull(alice), 0);
121 expect(queuePlace(app.db, mine)?.own).toBe(true);
122 expect(queuePlace(app.db, check(await pull(bot), 0))?.own).toBe(false);
123 expect(queuePlace(app.db, check(await pull(bob), 0))?.own).toBe(false);
124 expect(queuePlace(app.db, { ...mine, state: "running" })).toBeUndefined();
125 });
126
127 test("the home checks lane names the same check next as pickNext, an own pull queued behind older crew checks", async () => {
128 const crewOld = check(await pull(bot), 0);
129 const mine = check(await pull(alice), 0);
130 // The crew's check has waited past the starvation rule, short of the cap.
131 app.db.query("UPDATE run SET created_at = ?2 WHERE id = ?1").run(crewOld.id, new Date(Date.now() - STARVATION_MS * 2).toISOString());
132 // Every other queued check is out of the way: this is the queue the scheduler sees.
133 app.db.query("UPDATE run SET state = 'cancelled' WHERE kind = 'check' AND state = 'queued' AND id NOT IN (?1, ?2)").run(crewOld.id, mine.id);
134 const queued = listActive(app.db, "check").filter((r) => r.state === "queued");
135 const scheduler = pickNext(queued, Date.now(), approvedOnce(app.db), rankOnce(app.db), outsideOnce(app.db), ownOnce(app.db));
136 expect(scheduler?.id).toBe(mine.id);
137 const lane = readFast(app.db, new Date()).lanes.checks;
138 const first = lane.items.find((i) => i.position === 1)!;
139 expect(first.runId).toBe(scheduler!.id);
140 expect(first.hint).toContain("next in line");
141 expect(pickOrder(queued, Date.now(), approvedOnce(app.db), rankOnce(app.db), outsideOnce(app.db), ownOnce(app.db)).map((r) => r.id)).toEqual([mine.id, crewOld.id]);
142 });

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

Keyboard shortcuts

Docs