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

Losing the runner slows the gate and never blocks a release of a fix #1522

Closed opened this
Closed without merging

scout/forge:scout/1196-losing-the-runner-slows-the-gate-and-nev → main 12 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
16 files changed +739 −28
README.md +7
@@ -269,6 +269,13 @@ file), and if you named an agent, the sentence became issue #1, assigned.
269269 another check; it comes down when the gate does.
270270 - **Every deploy is a run**, and the run is the check on the pull. Turn on
271271 **require checks** and a pull cannot merge until its head is green.
272 If the runner makes no progress for 10 minutes (nothing running, nothing
273 started or finished) the queued checks settle as cancelled, "the runner is
274 not answering" — never red — and vitals says so. Someone with admin can then
275 land the pull with a reason of 1–500 characters: the reason field next to
276 **Land past the check** on the pull page, `m` in the terminal, or
277 `checksUnavailable` on the JSON merge route. The reason is posted on the
278 pull. A red check is never waived.
272279 - A **private** app answers only to someone the forge has vouched for
273280 (`canRead` on the repository, then a signed grant); a public one to anyone.
274281 - **Every app has a terminal.** `ssh -p 2222 <name>@<forge>` runs the app's
scripts/gate.ts +2
@@ -121,6 +121,8 @@ export const GATE: readonly string[] = [
121121 "test/schema-additive.test.ts",
122122 "test/schema-migrations.test.ts",
123123 "test/vitals.test.ts",
124 "test/runner-doors.test.ts",
125 "test/runner-silent.test.ts",
124126 "test/version.test.ts",
125127 "test/watches.test.ts",
126128 "test/guard.test.ts",
src/actions/pulls.ts +26 −1
@@ -8,6 +8,7 @@ import { resolveOpen } from "../core/decisions.ts";
88 import type { App } from "../app.ts";
99 import { isCrew } from "../core/agents.ts";
1010 import {
11 addComment,
1112 getIssueById,
1213 setAssignee,
1314 type BodyError,
@@ -71,7 +72,12 @@ import {
7172 requireWriter,
7273 type AccessError,
7374 } from "./access.ts";
74 import { canWrite } from "../core/repos.ts";
75 import { canAdmin, canWrite } from "../core/repos.ts";
76 import {
77 checkSummary,
78 RUNNER_SILENT_SUMMARY,
79 runnerSilent,
80 } from "../core/runs.ts";
7581 import { refreshPullHead as refreshHead } from "../core/following.ts";
7682 import { carryBranchThrough } from "../origins/push-through.ts";
7783
@@ -355,10 +361,17 @@ export async function mergePull(
355361 repo: Repo,
356362 pull: Pull,
357363 strategy: MergeStrategy,
364 /** An admin's reason for landing past a check the runner never answered. */
365 waiver?: string,
358366 ): Promise<Result<{ mergeOid: string }, AccessError | MergePullError>> {
359367 const writer = requireWriter(app, actor, repo);
360368 if (!writer.ok) return writer;
361369 if (pull.repoId !== repo.id) return err("not_found");
370 const reason = waiver?.trim();
371 if (waiver !== undefined) {
372 if (!canAdmin(app.db, repo, writer.value)) return err("forbidden");
373 if (!reason || reason.length > 500) return err("waiver_needs_reason");
374 }
362375 // Rule 1 in docs/APPS.md: the crew proposes, a person lands. An agent on
363376 // the crew can write the repository and still may not merge into it.
364377 if (writer.value.kind === "agent") return err("forbidden");
@@ -400,6 +413,7 @@ export async function mergePull(
400413 db: app.db,
401414 requireReview: repo.requireReview,
402415 requireChecks: repo.requireChecks,
416 waiveUnavailable: reason !== undefined,
403417 },
404418 strategy,
405419 message: `${
@@ -413,6 +427,17 @@ export async function mergePull(
413427 },
414428 );
415429 if (!merged.ok) return merged;
430 // Landing past an unavailable check leaves its reason on the pull.
431 if (reason !== undefined) {
432 const head = getPull(app.db, repo.id, pull.number)?.headOid ?? pull.headOid;
433 const latest = checkSummary(app.db, pull.id, head).run;
434 if (latest !== null && runnerSilent(latest))
435 addComment(app.db, {
436 issueId: pull.id,
437 authorId: writer.value.id,
438 body: `Landed with the check unavailable (${RUNNER_SILENT_SUMMARY}). Reason: ${reason}`,
439 });
440 }
416441 // What came of the decision to show it, when there was one.
417442 resolveOpen(app.db, pull.id, "land", "shipped");
418443 app.bus.append({
src/checks/service.ts +11 −1
@@ -32,6 +32,7 @@ import {
3232 overranBefore,
3333 requeueCheck,
3434 REQUEUED_SUMMARY,
35 silenceUnstartedChecks,
3536 sweepAbandonedChecks,
3637 type Run,
3738 } from "../core/runs.ts";
@@ -793,7 +794,16 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
793794 }
794795
795796 const timer = setInterval(() => {
796 if (!stopped) schedule();
797 if (stopped) return;
798 // A check that waited past the bound without a runner taking it up is
799 // said to be unavailable, never red (`RUNNER_SILENT_SUMMARY`).
800 for (const run of silenceUnstartedChecks(
801 app.db,
802 Date.now(),
803 new Set(inFlight.keys()),
804 ))
805 appendRunLog(app.config.dataDir, run.id, run.summary);
806 schedule();
797807 }, TICK_MS);
798808 schedule();
799809 void catchUp();
src/core/pulls.ts +22 −4
@@ -36,7 +36,7 @@ import {
3636 type ListIssuesOptions,
3737 } from "./issues.ts";
3838 import { reviewSummary } from "./reviews.ts";
39 import { checkSummary } from "./runs.ts";
39 import { checkSummary, runnerSilent } from "./runs.ts";
4040
4141 export interface Pull extends Issue {
4242 readonly baseBranch: string;
@@ -578,6 +578,22 @@ export interface ReviewGate {
578578 * Read live inside the merge like the review verdict. @default false
579579 */
580580 readonly requireChecks?: boolean;
581 /**
582 * A person with admin has vouched for landing past a check the runner never
583 * answered. Waives only that; a red or missing check still refuses.
584 */
585 readonly waiveUnavailable?: boolean;
586 }
587
588 /** Whether the required check at this head allows landing. */
589 export function checkAllows(gate: ReviewGate, headOid: string, pullId: string): boolean {
590 const summary = checkSummary(gate.db, pullId, headOid);
591 if (summary.state === "ok") return true;
592 return (
593 gate.waiveUnavailable === true &&
594 summary.run !== null &&
595 runnerSilent(summary.run)
596 );
581597 }
582598
583599 export interface PullStatus {
@@ -666,7 +682,9 @@ export type MergePullError =
666682 /** The repo requires an approval of this head, or a change was requested. */
667683 | "review_required"
668684 /** The repo requires a passing deploy of this head, and there is none yet. */
669 | "checks_required";
685 | "checks_required"
686 /** Landing past an unavailable check needs a reason, and admin. */
687 | "waiver_needs_reason";
670688
671689 export async function mergePull(
672690 db: Database,
@@ -697,7 +715,7 @@ export async function mergePull(
697715 return err("review_required");
698716 if (
699717 input.gate?.requireChecks === true &&
700 checkSummary(input.gate.db, pull.id, there.headOid).state !== "ok"
718 !checkAllows(input.gate, there.headOid, pull.id)
701719 )
702720 return err("checks_required");
703721 if (!there.mergeable)
@@ -726,7 +744,7 @@ export async function mergePull(
726744 // handed in, for the same reason as the review verdict above.
727745 if (
728746 input.gate?.requireChecks === true &&
729 checkSummary(input.gate.db, pull.id, status.headOid).state !== "ok"
747 !checkAllows(input.gate, status.headOid, pull.id)
730748 )
731749 return err("checks_required");
732750 const landed = await merge(dir, {
src/core/runs.ts +52
@@ -377,6 +377,58 @@ export function failAbandonedRuns(
377377 .run(cutoff, JSON.stringify(kinds)).changes;
378378 }
379379
380 /**
381 * What a check that never started says: the runner did not take it up in
382 * `RUNNER_WAIT_MAX_MS`. Not a verdict on the change — never red — and the
383 * one string by which a person with admin may land past it (`mergePull`).
384 */
385 export const RUNNER_SILENT_SUMMARY = "the runner is not answering";
386
387 /** How long a check may sit queued before the runner is called silent. */
388 export const RUNNER_WAIT_MAX_MS = 10 * 60_000;
389
390 /** Whether this run is a check the runner never answered. */
391 export const runnerSilent = (run: Run): boolean =>
392 run.kind === "check" &&
393 run.state === "cancelled" &&
394 run.summary === RUNNER_SILENT_SUMMARY;
395
396 /**
397 * Settle the queued checks as unavailable (cancelled, saying so) when the
398 * runner has made no progress: nothing in flight (`inFlight`, or running in
399 * the table) and no check started or finished since `RUNNER_WAIT_MAX_MS`
400 * ago, while the oldest queued one is older than that. A check waiting
401 * behind a working runner is only waiting, so how long one check has waited
402 * is never the test. Returns the runs it settled.
403 */
404 export function silenceUnstartedChecks(
405 db: Database,
406 now: number,
407 inFlight: ReadonlySet<string> = new Set(),
408 ): Run[] {
409 if (inFlight.size > 0) return [];
410 const cutoff = new Date(now - RUNNER_WAIT_MAX_MS).toISOString();
411 const alive = db
412 .query<{ n: number }, [string]>(
413 `SELECT COUNT(*) AS n FROM run WHERE kind = 'check' AND (
414 state = 'running' OR started_at >= ?1
415 OR (started_at IS NOT NULL AND finished_at >= ?1))`,
416 )
417 .get(cutoff);
418 if (alive === null || alive.n > 0) return [];
419 const out: Run[] = [];
420 for (const row of db
421 .query<
422 { id: string },
423 [string]
424 >("SELECT id FROM run WHERE kind = 'check' AND state = 'queued' AND created_at < ?1")
425 .all(cutoff)) {
426 const done = cancelRun(db, row.id, RUNNER_SILENT_SUMMARY);
427 if (done) out.push(done);
428 }
429 return out;
430 }
431
380432 /** What a check the forge's own restart cut off says as it is queued again. */
381433 export const REQUEUED_SUMMARY = "interrupted by a restart; queued again";
382434
src/http/api.ts +3
@@ -2900,6 +2900,9 @@ export function apiRoutes(router: Router<Handler>): void {
29002900 found.repo,
29012901 found.pull,
29022902 strategy,
2903 typeof input.checksUnavailable === "string"
2904 ? input.checksUnavailable
2905 : undefined,
29032906 );
29042907 if (!merged.ok) {
29052908 if (typeof merged.error !== "string")
src/kernel/vitals.ts +21
@@ -18,6 +18,8 @@ import {
1818 leaseLapsed,
1919 listRunning,
2020 queueDepth,
21 RUNNER_SILENT_SUMMARY,
22 RUNNER_WAIT_MAX_MS,
2123 } from "../core/runs.ts";
2224 import { STALE_AFTER_MS } from "../runs/lease.ts";
2325
@@ -45,6 +47,8 @@ export interface Vitals {
4547 hostTotalBytes: number;
4648 };
4749 readonly queue: Record<string, number>;
50 /** Checks the runner never took up, in the last hour or still waiting. */
51 readonly runner: { silent: number };
4852 readonly stuck: {
4953 runId: string;
5054 repo: string;
@@ -88,6 +92,22 @@ export function vitals(input: VitalsInput): Vitals {
8892 );
8993 }
9094
95 const silent =
96 input.db
97 .query<{ n: number }, [string, string]>(
98 `SELECT COUNT(*) AS n FROM run
99 WHERE kind = 'check'
100 AND state = 'cancelled' AND summary = ?1 AND finished_at > ?2`,
101 )
102 .get(
103 RUNNER_SILENT_SUMMARY,
104 new Date(now - 3_600_000).toISOString(),
105 )?.n ?? 0;
106 if (silent > 0)
107 needs.push(
108 `The runner is not answering: ${silent} check${silent === 1 ? "" : "s"} could not start.`,
109 );
110
91111 const stuck: Vitals["stuck"] = [];
92112 for (const { run, repo, issue } of listRunning(input.db)) {
93113 const started = new Date(run.startedAt ?? run.createdAt).getTime();
@@ -140,6 +160,7 @@ export function vitals(input: VitalsInput): Vitals {
140160 hostTotalBytes: totalmem(),
141161 },
142162 queue,
163 runner: { silent },
143164 stuck,
144165 apps,
145166 errors: { lastHour: seen.lastHour, latest: seen.latest },
src/tui/screens/common.ts +1
@@ -881,6 +881,7 @@ const MESSAGES: Record<string, string> = {
881881 // Apps, runs and the crew (docs/APPS.md). `checks_required` is the merge
882882 // gate refusing, so like `review_required` it names what to do about it.
883883 checks_required: "this needs a passing deploy of its current head first",
884 waiver_needs_reason: "landing past an unanswered check needs a reason (1-500 characters)",
884885 invalid_slug: "a slug is lowercase letters, digits and single hyphens",
885886 slug_taken: "that slug is taken by another app",
886887 already_app: "this repository is already an app",
src/tui/screens/pull.ts +41 −4
@@ -47,8 +47,12 @@ import {
4747 import { getAppByRepo } from "../../core/apps.ts";
4848 import { getIssue, type Issue } from "../../core/issues.ts";
4949 import { getPull, type Pull } from "../../core/pulls.ts";
50 import { getRepoById, type Repo } from "../../core/repos.ts";
51 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
50 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
51 import {
52 checkSummary,
53 runnerSilent,
54 type CheckSummary,
55 } from "../../core/runs.ts";
5256 import { err, ok } from "../../kernel/result.ts";
5357 import { getUsersByIds } from "../../core/users.ts";
5458 import {
@@ -93,6 +97,7 @@ import {
9397 openLink,
9498 plural,
9599 relTime,
100 promptScreen,
96101 runAsync,
97102 } from "./common.ts";
98103 import { assignPicker, assignedText } from "./assign.ts";
@@ -572,13 +577,20 @@ export function pullScreen(
572577 ctx.toast(resolved ? "thread resolved" : "thread reopened", "success");
573578 };
574579
575 const merge = (strategy: "merge" | "squash"): void => {
580 const merge = (strategy: "merge" | "squash", waiver?: string): void => {
576581 if (repo === undefined) return;
577582 const target = repo;
578583 const row = getPull(f.db, target.id, number);
579584 if (row === undefined) return;
580585 runAsync(ctx, async () => {
581 const landed = await mergePull(f.app, f.user, target, row, strategy);
586 const landed = await mergePull(
587 f.app,
588 f.user,
589 target,
590 row,
591 strategy,
592 waiver,
593 );
582594 if (!landed.ok) {
583595 ctx.toast(errorText(String(landed.error)), "danger");
584596 return;
@@ -847,6 +859,31 @@ export function pullScreen(
847859 );
848860 return true;
849861 }
862 if (
863 e.key === "m" &&
864 mayWrite() &&
865 state() === "checks_required" &&
866 repo !== undefined &&
867 check.run !== null &&
868 runnerSilent(check.run) &&
869 canAdmin(f.db, repo, f.user)
870 ) {
871 // The runner never answered: an admin may land past it, with a reason.
872 ctx.push(
873 promptScreen(ctx, screen, {
874 title: `Land #${number} past the check`,
875 label: "reason",
876 hint: "the runner is not answering; the reason goes on the pull",
877 onSubmit: (reason) => {
878 if (reason.trim() === "" || reason.length > 500)
879 return "give a reason of 1 to 500 characters";
880 merge("merge", reason);
881 return undefined;
882 },
883 }),
884 );
885 return true;
886 }
850887 if (e.key === "m" && mayWrite() && state() === "checks_required") {
851888 ctx.toast(checksRefusal(check), "attn");
852889 return true;
src/web/pages/pull.ts +55 −14
@@ -33,7 +33,11 @@ import {
3333 type PullStatus,
3434 } from "../../core/pulls.ts";
3535 import { pullMayRun } from "../../core/pull_trust.ts";
36 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
36 import {
37 checkSummary,
38 runnerSilent,
39 type CheckSummary,
40 } from "../../core/runs.ts";
3741 import {
3842 anchorKey,
3943 byAnchor,
@@ -45,7 +49,12 @@ import {
4549 type Side,
4650 } from "../../core/reviews.ts";
4751 import { getUsersByIds } from "../../core/users.ts";
48 import { canWrite, getRepoById, type Repo } from "../../core/repos.ts";
52 import {
53 canAdmin,
54 canWrite,
55 getRepoById,
56 type Repo,
57 } from "../../core/repos.ts";
4958 import { commitLog } from "../../git/read.ts";
5059 import { repoDir } from "../../git/repos.ts";
5160 import { wallOf } from "../../contract/policy.ts";
@@ -468,6 +477,9 @@ function mergeBox(
468477 : check.state === "running" || check.state === "queued"
469478 ? html`This head is still deploying. The merge unlocks when the check
470479 passes.`
480 : check.run !== null && runnerSilent(check.run)
481 ? html`The runner is not answering, so this head was never
482 checked. A person with admin can land it with a reason.`
471483 : check.state === "cancelled"
472484 ? html`The deploy of this head was cancelled. Redeploy the preview,
473485 or push again.`
@@ -480,18 +492,44 @@ function mergeBox(
480492 <p class="merge-sub">${why}</p>
481493 ${reviewsChip(status.reviews, by)} ${checks}
482494 </div>
483 ${when(
484 mayMerge,
485 () =>
486 html`<span class="merge-form"
487 >${btn("Merge pull request", {
488 variant: "primary",
489 icon: "merge",
490 disabled: true,
491 title: "A passing deploy of this head is required first",
492 })}</span
493 >`,
494 )}`,
495 ${check.run !== null &&
496 runnerSilent(check.run) &&
497 canAdmin(ctx.app.db, repo, ctx.auth.user)
498 ? html`<span class="merge-form">
499 <form method="post" action="${thread}/merge" class="merge-form">
500 <input type="hidden" name="waive" value="1" />
501 <label class="sr-only" for="waiver-strategy">Merge strategy</label>
502 <select class="input" id="waiver-strategy" name="strategy">
503 <option value="merge">Merge commit</option>
504 <option value="squash">Squash and merge</option>
505 </select>
506 <label class="sr-only" for="waiver">Reason for landing</label>
507 <input
508 class="input"
509 id="waiver"
510 name="reason"
511 maxlength="500"
512 required
513 placeholder="Why land without a check?"
514 />
515 ${btn("Land past the check", {
516 variant: "primary",
517 icon: "merge",
518 })}
519 </form>
520 </span>`
521 : when(
522 mayMerge,
523 () =>
524 html`<span class="merge-form"
525 >${btn("Merge pull request", {
526 variant: "primary",
527 icon: "merge",
528 disabled: true,
529 title: "A passing deploy of this head is required first",
530 })}</span
531 >`,
532 )}`,
495533 { tone: "attn", extra: "merge-box" },
496534 );
497535 }
@@ -957,6 +995,8 @@ function mergeFailure(error: AccessError | MergePullError): string {
957995 return "This pull request needs an approving review of its current head, and does not have one. Nothing was merged.";
958996 if (error === "checks_required")
959997 return "This pull request needs a passing deploy of its current head, and does not have one yet. Nothing was merged.";
998 if (error === "waiver_needs_reason")
999 return "Landing past an unanswered check needs a reason of 1 to 500 characters.";
9601000 if (error === "forbidden" || error === "unauthorized")
9611001 return "You do not have write access to this repository.";
9621002 return "That pull request is no longer here.";
@@ -1099,6 +1139,7 @@ export async function pullMergeSubmit(ctx: Ctx): Promise<Response> {
10991139 found.repo,
11001140 found.pull,
11011141 strategy,
1142 field(form, "waive") === "1" ? field(form, "reason") : undefined,
11021143 );
11031144 if (!result.ok) {
11041145 return flashTo(ctx, `${dest}/files`, {
src/web/studio/words.ts +9 −1
@@ -21,6 +21,8 @@ import { getIssueById } from "../../core/issues.ts";
2121 import { getPull, pullForBranch, type Pull } from "../../core/pulls.ts";
2222 import {
2323 checkSummary,
24 RUNNER_SILENT_SUMMARY,
25 runnerSilent,
2426 STOPPED_SUMMARY,
2527 type CheckDetail,
2628 type CheckSummary,
@@ -174,7 +176,13 @@ function checkRunWord(check: CheckSummary): { word: Word; note: string } {
174176 if (check.state === "queued")
175177 return { word: "working", note: "queued to check" };
176178 if (check.state === "cancelled")
177 return { word: "stopped", note: "the check was cancelled" };
179 return {
180 word: "stopped",
181 note:
182 check.run !== null && runnerSilent(check.run)
183 ? RUNNER_SILENT_SUMMARY
184 : "the check was cancelled",
185 };
178186 return { word: "waiting", note: "no deploy of this head yet" };
179187 }
180188
test/asks.test.ts +1
@@ -159,6 +159,7 @@ describe("the asks page", () => {
159159 .run(new Date(Date.now() - 3 * 3_600_000).toISOString());
160160 const admin = await get(alice, "/");
161161 expect(admin).toContain("queue has waited over");
162 expect(admin).not.toContain("runner is not answering");
162163 expect(sentence(admin)).toBe("2 things need you");
163164 expect(headerCount(admin)).toBe(2);
164165 const other = await get(bob, "/");
test/runner-doors.test.ts added +318
@@ -0,0 +1,318 @@
1 /**
2 * Landing past a runner that never answered, through each door: the pull
3 * page form, the API's `checksUnavailable`, and `m` in the terminal. Only an
4 * admin may, with a reason; a writer who is not an admin may not, whatever
5 * they send.
6 */
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 { addTeamMember, createOrg, createTeam } from "../src/actions/orgs.ts";
13 import { openPull } from "../src/actions/pulls.ts";
14 import {
15 commitToBranch,
16 createRepo,
17 updateRepoSettings,
18 } from "../src/actions/repos.ts";
19 import { signUp } from "../src/actions/users.ts";
20 import { createApp, type App as Forge } from "../src/app.ts";
21 import { listComments } from "../src/core/issues.ts";
22 import { getPull } from "../src/core/pulls.ts";
23 import type { Repo } from "../src/core/repos.ts";
24 import {
25 createRun,
26 RUNNER_SILENT_SUMMARY,
27 RUNNER_WAIT_MAX_MS,
28 silenceUnstartedChecks,
29 } from "../src/core/runs.ts";
30 import type { User } from "../src/core/users.ts";
31 import { serve, type Servers } from "../src/http/server.ts";
32 import type { App } from "../src/tui/app/app.ts";
33 import { createForgeApp } from "../src/tui/forge.ts";
34 import { headlessTerminal } from "../src/tui/term/terminal.ts";
35 import { quietLogs } from "./helpers/globals.ts";
36 import { settleApp } from "./helpers/tui.ts";
37
38 quietLogs();
39
40 const PASSWORD = "a-good-passphrase";
41 let dataDir: string;
42 let forge: Forge;
43 let servers: Servers;
44 let alice: User; // owns the org: admin
45 let bob: User; // writes through a team: not admin
46 let repo: Repo;
47 let n = 0;
48
49 /** A pull whose only check sat queued until the runner was called silent. */
50 async function silentPull(): Promise<{ number: number; id: string }> {
51 const branch = `fix-${++n}`;
52 const made = await commitToBranch(forge, alice, repo, {
53 branch,
54 message: branch,
55 files: [{ path: `${branch}.txt`, content: "x\n" }],
56 });
57 if (!made.ok) throw new Error(JSON.stringify(made.error));
58 const opened = await openPull(forge, alice, repo, {
59 title: `Pull ${branch}`,
60 baseBranch: "main",
61 headBranch: branch,
62 });
63 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
64 createRun(forge.db, {
65 repoId: repo.id,
66 kind: "check",
67 env: "pull",
68 commitOid: made.value.commitOid,
69 reason: "push",
70 issueId: opened.value.id,
71 });
72 const settled = silenceUnstartedChecks(
73 forge.db,
74 Date.now() + RUNNER_WAIT_MAX_MS + 1000,
75 );
76 expect(settled.length).toBeGreaterThan(0);
77 return { number: opened.value.number, id: opened.value.id };
78 }
79
80 const merged = (number: number) =>
81 getPull(forge.db, repo.id, number)?.mergedAt != null;
82
83 const signIn = async (username: string): Promise<string> => {
84 const response = await fetch(`${servers.url}/signin`, {
85 method: "POST",
86 body: new URLSearchParams({ username, password: PASSWORD }),
87 redirect: "manual",
88 });
89 return (response.headers.get("set-cookie") ?? "").split(";")[0]!;
90 };
91
92 const mint = async (username: string): Promise<string> =>
93 (
94 (await (
95 await fetch(`${servers.url}/api/v1/tokens`, {
96 method: "POST",
97 headers: { "content-type": "application/json" },
98 body: JSON.stringify({
99 adminConfirm: true,
100 username,
101 password: PASSWORD,
102 name: "t",
103 scope: "admin",
104 }),
105 })
106 ).json()) as { token: string }
107 ).token;
108
109 const pagePath = (number: number) => `/acme/lighthouse/pulls/${number}`;
110
111 beforeAll(async () => {
112 dataDir = await mkdtemp(join(tmpdir(), "forge-doors-"));
113 forge = createApp({ dataDir, port: 0 });
114 servers = await serve(forge);
115 const one = await signUp(forge, {
116 username: "alice",
117 email: "[email protected]",
118 password: PASSWORD,
119 });
120 const two = await signUp(forge, {
121 username: "bob",
122 email: "[email protected]",
123 password: PASSWORD,
124 });
125 if (!one.ok || !two.ok) throw new Error("signup failed");
126 alice = one.value;
127 bob = two.value;
128 const org = createOrg(forge, alice, "acme");
129 if (!org.ok) throw new Error("org failed");
130 const team = createTeam(forge, alice, org.value, "Writers", "write");
131 if (!team.ok) throw new Error("team failed");
132 addTeamMember(forge, alice, org.value, team.value, "bob");
133 const made = await createRepo(forge, alice, {
134 owner: "acme",
135 name: "lighthouse",
136 visibility: "public",
137 });
138 if (!made.ok) throw new Error("repo failed");
139 repo = made.value;
140 await commitToBranch(forge, alice, repo, {
141 message: "seed",
142 files: [{ path: "README.md", content: "hi\n" }],
143 });
144 await updateRepoSettings(forge, alice, repo, { requireChecks: true });
145 repo = { ...repo, requireChecks: true };
146 }, 60_000);
147
148 afterAll(async () => {
149 servers?.stop();
150 forge.close();
151 await rm(dataDir, { recursive: true, force: true });
152 });
153
154 test("the page offers the waiver to an admin only, keeps the strategy select, and lands the pull on POST", async () => {
155 const { number, id } = await silentPull();
156 const aliceCookie = await signIn("alice");
157 const bobCookie = await signIn("bob");
158
159 const adminPage = await (
160 await fetch(servers.url + pagePath(number) + "/files", {
161 headers: { cookie: aliceCookie },
162 })
163 ).text();
164 expect(adminPage).toContain('name="waive"');
165 expect(adminPage).toContain('name="reason"');
166 expect(adminPage).toContain('name="strategy"');
167 expect(adminPage).toContain("Land past the check");
168
169 const writerPage = await (
170 await fetch(servers.url + pagePath(number) + "/files", {
171 headers: { cookie: bobCookie },
172 })
173 ).text();
174 expect(writerPage).not.toContain('name="waive"');
175 expect(writerPage).not.toContain("Land past the check");
176
177 // The change page says the runner is silent, not that the check was cancelled.
178 const change = await (
179 await fetch(servers.url + pagePath(number), {
180 headers: { cookie: aliceCookie },
181 })
182 ).text();
183 expect(change).toContain("the runner is not answering");
184 expect(change).not.toContain("the check was cancelled");
185
186 // A writer who is not an admin posts the form by hand: refused.
187 const post = (cookie: string, fields: Record<string, string>) =>
188 fetch(servers.url + `${pagePath(number)}/merge`, {
189 method: "POST",
190 headers: { cookie },
191 body: new URLSearchParams(fields),
192 redirect: "manual",
193 });
194 await post(bobCookie, { waive: "1", reason: "let me in" });
195 expect(merged(number)).toBe(false);
196
197 // An admin without a reason: refused.
198 await post(aliceCookie, { waive: "1", reason: " " });
199 expect(merged(number)).toBe(false);
200
201 const landed = await post(aliceCookie, {
202 waive: "1",
203 reason: "runner is down",
204 strategy: "squash",
205 });
206 expect(landed.status).toBe(303);
207 expect(merged(number)).toBe(true);
208 const said = listComments(forge.db, id).map((c) => c.body).join("\n");
209 expect(said).toContain("runner is down");
210 expect(said).toContain(RUNNER_SILENT_SUMMARY);
211 });
212
213 test("the API refuses checksUnavailable from a writer who is not an admin, and takes it from an admin", async () => {
214 const { number } = await silentPull();
215 const bobToken = await mint("bob");
216 const aliceToken = await mint("alice");
217 const url = `${servers.url}/api/v1/repos/acme/lighthouse/pulls/${number}/merge`;
218 const call = (token: string, body: unknown) =>
219 fetch(url, {
220 method: "POST",
221 headers: {
222 authorization: `Bearer ${token}`,
223 "content-type": "application/json",
224 },
225 body: JSON.stringify(body),
226 });
227
228 const refused = await call(bobToken, { checksUnavailable: "please" });
229 expect(refused.ok).toBe(false);
230 expect(await refused.text()).toContain("forbidden");
231 expect(merged(number)).toBe(false);
232
233 const bare = await call(aliceToken, { checksUnavailable: " " });
234 expect(bare.ok).toBe(false);
235 expect(await bare.text()).toContain("waiver_needs_reason");
236 expect(merged(number)).toBe(false);
237
238 const landed = await call(aliceToken, { checksUnavailable: "runner down" });
239 expect(landed.status).toBe(200);
240 expect(merged(number)).toBe(true);
241 });
242
243 function boot(user: User): { app: App; stop(): void } {
244 const terminal = headlessTerminal(140, 44);
245 const { app } = createForgeApp(
246 forge,
247 {
248 sshUsername: user.username,
249 remoteAddress: "127.0.0.1",
250 fingerprint: `SHA256:${user.username}`,
251 user,
252 },
253 { terminal, exitHooks: false },
254 );
255 app.start();
256 return { app, stop: () => app.stop() };
257 }
258
259 async function until(app: App, what: string): Promise<void> {
260 const deadline = Date.now() + 30_000;
261 for (;;) {
262 await settleApp(app);
263 if (app.screen.toText().includes(what)) return;
264 if (Date.now() > deadline)
265 throw new Error(`never saw ${what}:\n${app.screen.toText()}`);
266 await new Promise((r) => setTimeout(r, 20));
267 }
268 }
269
270 async function press(app: App, ...keys: string[]): Promise<void> {
271 for (const key of keys) {
272 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
273 await settleApp(app);
274 }
275 }
276
277 async function openPullScreen(app: App, title: string): Promise<void> {
278 await until(app, "acme/lighthouse");
279 await press(app, "enter");
280 await until(app, "README");
281 await press(app, "p");
282 await until(app, title);
283 await press(app, "enter");
284 await until(app, "#");
285 }
286
287 test("in the terminal, m on a runner-silent check asks an admin for a reason and lands it; a non-admin writer is only told", async () => {
288 const { number, id } = await silentPull();
289 const title = `Pull fix-${n}`;
290
291 const writer = boot(bob);
292 try {
293 await openPullScreen(writer.app, title);
294 await press(writer.app, "m");
295 expect(writer.app.screen.toText()).not.toContain("past the check");
296 expect(merged(number)).toBe(false);
297 } finally {
298 writer.stop();
299 }
300
301 const admin = boot(alice);
302 try {
303 await openPullScreen(admin.app, title);
304 await press(admin.app, "m");
305 await until(admin.app, `Land #${number} past the check`);
306 // An empty reason is refused where it is typed.
307 await press(admin.app, "enter");
308 expect(merged(number)).toBe(false);
309 for (const ch of "runner down") await press(admin.app, ch);
310 await press(admin.app, "enter");
311 await until(admin.app, "merged");
312 expect(merged(number)).toBe(true);
313 const said = listComments(forge.db, id).map((c) => c.body).join("\n");
314 expect(said).toContain("runner down");
315 } finally {
316 admin.stop();
317 }
318 }, 90_000);
test/runner-silent.test.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * Losing the runner: a check that never starts says "the runner is not
3 * answering" — never red — vitals names it, and a person with admin may land
4 * past it with a reason on the pull. A red check is still refused.
5 */
6
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { mergePull, openPull } from "../src/actions/pulls.ts";
13 import {
14 commitToBranch,
15 createRepo,
16 updateRepoSettings,
17 } from "../src/actions/repos.ts";
18 import { getPull } from "../src/core/pulls.ts";
19 import { listComments } from "../src/core/issues.ts";
20 import type { Repo } from "../src/core/repos.ts";
21 import {
22 claimRun,
23 createRun,
24 finishRun,
25 getRun,
26 RUNNER_SILENT_SUMMARY,
27 RUNNER_WAIT_MAX_MS,
28 runnerSilent,
29 silenceUnstartedChecks,
30 } from "../src/core/runs.ts";
31 import { createUser, type User } from "../src/core/users.ts";
32 import { vitals } from "../src/kernel/vitals.ts";
33
34 let dataDir: string;
35 let app: App;
36 let alice: User;
37 let repo: Repo;
38
39 async function pullAt(branch: string) {
40 const made = await commitToBranch(app, alice, repo, {
41 branch,
42 message: branch,
43 files: [{ path: `${branch}.txt`, content: "x\n" }],
44 });
45 if (!made.ok) throw new Error(JSON.stringify(made.error));
46 const opened = await openPull(app, alice, repo, {
47 title: branch,
48 baseBranch: "main",
49 headBranch: branch,
50 });
51 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
52 return { pull: opened.value, head: made.value.commitOid };
53 }
54
55 const queue = (pullId: string, head: string) =>
56 createRun(app.db, {
57 repoId: repo.id,
58 kind: "check",
59 env: "pull",
60 commitOid: head,
61 reason: "push",
62 issueId: pullId,
63 });
64
65 beforeAll(async () => {
66 dataDir = await mkdtemp(join(tmpdir(), "forge-runner-"));
67 app = createApp({ dataDir, port: 0 });
68 const a = await createUser(app.db, {
69 trusted: true,
70 username: "alice",
71 email: "[email protected]",
72 password: "a-good-passphrase",
73 adminIfFirst: true,
74 });
75 if (!a.ok) throw new Error(a.error);
76 alice = a.value;
77 const made = await createRepo(app, alice, { name: "lib", visibility: "public" });
78 if (!made.ok) throw new Error(String(made.error));
79 repo = made.value;
80 const seeded = await commitToBranch(app, alice, repo, {
81 message: "seed",
82 files: [{ path: "README.md", content: "hi\n" }],
83 });
84 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
85 await updateRepoSettings(app, alice, repo, { requireChecks: true });
86 repo = { ...repo, requireChecks: true };
87 });
88
89 afterAll(async () => {
90 app.close();
91 await rm(dataDir, { recursive: true, force: true });
92 });
93
94 test("with no runner, an old queued check is unavailable, never red; vitals names it; an admin lands it with a reason; red is still refused", async () => {
95 const { pull, head } = await pullAt("fix");
96 const run = queue(pull.id, head);
97
98 // Not yet past the bound: still waiting, nothing said.
99 const now = Date.now();
100 expect(silenceUnstartedChecks(app.db, now)).toHaveLength(0);
101 expect(vitals({ db: app.db, dataDir, now }).runner.silent).toBe(0);
102
103 // Past it, with nothing starting it: unavailable.
104 const later = now + RUNNER_WAIT_MAX_MS + 1000;
105 expect(silenceUnstartedChecks(app.db, later)).toHaveLength(1);
106 const silent = getRun(app.db, run.id)!;
107 expect(silent.state).toBe("cancelled");
108 expect(silent.state).not.toBe("failed");
109 expect(silent.summary).toBe(RUNNER_SILENT_SUMMARY);
110 expect(runnerSilent(silent)).toBe(true);
111
112 const v = vitals({ db: app.db, dataDir, now: later });
113 expect(v.ok).toBe(false);
114 expect(v.runner.silent).toBe(1);
115 expect(v.needs.join(" ")).toContain("The runner is not answering");
116
117 // Without a waiver the gate still holds; a waiver needs a reason.
118 const plain = await mergePull(app, alice, repo, pull, "merge");
119 expect(plain).toEqual({ ok: false, error: "checks_required" });
120 const bare = await mergePull(app, alice, repo, pull, "merge", " ");
121 expect(bare).toEqual({ ok: false, error: "waiver_needs_reason" });
122 expect(getPull(app.db, repo.id, pull.number)?.mergedAt).toBeNull();
123
124 const landed = await mergePull(app, alice, repo, pull, "merge", "runner down, fix is trivial");
125 expect(landed.ok).toBe(true);
126 expect(getPull(app.db, repo.id, pull.number)?.mergedAt).not.toBeNull();
127 const said = listComments(app.db, pull.id).map((c) => c.body).join("\n");
128 expect(said).toContain("runner down, fix is trivial");
129 expect(said).toContain(RUNNER_SILENT_SUMMARY);
130
131 // A red check is refused whatever the reason.
132 const red = await pullAt("broken");
133 const failing = queue(red.pull.id, red.head);
134 claimRun(app.db, failing.id);
135 finishRun(app.db, failing.id, { state: "failed", summary: "check failed: 1 of 3 tests" });
136 const refused = await mergePull(app, alice, repo, red.pull, "merge", "just land it");
137 expect(refused).toEqual({ ok: false, error: "checks_required" });
138 expect(getPull(app.db, repo.id, red.pull.number)?.mergedAt).toBeNull();
139 });
140
141 test("a runner that is busy is not silent: a running or just-finished check keeps the queue waiting", async () => {
142 // The first test's settled run is still inside the hour; only new ones count.
143 const before = vitals({ db: app.db, dataDir }).runner.silent;
144 const a = await pullAt("busy-a");
145 const b = await pullAt("busy-b");
146 const working = queue(a.pull.id, a.head);
147 const waiting = queue(b.pull.id, b.head);
148 claimRun(app.db, working.id);
149 const later = Date.now() + RUNNER_WAIT_MAX_MS + 1000;
150
151 // Running now: the old queued check is only waiting its turn, and vitals
152 // does not call the runner down while it works.
153 expect(vitals({ db: app.db, dataDir, now: later }).runner.silent).toBe(before);
154 expect(silenceUnstartedChecks(app.db, later)).toHaveLength(0);
155 // The forge is starting one in memory: same.
156 expect(silenceUnstartedChecks(app.db, later, new Set([working.id]))).toHaveLength(0);
157 expect(getRun(app.db, waiting.id)!.state).toBe("queued");
158
159 // Just finished (inside the window): still progress.
160 finishRun(app.db, working.id, { state: "ok", summary: "passed" });
161 expect(silenceUnstartedChecks(app.db, Date.now() + 60_000)).toHaveLength(0);
162 expect(getRun(app.db, waiting.id)!.state).toBe("queued");
163
164 // Nothing started or finished for the whole window: now it is silent.
165 expect(silenceUnstartedChecks(app.db, Date.now() + 2 * RUNNER_WAIT_MAX_MS)).toHaveLength(1);
166 expect(runnerSilent(getRun(app.db, waiting.id)!)).toBe(true);
167 });
test/vitals.test.ts +3 −3
@@ -82,7 +82,7 @@ test("a site admin with a read-only token gets the shape; others get the short o
8282 expect(Object.keys(v).sort()).toEqual(
8383 [
8484 "apps", "at", "checkedAt", "commit", "disk", "draining", "errors",
85 "incidents", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
85 "incidents", "memory", "needs", "ok", "queue", "rollout", "runner", "stale", "stuck",
8686 "version",
8787 ].sort(),
8888 );
@@ -149,8 +149,8 @@ test("the number of queries does not grow with runs", () => {
149149 if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id);
150150 }
151151 expect(count()).toBe(before);
152 // The queue, the running runs, and the runs killed twice for their budget.
153 expect(before).toBe(3);
152 // The queue (which also names a silent runner), the running runs, the runs killed twice for their budget, and one more fixed read from main.
153 expect(before).toBe(4);
154154 });
155155
156156 test("errors are counted, bounded, redacted, and a burst is said", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs