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

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

Closed opened this
Closed without merging

scout/forge:scout/1196-losing-the-runner-slows-the-gate-and-nev → main 7 commits fork 7 threads · 7 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +724 −28
README.md +7
@@ -253,6 +253,13 @@ file), and if you named an agent, the sentence became issue #1, assigned.
253253 never writes back. Merging moves code and touches no data.
254254 - **Every deploy is a run**, and the run is the check on the pull. Turn on
255255 **require checks** and a pull cannot merge until its head is green.
256 If the runner makes no progress for 10 minutes (nothing running, nothing
257 started or finished) the queued checks settle as cancelled, "the runner is
258 not answering" — never red — and vitals says so. Someone with admin can then
259 land the pull with a reason of 1–500 characters: the reason field next to
260 **Land past the check** on the pull page, `m` in the terminal, or
261 `checksUnavailable` on the JSON merge route. The reason is posted on the
262 pull. A red check is never waived.
256263 - A **private** app answers only to someone the forge has vouched for
257264 (`canRead` on the repository, then a signed grant); a public one to anyone.
258265 - **Every app has a terminal.** `ssh -p 2222 <name>@<forge>` runs the app's
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;
outdated

pull.headOid comes from the pull object passed in, so it can be stale. The gate checked the live head (there.headOid / status.headOid). If the head moved in between, the reason comment is skipped. Look the check up at the head that actually landed.

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
@@ -31,6 +31,7 @@ import {
3131 noteRunProgress,
3232 requeueCheck,
3333 REQUEUED_SUMMARY,
34 silenceUnstartedChecks,
3435 sweepAbandonedChecks,
3536 type Run,
3637 } from "../core/runs.ts";
@@ -616,7 +617,16 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
616617 }
617618
618619 const timer = setInterval(() => {
619 if (!stopped) schedule();
620 if (stopped) return;
621 // A check that waited past the bound without a runner taking it up is
622 // said to be unavailable, never red (`RUNNER_SILENT_SUMMARY`).
623 for (const run of silenceUnstartedChecks(

This runs every 5s tick even while inFlight is non-empty, which is the clearest sign the runner is answering. Skip silencing when inFlight.size > 0, or move that test into silenceUnstartedChecks, so a busy queue is never mislabelled.

624 app.db,
625 Date.now(),
626 new Set(inFlight.keys()),
627 ))
628 appendRunLog(app.config.dataDir, run.id, run.summary);
629 schedule();
620630 }, TICK_MS);
621631 schedule();
622632 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
@@ -376,6 +376,58 @@ export function failAbandonedRuns(
376376 .run(cutoff, JSON.stringify(kinds)).changes;
377377 }
378378
379 /**
380 * What a check that never started says: the runner did not take it up in
381 * `RUNNER_WAIT_MAX_MS`. Not a verdict on the change — never red — and the
382 * one string by which a person with admin may land past it (`mergePull`).
383 */
384 export const RUNNER_SILENT_SUMMARY = "the runner is not answering";
385
386 /** How long a check may sit queued before the runner is called silent. */
387 export const RUNNER_WAIT_MAX_MS = 10 * 60_000;
388
389 /** Whether this run is a check the runner never answered. */
390 export const runnerSilent = (run: Run): boolean =>
391 run.kind === "check" &&
392 run.state === "cancelled" &&
393 run.summary === RUNNER_SILENT_SUMMARY;
394
395 /**
396 * Settle the queued checks as unavailable (cancelled, saying so) when the
397 * runner has made no progress: nothing in flight (`inFlight`, or running in
398 * the table) and no check started or finished since `RUNNER_WAIT_MAX_MS`
399 * ago, while the oldest queued one is older than that. A check waiting
400 * behind a working runner is only waiting, so how long one check has waited
401 * is never the test. Returns the runs it settled.
402 */
403 export function silenceUnstartedChecks(
404 db: Database,
405 now: number,
406 inFlight: ReadonlySet<string> = new Set(),
outdated

High (correctness): the cutoff here is per-check queue age, so a check waiting behind a working runner (concurrency 1, several pulls pushed) is cancelled as 'the runner is not answering' and never re-queued. Silence should require the runner to have made no progress in the window: no run in flight and no check started or finished since now - RUNNER_WAIT_MAX_MS. Then settle the queued ones.

407 ): Run[] {
408 if (inFlight.size > 0) return [];
409 const cutoff = new Date(now - RUNNER_WAIT_MAX_MS).toISOString();
410 const alive = db
411 .query<{ n: number }, [string]>(
412 `SELECT COUNT(*) AS n FROM run WHERE kind = 'check' AND (
413 state = 'running' OR started_at >= ?1
414 OR (started_at IS NOT NULL AND finished_at >= ?1))`,
415 )
416 .get(cutoff);
417 if (alive === null || alive.n > 0) return [];
418 const out: Run[] = [];
419 for (const row of db
420 .query<
421 { id: string },
422 [string]
423 >("SELECT id FROM run WHERE kind = 'check' AND state = 'queued' AND created_at < ?1")
424 .all(cutoff)) {
425 const done = cancelRun(db, row.id, RUNNER_SILENT_SUMMARY);
426 if (done) out.push(done);
427 }
428 return out;
429 }
430
379431 /** What a check the forge's own restart cut off says as it is queued again. */
380432 export const REQUEUED_SUMMARY = "interrupted by a restart; queued again";
381433
src/http/api.ts +3
@@ -2866,6 +2866,9 @@ export function apiRoutes(router: Router<Handler>): void {
28662866 found.repo,
28672867 found.pull,
28682868 strategy,
2869 typeof input.checksUnavailable === "string"

The only door for the waiver. The pull page (src/web/pages/pull.ts:1022) and the TUI pull screen (src/tui/screens/pull.ts:581) need the same reason input, shown only when the latest check is runner-silent and the viewer can admin, and the README needs a line on it. Also cap and validate the reason the same way at each boundary (the 500-char check in mergePull covers it if every door passes the raw string through).

2870 ? input.checksUnavailable
2871 : undefined,
28692872 );
28702873 if (!merged.ok) {
28712874 if (typeof merged.error !== "string")
src/kernel/vitals.ts +26 −1
@@ -12,7 +12,13 @@ import type { Database } from "bun:sqlite";
1212 import { statfsSync } from "node:fs";
1313 import { freemem, totalmem } from "node:os";
1414 import { recentErrors, type ErrorLine } from "./log.ts";
15 import { leaseLapsed, listRunning, queueDepth } from "../core/runs.ts";
15 import {
16 leaseLapsed,
17 listRunning,
18 queueDepth,
19 RUNNER_SILENT_SUMMARY,
20 RUNNER_WAIT_MAX_MS,
21 } from "../core/runs.ts";
1622 import { STALE_AFTER_MS } from "../runs/lease.ts";
1723
1824 /** Free disk under this share of the volume is something to say. */
@@ -39,6 +45,8 @@ export interface Vitals {
3945 hostTotalBytes: number;
4046 };
4147 readonly queue: Record<string, number>;
48 /** Checks the runner never took up, in the last hour or still waiting. */
49 readonly runner: { silent: number };
4250 readonly stuck: {
4351 runId: string;
4452 repo: string;
@@ -82,6 +90,22 @@ export function vitals(input: VitalsInput): Vitals {
8290 );
8391 }
8492
93 const silent =
94 input.db
95 .query<{ n: number }, [string, string]>(
96 `SELECT COUNT(*) AS n FROM run
97 WHERE kind = 'check'
98 AND state = 'cancelled' AND summary = ?1 AND finished_at > ?2`,
outdated

High. state = 'queued' AND created_at < ?3 counts a check that is simply waiting behind a busy runner, so admins see 'The runner is not answering' during an ordinary backlog. Count only the settled silent runs (the first branch of this query), or use the same no-progress rule as silenceUnstartedChecks, so that vitals and the gate agree.

99 )
100 .get(
101 RUNNER_SILENT_SUMMARY,
102 new Date(now - 3_600_000).toISOString(),
103 )?.n ?? 0;
104 if (silent > 0)
105 needs.push(
106 `The runner is not answering: ${silent} check${silent === 1 ? "" : "s"} could not start.`,
107 );
108
85109 const stuck: Vitals["stuck"] = [];
86110 for (const { run, repo, issue } of listRunning(input.db)) {
87111 const started = new Date(run.startedAt ?? run.createdAt).getTime();
@@ -121,6 +145,7 @@ export function vitals(input: VitalsInput): Vitals {
121145 hostTotalBytes: totalmem(),
122146 },
123147 queue,
148 runner: { silent },
124149 stuck,
125150 apps,
126151 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 (

The terminal door has no test. Add one where m on a runner-silent check opens the reason prompt for an admin and lands the pull, and a non-admin still gets the checks toast.

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
@@ -29,7 +29,11 @@ import {
2929 type PullStatus,
3030 } from "../../core/pulls.ts";
3131 import { pullMayRun } from "../../core/pull_trust.ts";
32 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
32 import {
33 checkSummary,
34 runnerSilent,
35 type CheckSummary,
36 } from "../../core/runs.ts";
3337 import {
3438 anchorKey,
3539 byAnchor,
@@ -41,7 +45,12 @@ import {
4145 type Side,
4246 } from "../../core/reviews.ts";
4347 import { getUsersByIds } from "../../core/users.ts";
44 import { canWrite, getRepoById, type Repo } from "../../core/repos.ts";
48 import {
49 canAdmin,
50 canWrite,
51 getRepoById,
52 type Repo,
53 } from "../../core/repos.ts";
4554 import { commitLog } from "../../git/read.ts";
4655 import { repoDir } from "../../git/repos.ts";
4756 import { wallOf } from "../../contract/policy.ts";
@@ -414,6 +423,9 @@ function mergeBox(
414423 : check.state === "running" || check.state === "queued"
415424 ? html`This head is still deploying. The merge unlocks when the check
416425 passes.`
426 : check.run !== null && runnerSilent(check.run)
427 ? html`The runner is not answering, so this head was never
428 checked. A person with admin can land it with a reason.`
417429 : check.state === "cancelled"
418430 ? html`The deploy of this head was cancelled. Redeploy the preview,
419431 or push again.`
@@ -426,18 +438,44 @@ function mergeBox(
426438 <p class="merge-sub">${why}</p>
427439 ${reviewsChip(status.reviews, by)} ${checks}
428440 </div>
429 ${when(
430 mayMerge,
431 () =>
432 html`<span class="merge-form"
433 >${btn("Merge pull request", {
434 variant: "primary",
435 icon: "merge",
436 disabled: true,
437 title: "A passing deploy of this head is required first",
438 })}</span
439 >`,
440 )}`,
441 ${check.run !== null &&

This form has no test: it should render only for an admin when the check is runner-silent, and land the pull on POST. It also leaves out the strategy select, so a squash-only repository gets a plain merge here. Either carry the select over, or say in the README that the waiver always merges.

442 runnerSilent(check.run) &&
443 canAdmin(ctx.app.db, repo, ctx.auth.user)
444 ? html`<span class="merge-form">
445 <form method="post" action="${thread}/merge" class="merge-form">
446 <input type="hidden" name="waive" value="1" />
447 <label class="sr-only" for="waiver-strategy">Merge strategy</label>
448 <select class="input" id="waiver-strategy" name="strategy">
449 <option value="merge">Merge commit</option>
450 <option value="squash">Squash and merge</option>
451 </select>
452 <label class="sr-only" for="waiver">Reason for landing</label>
453 <input
454 class="input"
455 id="waiver"
456 name="reason"
457 maxlength="500"
458 required
459 placeholder="Why land without a check?"
460 />
461 ${btn("Land past the check", {
462 variant: "primary",
463 icon: "merge",
464 })}
465 </form>
466 </span>`
467 : when(
468 mayMerge,
469 () =>
470 html`<span class="merge-form"
471 >${btn("Merge pull request", {
472 variant: "primary",
473 icon: "merge",
474 disabled: true,
475 title: "A passing deploy of this head is required first",
476 })}</span
477 >`,
478 )}`,
441479 { tone: "attn", extra: "merge-box" },
442480 );
443481 }
@@ -902,6 +940,8 @@ function mergeFailure(error: AccessError | MergePullError): string {
902940 return "This pull request needs an approving review of its current head, and does not have one. Nothing was merged.";
903941 if (error === "checks_required")
904942 return "This pull request needs a passing deploy of its current head, and does not have one yet. Nothing was merged.";
943 if (error === "waiver_needs_reason")
944 return "Landing past an unanswered check needs a reason of 1 to 500 characters.";
905945 if (error === "forbidden" || error === "unauthorized")
906946 return "You do not have write access to this repository.";
907947 return "That pull request is no longer here.";
@@ -1025,6 +1065,7 @@ export async function pullMergeSubmit(ctx: Ctx): Promise<Response> {
10251065 found.repo,
10261066 found.pull,
10271067 strategy,
1068 field(form, "waive") === "1" ? field(form, "reason") : undefined,
10281069 );
10291070 if (!result.ok) {
10301071 return flashTo(ctx, `${dest}/files`, {
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 +309
@@ -0,0 +1,309 @@
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), {
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), {
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 // A writer who is not an admin posts the form by hand: refused.
178 const post = (cookie: string, fields: Record<string, string>) =>
179 fetch(servers.url + `${pagePath(number)}/merge`, {
180 method: "POST",
181 headers: { cookie },
182 body: new URLSearchParams(fields),
183 redirect: "manual",
184 });
185 await post(bobCookie, { waive: "1", reason: "let me in" });
186 expect(merged(number)).toBe(false);
187
188 // An admin without a reason: refused.
189 await post(aliceCookie, { waive: "1", reason: " " });
190 expect(merged(number)).toBe(false);
191
192 const landed = await post(aliceCookie, {
193 waive: "1",
194 reason: "runner is down",
195 strategy: "squash",
196 });
197 expect(landed.status).toBe(303);
198 expect(merged(number)).toBe(true);
199 const said = listComments(forge.db, id).map((c) => c.body).join("\n");
200 expect(said).toContain("runner is down");
201 expect(said).toContain(RUNNER_SILENT_SUMMARY);
202 });
203
204 test("the API refuses checksUnavailable from a writer who is not an admin, and takes it from an admin", async () => {
205 const { number } = await silentPull();
206 const bobToken = await mint("bob");
207 const aliceToken = await mint("alice");
208 const url = `${servers.url}/api/v1/repos/acme/lighthouse/pulls/${number}/merge`;
209 const call = (token: string, body: unknown) =>
210 fetch(url, {
211 method: "POST",
212 headers: {
213 authorization: `Bearer ${token}`,
214 "content-type": "application/json",
215 },
216 body: JSON.stringify(body),
217 });
218
219 const refused = await call(bobToken, { checksUnavailable: "please" });
220 expect(refused.ok).toBe(false);
221 expect(await refused.text()).toContain("forbidden");
222 expect(merged(number)).toBe(false);
223
224 const bare = await call(aliceToken, { checksUnavailable: " " });
225 expect(bare.ok).toBe(false);
226 expect(await bare.text()).toContain("waiver_needs_reason");
227 expect(merged(number)).toBe(false);
228
229 const landed = await call(aliceToken, { checksUnavailable: "runner down" });
230 expect(landed.status).toBe(200);
231 expect(merged(number)).toBe(true);
232 });
233
234 function boot(user: User): { app: App; stop(): void } {
235 const terminal = headlessTerminal(140, 44);
236 const { app } = createForgeApp(
237 forge,
238 {
239 sshUsername: user.username,
240 remoteAddress: "127.0.0.1",
241 fingerprint: `SHA256:${user.username}`,
242 user,
243 },
244 { terminal, exitHooks: false },
245 );
246 app.start();
247 return { app, stop: () => app.stop() };
248 }
249
250 async function until(app: App, what: string): Promise<void> {
251 const deadline = Date.now() + 30_000;
252 for (;;) {
253 await settleApp(app);
254 if (app.screen.toText().includes(what)) return;
255 if (Date.now() > deadline)
256 throw new Error(`never saw ${what}:\n${app.screen.toText()}`);
257 await new Promise((r) => setTimeout(r, 20));
258 }
259 }
260
261 async function press(app: App, ...keys: string[]): Promise<void> {
262 for (const key of keys) {
263 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
264 await settleApp(app);
265 }
266 }
267
268 async function openPullScreen(app: App, title: string): Promise<void> {
269 await until(app, "acme/lighthouse");
270 await press(app, "enter");
271 await until(app, "README");
272 await press(app, "p");
273 await until(app, title);
274 await press(app, "enter");
275 await until(app, "#");
276 }
277
278 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 () => {
279 const { number, id } = await silentPull();
280 const title = `Pull fix-${n}`;
281
282 const writer = boot(bob);
283 try {
284 await openPullScreen(writer.app, title);
285 await press(writer.app, "m");
286 expect(writer.app.screen.toText()).not.toContain("past the check");
287 expect(merged(number)).toBe(false);
288 } finally {
289 writer.stop();
290 }
291
292 const admin = boot(alice);
293 try {
294 await openPullScreen(admin.app, title);
295 await press(admin.app, "m");
296 await until(admin.app, `Land #${number} past the check`);
297 // An empty reason is refused where it is typed.
298 await press(admin.app, "enter");
299 expect(merged(number)).toBe(false);
300 for (const ch of "runner down") await press(admin.app, ch);
301 await press(admin.app, "enter");
302 await until(admin.app, "merged");
303 expect(merged(number)).toBe(true);
304 const said = listComments(forge.db, id).map((c) => c.body).join("\n");
305 expect(said).toContain("runner down");
306 } finally {
307 admin.stop();
308 }
309 }, 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
@@ -81,7 +81,7 @@ test("a site admin with a read-only token gets the shape; others get the short o
8181 expect(Object.keys(v).sort()).toEqual(
8282 [
8383 "apps", "at", "checkedAt", "commit", "disk", "draining", "errors",
84 "incidents", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
84 "incidents", "memory", "needs", "ok", "queue", "rollout", "runner", "stale", "stuck",
8585 "version",
8686 ].sort(),
8787 );
@@ -148,8 +148,8 @@ test("the number of queries does not grow with runs", () => {
148148 if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id);
149149 }
150150 expect(count()).toBe(before);
151 // The queue and the running runs.
152 expect(before).toBe(2);
151 // The queue, the running runs, and the silent-runner count.
152 expect(before).toBe(3);
153153 });
154154
155155 test("errors are counted, bounded, redacted, and a burst is said", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs