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

A check that started and has written nothing is found and asked again, so six… #16111

Merged opened this in answer to

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

Merged

mason/forge:mason/16105-a-check-that-started-and-has-written-not → main 0 commits fork

  • Merged. mason/16105-a-check-that-started-and-has-written-not was merged into main as 1d0a24d.

Review

Sign in to review this change.
14 files changed +365 −23
scripts/spawn-argv-allow.json +6
@@ -148,5 +148,11 @@
148148 "kind": "spawn",
149149 "code": "[opener, …]",
150150 "why": "opener is \"open\" or \"xdg-open\" by platform, decided on the line above; the URL is one argument"
151 },
152 {
153 "file": "src/git/read.ts",
154 "kind": "spawn",
155 "code": "[...this.command, …]",
156 "why": "command is a constructor seam whose default is [\"git\", \"cat-file\"]; only tests pass another, and no request text reaches it; the mode is one fixed flag"
151157 }
152158 ]
src/checks/execute.ts +35 −9
@@ -4,7 +4,7 @@ import { announceRun } from "../actions/runs.ts";
44 import { announceShard } from "./shard_event.ts";
55 import { issueMayRun } from "../core/pull_trust.ts";
66 import type { Repo } from "../core/repos.ts";
7 import { cancelRun, getRun, claimRun, finishRun, overranBefore, vanishedBefore, VANISHED_SUMMARY, infraBefore, INFRA_SUMMARY, CPU_STOP_SUMMARY, DISK_USED_SUMMARY, requeueCheck, chainCutOffs, CHECK_RELEASE_LIMIT, RELEASE_SUMMARY, type Run } from "../core/runs.ts";
7 import { cancelRun, getRun, claimRun, finishRun, overranBefore, vanishedBefore, VANISHED_SUMMARY, infraBefore, INFRA_SUMMARY, stalledBefore, STALLED_SUMMARY, CPU_STOP_SUMMARY, DISK_USED_SUMMARY, requeueCheck, chainCutOffs, CHECK_RELEASE_LIMIT, RELEASE_SUMMARY, type Run } from "../core/runs.ts";
88 import { withDisk } from "./disk_red.ts";
99 import { proposeRevert } from "./revert_red.ts";
1010 import { afterVerify, closeOnGreen } from "./culprit.ts";
@@ -23,6 +23,7 @@ import { isUsedRefusal } from "../apps/disk_guard.ts";
2323 import { JOB_VANISHED } from "./job_step.ts";
2424 import { describeJob, type CheckJob, type CheckOutcome } from "./runner.ts";
2525 import type { LaneState } from "./lane_state.ts";
26 import { offeredToRunner, STALLED_FAILURE, STALL_MS, watchStall } from "./stall.ts";
2627
2728 const log = createLog("checks");
2829
@@ -50,12 +51,17 @@ export async function execute(
5051 if (!claimed) return;
5152 const lease = holdLease(app.db, run.id);
5253 announceRun(app, claimed);
54 let wrote = false;
5355 const write = (line: string): void => {
56 wrote = true;
5457 appendRunLog(app.config.dataDir, run.id, line);
5558 announceShard(app, run, line);
5659 };
57 if (options.label !== undefined)
60 // The label is the forge's own line, not the check's: it does not count as the check writing.
61 if (options.label !== undefined) {
5862 write(`forge ${options.label} — checked in its parent's lane`);
63 wrote = false;
64 }
5965 const started = Date.now();
6066 // The budget: past it the check is aborted, whatever it is doing.
6167 const limit = checkLimitMs(run.env, {
@@ -71,13 +77,33 @@ export async function execute(
7177 overran = true;
7278 budget.abort();
7379 }, limit);
74 const outcome = await check(lane, claimed, repo, write, budget.signal).finally(
75 () => {
76 clearTimeout(clock);
77 signal.removeEventListener("abort", forward);
78 lease();
79 },
80 );
80 // A check that writes nothing and is offered to no runner is left, not waited for: its slot
81 // is freed even when the runner never answers the abort (#16105).
82 const stall = watchStall(options.stallMs ?? STALL_MS, () => wrote, () => offeredToRunner(app.db, run.id));
83 const ran = check(lane, claimed, repo, write, budget.signal);
84 ran.catch(() => {});
85 const result = await Promise.race([ran, stall.stalled]).finally(() => {
86 stall.stop();
87 clearTimeout(clock);
88 signal.removeEventListener("abort", forward);
89 lease();
90 });
91 if (result === "stalled") {
92 budget.abort();
93 if (!stalledBefore(app.db, claimed)) {
94 const moved = requeueCheck(app.db, run.id, undefined, STALLED_SUMMARY);
95 if (moved) {
96 write(STALLED_SUMMARY);
97 announceRun(app, moved.again, run.actorId ?? undefined);
98 return;
99 }
100 }
101 write(STALLED_FAILURE);
102 const failed = finishRun(app.db, run.id, { state: "failed", summary: STALLED_FAILURE });
103 if (failed) announceRun(app, failed);
104 return;
105 }
106 const outcome = result;
81107 // Where a check cut off here is asked again. A verification is of the
82108 // default branch as it stands: it goes back at the branch's newest
83109 // checked commit, the one `askVerifications` would ask of. Left at the
src/checks/lane_state.ts +5
@@ -29,6 +29,11 @@ export interface ChecksOptions {
2929 readonly label?: string | undefined;
3030 /** How long a check may run before it is killed. @default BUDGETS.gate */
3131 readonly budgetMs?: number | undefined;
32 /**
33 * How long a running check may have written nothing and been offered to no runner before it is
34 * stopped and queued again (#16105). @default STALL_MS
35 */
36 readonly stallMs?: number | undefined;
3237 /** How long a verification of the default branch may run. @default BUDGETS.verify */
3338 readonly verifyBudgetMs?: number | undefined;
3439 /**
src/checks/stall.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * A check that started and has written nothing (#16105). On 2026-11-23 six checks sat in
3 * `running` for hours, each with an empty log, a heartbeat the forge kept fresh and no job
4 * offered to any runner: they hung before their first line, and held every slot of the lane.
5 * A check writes its first line within seconds and offers its job within seconds after, so five
6 * minutes with neither is a hang, not a slow check.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 /** How long a running check may write nothing and offer no job before it is stopped, ms. */
12 export const STALL_MS = 5 * 60_000;
13
14 /** Whether a runner was offered anything for this run: its job is queued, claimed or done. */
15 export function offeredToRunner(db: Database, runId: string): boolean {
16 return db.query("SELECT 1 FROM check_job WHERE run_id = ?1 LIMIT 1").get(runId) !== null;
17 }
18
19 /** The plain reason a check that stalled twice fails with. */
20 export const STALLED_FAILURE = "check stalled: started and wrote nothing, offered to no runner, twice; not trying again";
21
22 /**
23 * Watch a check: `stalled` settles when `ms` passes with no line written (`wrote()`) and no job
24 * offered (`offered()`), so the caller can leave a runner that never returns. `stop` ends the
25 * watch.
26 */
27 export function watchStall(
28 ms: number,
29 wrote: () => boolean,
30 offered: () => boolean,
31 ): { stalled: Promise<"stalled">; stop: () => void } {
32 let timer: ReturnType<typeof setTimeout> | undefined;
33 const stalled = new Promise<"stalled">((resolve) => {
34 timer = setTimeout(() => {
35 if (!wrote() && !offered()) resolve("stalled");
36 }, ms);
37 });
38 return { stalled, stop: () => clearTimeout(timer) };
39 }
src/core/runs.ts +14
@@ -630,6 +630,12 @@ export const CPU_STOP_SUMMARY = "failed: infrastructure — stopped for CPU by t
630630 /** What a check says as it is queued again because the disk was 80% used (#11799): the machine's wait, not the pull's. */
631631 export const DISK_USED_SUMMARY = "waiting: the forge's disk is 80% used; queued again when there is room";
632632
633 /**
634 * What a check says as it is queued again after it started and wrote nothing and was offered to no
635 * runner (#16105).
636 */
637 export const STALLED_SUMMARY = "interrupted: started, wrote nothing and was offered to no runner; queued again";
638
633639 /** What a check cut off by its forge being stopped on purpose (a release) says when requeued. */
634640 export const RELEASE_SUMMARY = "interrupted by a release; queued again";
635641
@@ -758,6 +764,14 @@ export function overranBefore(db: Database, run: Run): boolean {
758764 return cutOffBefore(db, run, BUDGET_PREFIX);
759765 }
760766
767 /**
768 * Whether the attempt just before this one stalled at its start: it is queued again once, the
769 * second fails.
770 */
771 export function stalledBefore(db: Database, run: Run): boolean {
772 return cutOffBefore(db, run, STALLED_SUMMARY);
773 }
774
761775 /** Whether the attempt just before this one lost its cluster Job: it is queued again once. */
762776 export function vanishedBefore(db: Database, run: Run): boolean {
763777 return cutOffBefore(db, run, VANISHED_SUMMARY);
src/crew/autonomy.ts +3 −3
@@ -1496,7 +1496,7 @@ export async function autonomyTick(
14961496 // Crew pulls closed today after 3 days in conflict (#5940).
14971497 ...(staleToday === 0 ? {} : { staleClosed: staleToday }),
14981498 // Open pulls, opened/landed per hour and per 6 h, conflicted (#5935).
1499 ...flowVitals(app.db, now),
1499 ...flowVitals(app.db, now, app.config.dataDir),
15001500 active: status.active,
15011501 slots: status.slots,
15021502 // Builders with nothing in flight: what bounds active beside slots and startable (#7006).
@@ -1558,8 +1558,8 @@ export async function autonomyTick(
15581558 }
15591559
15601560 /** The tick line's flow vitals (#5935): the counts in words, and the targets they miss. */
1561 export function flowVitals(db: App["db"], now: Date): { pulls: string; offTarget?: string } {
1562 const v = sharedVitals(db, now);
1561 export function flowVitals(db: App["db"], now: Date, dataDir?: string): { pulls: string; offTarget?: string } {
1562 const v = sharedVitals(db, now, false, dataDir);
15631563 const misses = vitalsMisses(v);
15641564 return { pulls: vitalsWords(v), ...(misses.length === 0 ? {} : { offTarget: misses.join("; ") }) };
15651565 }
src/flow/silent_checks.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * Checks that run and write nothing (#16105). On 2026-11-23 six checks held every slot of the
3 * lane for hours, each `running`, its heartbeat kept fresh, its log empty; the vitals said
4 * nothing. A check writes its first line within seconds of starting, so one that has run
5 * `SILENT_MINUTES` with an empty log is a stalled lane, said in the vitals at once.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { existsSync, statSync } from "node:fs";
10 import { runLogPath } from "../runs/log.ts";
11
12 /** How long a running check may have written nothing before the vitals miss. */
13 export const SILENT_MINUTES = 10;
14
15 export interface SilentChecks {
16 /** Checks running at least `SILENT_MINUTES` with an empty log. */
17 readonly count: number;
18 /** Whole minutes the longest of them has run. */
19 readonly minutes: number;
20 }
21
22 /** The running checks with an empty log, past the bound; counts only, no repository named. */
23 export function readSilentChecks(db: Database, dataDir: string, now: Date, publicOnly = false): SilentChecks {
24 const before = new Date(now.getTime() - SILENT_MINUTES * 60_000).toISOString();
25 const rows = db
26 .query<{ id: string; started_at: string }, [string, number]>(
27 `SELECT run.id AS id, run.started_at AS started_at FROM run JOIN repo r ON r.id = run.repo_id
28 WHERE run.kind = 'check' AND run.state = 'running' AND run.started_at IS NOT NULL AND run.started_at <= ?1
29 AND (?2 = 0 OR r.visibility = 'public')`,
30 )
31 .all(before, publicOnly ? 1 : 0);
32 let count = 0;
33 let oldest = now.getTime();
34 for (const row of rows) {
35 const file = runLogPath(dataDir, row.id);
36 if (existsSync(file) && statSync(file).size > 0) continue;
37 count += 1;
38 oldest = Math.min(oldest, Date.parse(row.started_at));
39 }
40 return { count, minutes: count === 0 ? 0 : Math.floor((now.getTime() - oldest) / 60_000) };
41 }
42
43 /** `2 checks have run 130 minutes with nothing written`. */
44 export function silentWords(s: SilentChecks): string {
45 return `${s.count} check${s.count === 1 ? " has" : "s have"} run ${s.minutes} minutes with nothing written`;
46 }
src/flow/vitals.ts +11 −3
@@ -17,6 +17,7 @@ import { readChecksPile } from "./checks_pile.ts";
1717 import { readOldestApproved } from "./oldest_approved.ts";
1818 import { readStranded } from "./stranded.ts";
1919 import { kept } from "./kept.ts";
20 import { readSilentChecks, silentWords, type SilentChecks } from "./silent_checks.ts";
2021
2122 /** A stranded pull named with its dollars (#12440). */
2223 export interface NamedPull {
@@ -61,6 +62,11 @@ export interface Vitals {
6162 readonly batches6h: number;
6263 /** Share of those that went red; null when none finished. */
6364 readonly redBatchRate: number | null;
65 /**
66 * Checks running past `SILENT_MINUTES` with an empty log (#16105); left out when the reader has
67 * no data directory.
68 */
69 readonly silentChecks?: SilentChecks;
6470 }
6571
6672 /** What a reader is shown: `strandedUsd` is left out for a reader without telemetry:read. */
@@ -81,11 +87,11 @@ export function vitalsFor(v: Vitals, spend: boolean): ShownVitals {
8187 * `readVitals`, one reading shared by its callers for a moment (`kept.ts`): the telemetry's flow
8288 * slices and the crew's tick.
8389 */
84 export function sharedVitals(db: Database, now = new Date(), publicOnly = false): Vitals {
85 return kept(db, publicOnly ? "vitals:public" : "vitals", now.getTime(), () => readVitals(db, now, publicOnly));
90 export function sharedVitals(db: Database, now = new Date(), publicOnly = false, dataDir?: string): Vitals {
91 return kept(db, `${publicOnly ? "vitals:public" : "vitals"}${dataDir === undefined ? "" : ":logs"}`, now.getTime(), () => readVitals(db, now, publicOnly, dataDir));
8692 }
8793
88 export function readVitals(db: Database, now = new Date(), publicOnly = false): Vitals {
94 export function readVitals(db: Database, now = new Date(), publicOnly = false, dataDir?: string): Vitals {
8995 const to = now.toISOString();
9096 const h1 = new Date(now.getTime() - HOUR_MS).toISOString();
9197 const h6 = new Date(now.getTime() - 6 * HOUR_MS).toISOString();
@@ -125,6 +131,7 @@ export function readVitals(db: Database, now = new Date(), publicOnly = false):
125131 pullCheckMinutes1h: gate.pull1h,
126132 batches6h: batches.finished,
127133 redBatchRate: batches.rate,
134 ...(dataDir === undefined ? {} : { silentChecks: readSilentChecks(db, dataDir, now, publicOnly) }),
128135 ...(oldest === null ? {} : { oldestApprovedRef: oldest.ref }),
129136 ...(named.length === 0 ? {} : { strandedPulls: named }),
130137 };
@@ -140,6 +147,7 @@ export function vitalsMisses(v: ShownVitals): string[] {
140147 out.push(`oldest approved pull has waited ${Math.floor(v.oldestApprovedHours)} h${v.oldestApprovedRef ? ` (${v.oldestApprovedRef})` : ""}`);
141148 if (v.redBatchRate !== null && v.redBatchRate > RED_BATCH_TARGET && v.batches6h >= RED_BATCH_MIN)
142149 out.push(`${Math.round(v.redBatchRate * 100)}% of merge batches went red in 6 h`);
150 if (v.silentChecks !== undefined && v.silentChecks.count > 0) out.push(silentWords(v.silentChecks));
143151 return out;
144152 }
145153
src/git/read.ts +58 −7
@@ -38,13 +38,39 @@ function assertBatchSafe(rev: string): void {
3838 }
3939 }
4040
41 /**
42 * How long one read through a long-lived reader may take, ms. A `cat-file` that stops answering
43 * held every read of its repository behind it for minutes on 2026-11-23 (#16105); a read is
44 * milliseconds, a very large blob seconds.
45 */
46 export const READER_DEADLINE_MS = 30_000;
47
48 /**
49 * A read the reader did not answer in time: the reader was killed and the next read starts a new
50 * one.
51 */
52 export class ReaderTimeout extends Error {
53 constructor(dir: string, ms: number) {
54 super(`cat-file did not answer in ${ms} ms in ${dir}; the reader was replaced`);
55 this.name = "ReaderTimeout";
56 }
57 }
58
4159 export class RepoReader {
4260 private batch: BatchProc;
4361 private check: BatchProc;
4462
45 constructor(readonly dir: string) {
46 this.batch = new BatchProc(dir, "--batch");
47 this.check = new BatchProc(dir, "--batch-check");
63 /**
64 * `command` and `deadlineMs` are test seams: the process a reader speaks to, and how long it may
65 * take.
66 */
67 constructor(
68 readonly dir: string,
69 deadlineMs: number = READER_DEADLINE_MS,
70 command: readonly string[] = ["git", "cat-file"],
71 ) {
72 this.batch = new BatchProc(dir, "--batch", deadlineMs, command);
73 this.check = new BatchProc(dir, "--batch-check", deadlineMs, command);
4874 }
4975
5076 /** Full object content. `rev` may be an oid, ref, or `ref:path`. */
@@ -193,6 +219,8 @@ class BatchProc {
193219 constructor(
194220 private readonly dir: string,
195221 private readonly mode: "--batch" | "--batch-check",
222 private readonly deadlineMs: number = READER_DEADLINE_MS,
223 private readonly command: readonly string[] = ["git", "cat-file"],
196224 ) {}
197225
198226 request(rev: string, withBody: true): Promise<Result<GitObject, "missing">>;
@@ -205,17 +233,37 @@ class BatchProc {
205233 // one nothing holds (`own_refs.ts`).
206234 const hold = readerHold(this.dir);
207235 const run = this.queue.then(async () =>
208 hold !== undefined && !(await namesOnlyOwn(hold, [rev])) ? err("missing" as const) : this.exchange(rev, withBody),
236 hold !== undefined && !(await namesOnlyOwn(hold, [rev])) ? err("missing" as const) : this.withDeadline(this.exchange(rev, withBody)),
209237 );
210238 // The queue must survive a failed exchange; errors belong to the caller.
211239 this.queue = run.catch(() => {});
212240 return run;
213241 }
214242
243 /**
244 * `exchange` or, past the deadline, a {@link ReaderTimeout}: the process is killed and dropped so
245 * the read queued behind this one starts a fresh one instead of waiting on a reader that is gone.
246 */
247 private async withDeadline<T>(exchange: Promise<T>): Promise<T> {
248 let timer: ReturnType<typeof setTimeout> | undefined;
249 const late = new Promise<never>((_, reject) => {
250 timer = setTimeout(() => {
251 this.close();
252 reject(new ReaderTimeout(this.dir, this.deadlineMs));
253 }, this.deadlineMs);
254 });
255 exchange.catch(() => {});
256 try {
257 return await Promise.race([exchange, late]);
258 } finally {
259 clearTimeout(timer);
260 }
261 }
262
215263 private ensureProc() {
216264 if (this.proc && this.proc.exitCode === null && !this.proc.killed)
217265 return this.proc;
218 this.proc = Bun.spawn(["git", "cat-file", this.mode], {
266 this.proc = Bun.spawn([...this.command, this.mode], {
219267 cwd: this.dir,
220268 env: gitEnv(),
221269 stdin: "pipe",
@@ -263,10 +311,13 @@ class BatchProc {
263311 private async fill(): Promise<void> {
264312 if (!this.reader)
265313 defect("git.reader_gone", "cat-file stdout reader missing");
266 const { done, value } = await this.reader.next();
314 const reader = this.reader;
315 const { done, value } = await reader.next();
316 // A reader replaced while this read waited (a deadline, a close) is not this one's to judge.
317 if (reader !== this.reader) defect("git.catfile_replaced", `cat-file ${this.mode} was replaced in ${this.dir}`);
267318 if (done === true || value === undefined) {
268319 // Process died mid-read; drop it so the next request respawns.
269 this.proc = undefined;
320 if (reader === this.reader) this.proc = undefined;
270321 defect(
271322 "git.catfile_died",
272323 `cat-file ${this.mode} exited mid-response in ${this.dir}`,
src/system/telemetry.ts +1 −1
@@ -66,7 +66,7 @@ export function* flowSlices(app: App, reader: Reader, now = new Date()): Generat
6666 const requested = requestedWaits(app.db, reader.kind === "agent");
6767 const busy = reviewersBusy(app.db, reader.kind === "agent");
6868 yield;
69 const vitals = vitalsFor(sharedVitals(app.db, now, reader.kind === "agent"), reader.kind === "owner" || reader.spend === true);
69 const vitals = vitalsFor(sharedVitals(app.db, now, reader.kind === "agent", app.config.dataDir), reader.kind === "owner" || reader.spend === true);
7070 yield;
7171 const talk = readTalkResumes(app.db, running().version);
7272 const talkTurns = readTalkTurns(app.db);
src/tui/screens/flow.ts +8
@@ -44,6 +44,7 @@ import { readPipeline, readStepStats, STAGE_HOLDS, STAGE_LABEL, statWords, verdi
4444 import { parkedSays } from "../../flow/parked.ts";
4545 import { firedAlarms } from "../../flow/alarms.ts";
4646 import { readVitals, vitalsFor, vitalsLine } from "../../flow/vitals.ts";
47 import { readSilentChecks, silentWords } from "../../flow/silent_checks.ts";
4748 import type { LeadTime } from "../../flow/lead_time.ts";
4849 import { buildYieldSays } from "../../flow/build_yield.ts";
4950 import { reviewLatencySays } from "../../flow/review_latency.ts";
@@ -159,6 +160,7 @@ export function flowLines(
159160 ...(keeper?.ask == null ? [] : wrap(`${keeper.ask.question} Press l to ${keeper.ask.button.toLowerCase()}.`, inner)),
160161 "",
161162 ...wrap(vitalsLine(vitalsFor(readVitals(db, now, agent !== undefined), agent === undefined)), inner),
163 ...(dataDir === null ? [] : silentLines(db, dataDir, now, agent !== undefined, inner, wrap)),
162164 ...(agent === undefined ? clogLines(readClog(db, now), now.getTime()).flatMap((l) => wrap(l, inner)) : []),
163165 ...(agent === undefined ? clogViewLines(readClogView(db, now), inner, wrap) : []),
164166 ...(agent === undefined ? cpuStopLines(cpuStops(db, now).stopped, cpuClosedPulls(db, now), inner) : []),
@@ -431,3 +433,9 @@ export function flowScreen(
431433 };
432434 return self;
433435 }
436
437 /** The stalled lane, said on its own line when checks run with nothing written (#16105). */
438 function silentLines(db: Database, dataDir: string, now: Date, publicOnly: boolean, width: number, fold: (s: string, w: number) => string[]): string[] {
439 const silent = readSilentChecks(db, dataDir, now, publicOnly);
440 return silent.count === 0 ? [] : fold(`Miss: ${silentWords(silent)}.`, width);
441 }
test/check-stall.test.ts added +97
@@ -0,0 +1,97 @@
1 /**
2 * A check that started and wrote nothing is stopped and queued again once, then failed (#16105).
3 */
4
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { startChecks, type ChecksHandle } from "../src/checks/service.ts";
12 import { STALLED_FAILURE } from "../src/checks/stall.ts";
13 import { STALLED_SUMMARY, listRuns } from "../src/core/runs.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { readSilentChecks, silentWords } from "../src/flow/silent_checks.ts";
16 import { vitalsMisses, readVitals } from "../src/flow/vitals.ts";
17 import { readRunLog } from "../src/runs/log.ts";
18
19 const priorCells = process.env["FORGE_CELLS"]; // env-restored: afterAll
20
21 let dataDir: string;
22 let app: App;
23 let checks: ChecksHandle;
24 let started = 0;
25
26 beforeAll(async () => {
27 process.env["FORGE_CELLS"] = "off"; // env-restored: afterAll
28 dataDir = await mkdtemp(join(tmpdir(), "forge-stall-"));
29 app = createApp({ dataDir, port: 0 });
30 checks = startChecks(app, {
31 forgeUrl: "http://forge.test",
32 concurrency: 1,
33 stallMs: 300,
34 // A runner that never returns, and never writes.
35 runTier: () => {
36 started += 1;
37 return new Promise(() => {});
38 },
39 });
40 });
41
42 afterAll(async () => {
43 if (priorCells === undefined) delete process.env["FORGE_CELLS"];
44 else process.env["FORGE_CELLS"] = priorCells;
45 await checks.stop();
46 app.close();
47 await rm(dataDir, { recursive: true, force: true });
48 });
49
50 test("a runner that never returns frees its slot: queued again once, then failed plainly", async () => {
51 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
52 if (!u.ok) throw new Error(u.error);
53 const made = await createRepo(app, u.value, { name: "hung", visibility: "public" });
54 if (!made.ok) throw new Error(String(made.error));
55 const repo = made.value;
56 const pushed = await commitToBranch(app, u.value, repo, {
57 message: "A check whose runner never answers",
58 files: [{ path: "forge.json", content: `{"check": {"run": "true", "install": ""}}\n` }],
59 });
60 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
61 const oid = pushed.value.commitOid;
62
63 const seen = () => listRuns(app.db, repo.id, { kind: "check", limit: 50 }).filter((r) => r.commitOid === oid);
64 // Looked at on a 50 ms interval until the second attempt has failed.
65 const mine = await new Promise<ReturnType<typeof seen>>((resolve, reject) => {
66 const give = setTimeout(() => reject(new Error("the check was never failed")), 20_000);
67 const look = setInterval(() => {
68 const now = seen();
69 if (!now.some((r) => r.state === "failed")) return;
70 clearInterval(look);
71 clearTimeout(give);
72 resolve(now);
73 }, 50);
74 });
75 expect(mine).toHaveLength(2);
76 const first = mine.find((r) => r.attempt === 0)!;
77 const second = mine.find((r) => r.attempt === 1)!;
78 expect(first.state).toBe("cancelled");
79 expect(first.summary).toBe(STALLED_SUMMARY);
80 expect(second.state).toBe("failed");
81 expect(second.summary).toBe(STALLED_FAILURE);
82 expect(started).toBe(2);
83 expect(readRunLog(dataDir, first.id).lines.join("\n")).toContain(STALLED_SUMMARY);
84 }, 30_000);
85
86 test("the vitals miss names checks that have run with nothing written", () => {
87 const now = new Date();
88 const old = new Date(now.getTime() - 25 * 60_000).toISOString();
89 const repoId = app.db.query<{ id: string }, []>("SELECT id FROM repo LIMIT 1").get()!.id;
90 app.db.query("INSERT INTO run (id, repo_id, kind, state, started_at, heartbeat_at, created_at) VALUES ('silent-1', ?1, 'check', 'running', ?2, ?2, ?2)").run(repoId, old);
91 const silent = readSilentChecks(app.db, dataDir, now);
92 expect(silent).toEqual({ count: 1, minutes: 25 });
93 expect(silentWords(silent)).toBe("1 check has run 25 minutes with nothing written");
94 const misses = vitalsMisses(readVitals(app.db, now, false, dataDir));
95 expect(misses).toContain("1 check has run 25 minutes with nothing written");
96 expect(vitalsMisses(readVitals(app.db, now))).not.toContain("1 check has run 25 minutes with nothing written");
97 });
test/reader-deadline.test.ts added +38
@@ -0,0 +1,38 @@
1 /** A read through a long-lived git reader has a deadline (#16105). */
2
3 import { expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { ReaderTimeout, RepoReader } from "../src/git/read.ts";
8
9 test("a reader that stops answering is replaced and the caller gets an error", async () => {
10 const dir = await mkdtemp(join(tmpdir(), "forge-reader-"));
11 try {
12 // `sh -c "sleep 30"`: a process that never answers, whatever it is asked.
13 const stuck = new RepoReader(dir, 150, ["sh", "-c", "sleep 30", "stuck"]);
14 const started = Date.now();
15 const first = await stuck.object("HEAD").then(() => undefined, (e: unknown) => e);
16 expect(first).toBeInstanceOf(ReaderTimeout);
17 expect(Date.now() - started).toBeLessThan(3000);
18 // The read after it is not held by the dead reader: it gets its own error, in its own time.
19 const second = await stuck.stat("HEAD").then(() => undefined, (e: unknown) => e);
20 expect(second).toBeInstanceOf(ReaderTimeout);
21 stuck.close();
22 } finally {
23 await rm(dir, { recursive: true, force: true });
24 }
25 });
26
27 test("a reader that answers is not cut off", async () => {
28 const dir = await mkdtemp(join(tmpdir(), "forge-reader-"));
29 try {
30 await Bun.$`git init -q ${dir} && git -C ${dir} -c user.email=a@b -c user.name=a commit -q --allow-empty -m x`;
31 const reader = new RepoReader(dir, 5000);
32 const stat = await reader.stat("HEAD");
33 expect(stat.ok).toBe(true);
34 reader.close();
35 } finally {
36 await rm(dir, { recursive: true, force: true });
37 }
38 });
test/timers-named.test.ts +4
@@ -87,6 +87,10 @@ const ALLOWED: readonly Allowed[] = [
8787 ...allow("setTimeout", "the fork-offers list's size budget: one per page render, cleared when the render ends, resolves a promise and runs nothing", [["src/git/offer_size.ts", "done"]]),
8888 ...allow("setTimeout", `an openai runner bash call's kill deadline, ${PER_CONNECTION}`, [["src/crew/openai_runner.ts", "() => { timedOut = true"]]),
8989 ...allow("setTimeout", SLEEP, [["src/crew/openai_runner.ts", "r"]]),
90 ...allow("setTimeout", DEADLINE, [
91 ["src/checks/stall.ts", "() => { if (!wrote()"],
92 ["src/git/read.ts", "() => { this.close(); reject("],
93 ]),
9094 ...allow("setTimeout", `a check.txt wait's deadline, ${PER_CONNECTION}`, [["src/http/check_text.ts", "() => changed.resolve()"]]),
9195 ...allow("setTimeout", `an ssh login's auth deadline, ${PER_CONNECTION}`, [["src/ssh/server.ts", "() => { this.transport.disconnect("]]),
9296 ...allow("setInterval", `an ssh connection's idle watch once it is in (#14786), ${PER_CONNECTION}`, [["src/ssh/server.ts", "() => { if (this.channels.openCount > 0)"]]),

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs