Public: anyone can read this; the crew can change it.
A runner's work outlives a forge restart: the stopping forge hands the job over and the next one takes it back #16991
Check · Review · Land · Live done — Landed and live in production.
runner-adopt → main 0 commits
11 files
changed +370
−36
src/checks/adopt.ts added +40
| @@ -0,0 +1,40 @@ | ||
| 1 | /** | |
| 2 | * Runner work outlives a forge restart (runner-followups item 3). A release used to cancel every | |
| 3 | * check a runner was running and queue it again from nothing: on 2026-12-01 each of three | |
| 4 | * releases cut 9 pull checks of about 15 minutes, and pushed pulls never got a green check between | |
| 5 | * releases. Now the forge that stops hands a claimed job over (`HANDED_OVER`, `runner_step.ts`): | |
| 6 | * the run stays running and the runner keeps its job, its reports answered "try again" while no | |
| 7 | * forge waits on it (`holdForAdoption`). The forge that comes up takes each such check back here, | |
| 8 | * before anything is scheduled, and waits on the runner's answer as the first one would have. | |
| 9 | * | |
| 10 | * A check whose lease went quiet longer than `STALE_AFTER_MS` is not taken back: the abandoned | |
| 11 | * sweep queues it again (`checks/abandoned.ts`), as before. An adopted check whose runner has | |
| 12 | * gone quiet too is queued again by the lease on its job, as any silent runner's is. | |
| 13 | */ | |
| 14 | ||
| 15 | import { getRepoById } from "../core/repos.ts"; | |
| 16 | import { getRun } from "../core/runs.ts"; | |
| 17 | import { STALE_AFTER_MS } from "../runs/lease.ts"; | |
| 18 | import type { LaneState } from "./lane_state.ts"; | |
| 19 | import { adoptableJobs, deskOf, takeBackJob } from "./runner_jobs.ts"; | |
| 20 | import { start } from "./start.ts"; | |
| 21 | ||
| 22 | /** Take back every check the forge before this one left on a runner; how many. */ | |
| 23 | export function adoptRunnerJobs(lane: LaneState, now: number = Date.now()): number { | |
| 24 | if (lane.placement.mode !== "runner") return 0; | |
| 25 | const { db } = lane.app; | |
| 26 | const desk = deskOf(lane.app); | |
| 27 | let taken = 0; | |
| 28 | for (const { jobId, runId } of adoptableJobs(db, now, STALE_AFTER_MS)) { | |
| 29 | if (lane.inFlight.has(runId)) continue; | |
| 30 | const run = getRun(db, runId); | |
| 31 | const repo = run === undefined ? undefined : getRepoById(db, run.repoId); | |
| 32 | if (run === undefined || repo === undefined) continue; | |
| 33 | // One forge takes it back; the runner keeps the job while this one comes to wait on it. | |
| 34 | if (!takeBackJob(db, jobId, now)) continue; | |
| 35 | desk.adopt.set(runId, jobId); | |
| 36 | start(lane, run, repo, true); | |
| 37 | taken++; | |
| 38 | } | |
| 39 | return taken; | |
| 40 | } |
src/checks/execute.ts +19 −5
| @@ -22,18 +22,24 @@ import { cancelledLine } from "../runs/cancelled.ts"; | ||
| 22 | 22 | import { requeueCpuStop } from "./cpu_stop.ts"; |
| 23 | 23 | import { isUsedRefusal } from "../apps/disk_guard.ts"; |
| 24 | 24 | import { JOB_VANISHED } from "./job_step.ts"; |
| 25 | import { HANDED_OVER } from "./runner_step.ts"; | |
| 25 | 26 | import { describeJob, type CheckJob, type CheckOutcome } from "./runner.ts"; |
| 26 | 27 | import type { LaneState } from "./lane_state.ts"; |
| 27 | 28 | import { offeredToRunner, STALLED_FAILURE, STALL_MS, watchStall } from "./stall.ts"; |
| 28 | 29 | |
| 29 | 30 | const log = createLog("checks"); |
| 30 | 31 | |
| 32 | /** The run, when it is still running: what an adopted check takes up. */ | |
| 33 | const stillRunning = (run: Run | undefined): Run | undefined => (run?.state === "running" ? run : undefined); | |
| 34 | ||
| 31 | 35 | export async function execute( |
| 32 | 36 | lane: LaneState, |
| 33 | 37 | run: Run, |
| 34 | 38 | repo: Repo, |
| 35 | 39 | signal: AbortSignal, |
| 36 | 40 | slot = true, |
| 41 | /** Taken over from the forge before this one, still running on its runner (`adoptRunnerJobs`). */ | |
| 42 | adopted = false, | |
| 37 | 43 | ): Promise<void> { |
| 38 | 44 | const { app, options } = lane; |
| 39 | 45 | // The verification lane takes no slot of the gate (`startVerify`). |
| @@ -44,15 +50,17 @@ export async function execute( | ||
| 44 | 50 | if (lane.stopped) return; |
| 45 | 51 | // Asked again as it starts: a check queued before a rule changed, or |
| 46 | 52 | // handed back by a forge that stopped, runs only what may run now. |
| 47 | if (!issueMayRun(app.db, repo, run.issueId, run.commitOid)) { | |
| 53 | // An adopted check was approved and claimed by the forge before: it is still running, and this | |
| 54 | // forge only takes up its lease. | |
| 55 | if (!adopted && !issueMayRun(app.db, repo, run.issueId, run.commitOid)) { | |
| 48 | 56 | cancelRun(app.db, run.id, "waiting for a writer to approve this head"); |
| 49 | 57 | return; |
| 50 | 58 | } |
| 51 | const claimed = claimRun(app.db, run.id); | |
| 59 | const claimed = adopted ? stillRunning(getRun(app.db, run.id)) : claimRun(app.db, run.id); | |
| 52 | 60 | if (!claimed) return; |
| 53 | 61 | const lease = holdLease(app.db, run.id); |
| 54 | 62 | trackCompute(meterOf(app.db), run.id, `check:${run.id}`); |
| 55 | announceRun(app, claimed); | |
| 63 | if (!adopted) announceRun(app, claimed); | |
| 56 | 64 | let wrote = false; |
| 57 | 65 | const write = (line: string): void => { |
| 58 | 66 | wrote = true; |
| @@ -64,7 +72,10 @@ export async function execute( | ||
| 64 | 72 | write(`forge ${options.label} — checked in its parent's lane`); |
| 65 | 73 | wrote = false; |
| 66 | 74 | } |
| 67 | const started = Date.now(); | |
| 75 | // An adopted check's time counts from when it really started, so a release does not give it | |
| 76 | // a fresh budget. | |
| 77 | const began = adopted && claimed.startedAt !== null ? Date.parse(claimed.startedAt) : Number.NaN; | |
| 78 | const started = Number.isFinite(began) ? began : Date.now(); | |
| 68 | 79 | // The budget: past it the check is aborted, whatever it is doing. |
| 69 | 80 | const limit = checkLimitMs(run.env, { |
| 70 | 81 | gate: options.budgetMs ?? BUDGETS.gate, |
| @@ -78,7 +89,7 @@ export async function execute( | ||
| 78 | 89 | const clock = setTimeout(() => { |
| 79 | 90 | overran = true; |
| 80 | 91 | budget.abort(); |
| 81 | }, limit); | |
| 92 | }, Math.max(0, limit - (Date.now() - started))); | |
| 82 | 93 | // A check that writes nothing and is offered to no runner is left, not waited for: its slot |
| 83 | 94 | // is freed even when the runner never answers the abort (#16105). |
| 84 | 95 | const stall = watchStall(options.stallMs ?? STALL_MS, () => wrote, () => offeredToRunner(app.db, run.id)); |
| @@ -151,6 +162,9 @@ export async function execute( | ||
| 151 | 162 | write(cancelledLine(row) ?? `superseded: ${row.summary}`); |
| 152 | 163 | return; |
| 153 | 164 | } |
| 165 | // Handed over for a release: the run stays running and its runner keeps the job; the forge | |
| 166 | // that comes up takes both back (`adoptRunnerJobs`). Nothing is queued again. | |
| 167 | if (!outcome.ok && outcome.error === HANDED_OVER && lane.stopped) return; | |
| 154 | 168 | if (!outcome.ok && lane.stopped && signal.aborted) { |
| 155 | 169 | // Cut off by this forge stopping, not by the check: the same check |
| 156 | 170 | // goes back on the queue, and the forge that carries on runs it. |
src/checks/runner_jobs.ts +95 −1
| @@ -676,6 +676,11 @@ export interface JobEar { | ||
| 676 | 676 | export interface Desk { |
| 677 | 677 | readonly claimers: Set<() => void>; |
| 678 | 678 | readonly ears: Map<string, JobEar>; |
| 679 | /** | |
| 680 | * Checks this forge took over from the one before it, by run id: the job their runner still | |
| 681 | * holds (`adoptRunnerJobs`). `runRunnerStep` waits on that job instead of offering a new one. | |
| 682 | */ | |
| 683 | readonly adopt: Map<string, string>; | |
| 679 | 684 | } |
| 680 | 685 | |
| 681 | 686 | const desks = new WeakMap<App, Desk>(); |
| @@ -683,7 +688,7 @@ const desks = new WeakMap<App, Desk>(); | ||
| 683 | 688 | export function deskOf(app: App): Desk { |
| 684 | 689 | let desk = desks.get(app); |
| 685 | 690 | if (desk === undefined) { |
| 686 | desk = { claimers: new Set(), ears: new Map() }; | |
| 691 | desk = { claimers: new Set(), ears: new Map(), adopt: new Map() }; | |
| 687 | 692 | desks.set(app, desk); |
| 688 | 693 | } |
| 689 | 694 | return desk; |
| @@ -746,3 +751,92 @@ export function heldByRunner(db: Database): Map<string, number> { | ||
| 746 | 751 | .map((r) => [r.runner_id, r.n]), |
| 747 | 752 | ); |
| 748 | 753 | } |
| 754 | ||
| 755 | /** | |
| 756 | * A claimed job whose check this process is not waiting on (a forge stopping, or just started): | |
| 757 | * the claim's lease is pushed out so the runner keeps the job until a forge takes it back, and the | |
| 758 | * runner is told to try again. Only while the check is still running: one the forge settled has | |
| 759 | * no one coming back for it, and its job goes. True when the runner should try again; false when | |
| 760 | * the job is no longer this token's. | |
| 761 | */ | |
| 762 | export function holdForAdoption(db: Database, jobId: string, presented: string, now: number, leaseMs: number = LEASE_MS): boolean { | |
| 763 | if (!presented.startsWith(JOB_TOKEN_PREFIX)) return false; | |
| 764 | const row = db | |
| 765 | .query<{ running: number }, [string, string]>( | |
| 766 | `SELECT (SELECT state FROM run WHERE run.id = check_job.run_id) = 'running' AS running FROM check_job | |
| 767 | WHERE id = ?1 AND token_hash = ?2 AND state = 'claimed'`, | |
| 768 | ) | |
| 769 | .get(jobId, sha256(presented)); | |
| 770 | if (row === null) return false; | |
| 771 | if (row.running !== 1) { | |
| 772 | dropJob(db, jobId); | |
| 773 | return false; | |
| 774 | } | |
| 775 | // Pushed out, never pulled in: a handover's longer lease stands. | |
| 776 | db.query("UPDATE check_job SET lease_until = MAX(lease_until, ?2) WHERE id = ?1 AND state = 'claimed'").run(jobId, now + leaseMs); | |
| 777 | return true; | |
| 778 | } | |
| 779 | ||
| 780 | /** How long a handed-over job's claim holds with no forge waiting on it: a restart and a boot. */ | |
| 781 | export const HANDOVER_LEASE_MS = 180_000; | |
| 782 | ||
| 783 | /** What a handed-over job's `result` says while it is claimed: the mark adoption looks for. */ | |
| 784 | const HANDED_OVER_MARK = "handed-over"; | |
| 785 | ||
| 786 | /** | |
| 787 | * The stopping forge leaves a claimed job to its runner and the forge after it: marked, so only a | |
| 788 | * job its forge let go is taken back (never one a live forge still waits on), and its lease pushed | |
| 789 | * out past a restart. False when the job is no longer claimed. | |
| 790 | */ | |
| 791 | export function handOverJob(db: Database, jobId: string, now: number): boolean { | |
| 792 | return ( | |
| 793 | db | |
| 794 | .query("UPDATE check_job SET result = ?2, lease_until = MAX(lease_until, ?3) WHERE id = ?1 AND state = 'claimed'") | |
| 795 | .run(jobId, HANDED_OVER_MARK, now + HANDOVER_LEASE_MS).changes > 0 | |
| 796 | ); | |
| 797 | } | |
| 798 | ||
| 799 | /** | |
| 800 | * Take a handed-over job back: one forge only (the UPDATE's WHERE decides), its mark cleared and | |
| 801 | * its lease that of a job a forge waits on. False when another forge took it first, or it is gone. | |
| 802 | */ | |
| 803 | export function takeBackJob(db: Database, jobId: string, now: number): boolean { | |
| 804 | return ( | |
| 805 | db | |
| 806 | .query("UPDATE check_job SET result = NULL, lease_until = MAX(lease_until, ?3) WHERE id = ?1 AND state = 'claimed' AND result = ?2") | |
| 807 | .run(jobId, HANDED_OVER_MARK, now + LEASE_MS).changes > 0 | |
| 808 | ); | |
| 809 | } | |
| 810 | ||
| 811 | /** | |
| 812 | * A job a forge before this one left claimed under a running check: what `adoptRunnerJobs` takes | |
| 813 | * back. | |
| 814 | */ | |
| 815 | export interface Adoptable { | |
| 816 | readonly jobId: string; | |
| 817 | readonly runId: string; | |
| 818 | } | |
| 819 | ||
| 820 | /** | |
| 821 | * The claimed jobs a forge handed over (`handOverJob`) whose check is still running and was held | |
| 822 | * within `freshMs`: their runner may still be at work. A check whose lease went quiet longer than | |
| 823 | * that is the abandoned sweep's (`checks/abandoned.ts`), and a forge that died without handing | |
| 824 | * over leaves its checks to that sweep too. | |
| 825 | */ | |
| 826 | export function adoptableJobs(db: Database, now: number, freshMs: number): Adoptable[] { | |
| 827 | const since = new Date(now - freshMs).toISOString(); | |
| 828 | return db | |
| 829 | .query<{ jobId: string; runId: string }, [string]>( | |
| 830 | `SELECT check_job.id AS jobId, check_job.run_id AS runId FROM check_job JOIN run ON run.id = check_job.run_id | |
| 831 | WHERE check_job.state = 'claimed' AND check_job.result = 'handed-over' AND run.kind = 'check' AND run.state = 'running' | |
| 832 | AND run.heartbeat_at IS NOT NULL AND run.heartbeat_at >= ?1 | |
| 833 | ORDER BY check_job.id`, | |
| 834 | ) | |
| 835 | .all(since); | |
| 836 | } | |
| 837 | ||
| 838 | /** The job's own spec, as it was offered: an adopted check is judged by the steps it was sent. */ | |
| 839 | export function jobSpec(db: Database, jobId: string): RunnerJob | undefined { | |
| 840 | const row = db.query<{ spec: string }, [string]>("SELECT spec FROM check_job WHERE id = ?1").get(jobId); | |
| 841 | return row === null ? undefined : (JSON.parse(row.spec) as RunnerJob); | |
| 842 | } |
src/checks/runner_step.ts +40 −11
| @@ -23,6 +23,8 @@ import type { CheckOutcome, CheckTier } from "./runner.ts"; | ||
| 23 | 23 | import { |
| 24 | 24 | deskOf, |
| 25 | 25 | dropJob, |
| 26 | handOverJob, | |
| 27 | jobSpec, | |
| 26 | 28 | lapseJobs, |
| 27 | 29 | offerJob, |
| 28 | 30 | runnersAround, |
| @@ -101,8 +103,19 @@ export interface RunnerStepInput { | ||
| 101 | 103 | readonly waitMs?: number | undefined; |
| 102 | 104 | /** Tests stand a clock in. @default Date.now */ |
| 103 | 105 | readonly now?: (() => number) | undefined; |
| 106 | /** | |
| 107 | * Whether this forge is stopping (a release): a job a runner holds is then handed over, not | |
| 108 | * dropped, for the forge that comes up to take back (`adoptRunnerJobs`). | |
| 109 | */ | |
| 110 | readonly handingOver?: (() => boolean) | undefined; | |
| 104 | 111 | } |
| 105 | 112 | |
| 113 | /** | |
| 114 | * Why a step ended without a verdict: this forge stopped and left the job to its runner and the | |
| 115 | * next forge. | |
| 116 | */ | |
| 117 | export const HANDED_OVER = "handed over: the runner keeps the job, and the forge that comes up takes it back"; | |
| 118 | ||
| 106 | 119 | function parseResult(text: string | null): RunnerResult | undefined { |
| 107 | 120 | try { |
| 108 | 121 | const value = JSON.parse(text ?? "") as RunnerResult; |
| @@ -140,16 +153,26 @@ export async function runRunnerStep( | ||
| 140 | 153 | const now = input.now ?? Date.now; |
| 141 | 154 | const waitMs = input.waitMs ?? RUNNER_WAIT_MS; |
| 142 | 155 | const desk = deskOf(app); |
| 156 | // A check the forge before this one handed over: its runner still holds the job, and this waits | |
| 157 | // on it as that forge did, judged by the steps it was sent. | |
| 158 | const adopted = desk.adopt.get(input.runId); | |
| 159 | if (adopted !== undefined) desk.adopt.delete(input.runId); | |
| 160 | const sent = adopted === undefined ? undefined : jobSpec(app.db, adopted); | |
| 143 | 161 | // Nobody to offer it to: not a second is spent waiting. |
| 144 | if (desk.claimers.size === 0 && !runnersAround(app.db, now())) | |
| 162 | if (sent === undefined && desk.claimers.size === 0 && !runnersAround(app.db, now())) | |
| 145 | 163 | return { taken: false, why: "no runner is connected" }; |
| 146 | const job = offerJob(app.db, { | |
| 147 | runId: input.runId, | |
| 148 | repoId: input.repoId, | |
| 149 | dir: input.dir, | |
| 150 | job: input.job, | |
| 151 | author: input.author ?? "", | |
| 152 | }); | |
| 164 | const job = | |
| 165 | sent ?? | |
| 166 | offerJob(app.db, { | |
| 167 | runId: input.runId, | |
| 168 | repoId: input.repoId, | |
| 169 | dir: input.dir, | |
| 170 | job: input.job, | |
| 171 | author: input.author ?? "", | |
| 172 | }); | |
| 173 | const steps = sent?.steps ?? input.job.steps; | |
| 174 | if (sent !== undefined) input.log(`adopted: runner job ${job.id} kept running through the forge's restart`); | |
| 175 | let handedOver = false; | |
| 153 | 176 | let wake: () => void = () => {}; |
| 154 | 177 | let sawEcho = false; |
| 155 | 178 | desk.ears.set(job.id, { |
| @@ -182,7 +205,12 @@ export async function runRunnerStep( | ||
| 182 | 205 | try { |
| 183 | 206 | wakeClaimers(app); |
| 184 | 207 | for (;;) { |
| 185 | if (input.signal.aborted) | |
| 208 | if (input.signal.aborted) { | |
| 209 | // Stopping for a release, a job a runner holds stays with it for the next forge. | |
| 210 | if (input.handingOver?.() === true && handOverJob(app.db, job.id, now())) { | |
| 211 | handedOver = true; | |
| 212 | return { taken: false, why: HANDED_OVER }; | |
| 213 | } | |
| 186 | 214 | return { |
| 187 | 215 | taken: true, |
| 188 | 216 | ran: err("check cancelled"), |
| @@ -190,6 +218,7 @@ export async function runRunnerStep( | ||
| 190 | 218 | contained: false, |
| 191 | 219 | note: "", |
| 192 | 220 | }; |
| 221 | } | |
| 193 | 222 | // Every lapsed lease on the desk, this job's among them, goes back to queued. |
| 194 | 223 | lapseJobs(app.db, now()); |
| 195 | 224 | const view = viewJob(app.db, job.id); |
| @@ -212,7 +241,7 @@ export async function runRunnerStep( | ||
| 212 | 241 | } |
| 213 | 242 | if (view.state === "done") { |
| 214 | 243 | const result = parseResult(view.result); |
| 215 | const read = result === undefined ? undefined : readSteps(input.job.steps, result.steps); | |
| 244 | const read = result === undefined ? undefined : readSteps(steps, result.steps); | |
| 216 | 245 | if (result === undefined || read === undefined) |
| 217 | 246 | return { taken: false, why: `runner ${holder} sent a result that does not match the job's steps` }; |
| 218 | 247 | return { |
| @@ -255,7 +284,7 @@ export async function runRunnerStep( | ||
| 255 | 284 | } |
| 256 | 285 | } finally { |
| 257 | 286 | desk.ears.delete(job.id); |
| 258 | dropJob(app.db, job.id); | |
| 287 | if (!handedOver) dropJob(app.db, job.id); | |
| 259 | 288 | } |
| 260 | 289 | } |
| 261 | 290 |
src/checks/service.ts +4
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | import { holdClock } from "../core/one_core.ts"; |
| 15 | 15 | import type { App } from "../app.ts"; |
| 16 | 16 | import { sweepJobs } from "./runner_jobs.ts"; |
| 17 | import { adoptRunnerJobs } from "./adopt.ts"; | |
| 17 | 18 | import { watchGates, extraGates } from "./queue.ts"; |
| 18 | 19 | import { Gate } from "../git/env.ts"; |
| 19 | 20 | import { capacityCount, noteBooted } from "../core/capacity.ts"; |
| @@ -103,6 +104,9 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 103 | 104 | }; |
| 104 | 105 | |
| 105 | 106 | sweepSoon(app); |
| 107 | // What a runner kept through the restart is this forge's to wait on, before anything new starts. | |
| 108 | const adopted = adoptRunnerJobs(lane); | |
| 109 | if (adopted > 0) log.info("adopted checks a runner kept through the restart", { checks: adopted }); | |
| 106 | 110 | |
| 107 | 111 | // What starts a check: a branch moving, a pull opening, a fork's push |
| 108 | 112 | // moving a pull's head. The commit checked is always the one the pull |
src/checks/start.ts +13 −3
| @@ -7,12 +7,15 @@ import { trackRun, untrackRun } from "../runs/stoppable.ts"; | ||
| 7 | 7 | import { workBegins, workEnds } from "../runs/ending.ts"; |
| 8 | 8 | import type { LaneState } from "./lane_state.ts"; |
| 9 | 9 | import { execute } from "./execute.ts"; |
| 10 | import { deskOf, dropJob } from "./runner_jobs.ts"; | |
| 10 | 11 | import { recheckFinished } from "./recheck_base.ts"; |
| 11 | 12 | |
| 12 | 13 | const log = createLog("checks"); |
| 13 | 14 | |
| 14 | /** Run a queued check here, whichever forge queued it. */ | |
| 15 | export function start(lane: LaneState, run: Run, repo: Repo): void { | |
| 15 | /** | |
| 16 | * Run a queued check here, whichever forge queued it; `adopted`, one the forge before left running. | |
| 17 | */ | |
| 18 | export function start(lane: LaneState, run: Run, repo: Repo, adopted = false): void { | |
| 16 | 19 | const { app } = lane; |
| 17 | 20 | if (lane.inFlight.has(run.id)) return; |
| 18 | 21 | lane.waiting.delete(run.id); |
| @@ -24,7 +27,7 @@ export function start(lane: LaneState, run: Run, repo: Repo): void { | ||
| 24 | 27 | // A person's cancel (`cancelRepoRun`) reaches it through this. |
| 25 | 28 | trackRun(run.id, abort); |
| 26 | 29 | workBegins(app.db, run.id); |
| 27 | const promise = execute(lane, run, repo, abort.signal, !low) | |
| 30 | const promise = execute(lane, run, repo, abort.signal, !low, adopted) | |
| 28 | 31 | .catch((error) => |
| 29 | 32 | log.error("check failed to execute", { |
| 30 | 33 | run: run.id, |
| @@ -37,6 +40,13 @@ export function start(lane: LaneState, run: Run, repo: Repo): void { | ||
| 37 | 40 | // that is heard now (#13291). |
| 38 | 41 | workEnds(app.db, run.id); |
| 39 | 42 | lane.inFlight.delete(run.id); |
| 43 | // An adoption its run never reached the runner step for (proven already, run here instead): | |
| 44 | // the runner's job goes, so it stops on its next report rather than working for no one. | |
| 45 | const left = deskOf(app).adopt.get(run.id); | |
| 46 | if (left !== undefined) { | |
| 47 | deskOf(app).adopt.delete(run.id); | |
| 48 | dropJob(app.db, left); | |
| 49 | } | |
| 40 | 50 | if (lane.verifying === run.id) lane.verifying = undefined; |
| 41 | 51 | // A pull's green that ran while its base moved is of the old tip: asked again once. |
| 42 | 52 | if (run.issueId !== null && !lane.stopped) |
src/checks/tier_runner.ts +13 −3
| @@ -10,7 +10,7 @@ import { recordCrashFlakes } from "./flake.ts"; | ||
| 10 | 10 | import { handoverEnv } from "./handover.ts"; |
| 11 | 11 | import { capacityEnv, checkShardCpus, egressSetting, shardsInForce, shardsLine } from "../core/capacity.ts"; |
| 12 | 12 | import { resolveLimits, STEP_HOSTS } from "../apps/contain.ts"; |
| 13 | import { runRunnerStep, runnerTakes, runnerVerdict } from "./runner_step.ts"; | |
| 13 | import { HANDED_OVER, runRunnerStep, runnerTakes, runnerVerdict } from "./runner_step.ts"; | |
| 14 | 14 | import type { CheckOutcome } from "./runner.ts"; |
| 15 | 15 | import type { LaneState } from "./lane_state.ts"; |
| 16 | 16 | import type { Execution } from "./local_runner.ts"; |
| @@ -89,7 +89,7 @@ export async function tryRunner( | ||
| 89 | 89 | write(shardsLine(shardsInForce(app.db, shardCpus, x.tier === "verify"))); |
| 90 | 90 | // The checkout there is seeded as one here is, read-only (`runner_seeds.ts`). |
| 91 | 91 | const seeds = prepareSeeds(app.config.dataDir, repo, run.id, builtOnBase, write); |
| 92 | let sent: Awaited<ReturnType<typeof send>>; | |
| 92 | let sent: Awaited<ReturnType<typeof send>> | undefined; | |
| 93 | 93 | try { |
| 94 | 94 | sent = await send(app, { |
| 95 | 95 | runId: x.runId, |
| @@ -136,9 +136,19 @@ export async function tryRunner( | ||
| 136 | 136 | output: lines, |
| 137 | 137 | signal, |
| 138 | 138 | waitMs: lane.placement.waitMs, |
| 139 | // A release stopping this forge leaves the job with its runner (`adoptRunnerJobs`). | |
| 140 | handingOver: () => lane.stopped, | |
| 139 | 141 | }); |
| 140 | 142 | } finally { |
| 141 | await dropSeeds(app.config.dataDir, run.id); | |
| 143 | // A handed-over job's runner, or the one after it, may still fetch them; the forge that takes | |
| 144 | // it back drops them when the check ends. | |
| 145 | if (sent === undefined || sent.taken || sent.why !== HANDED_OVER) await dropSeeds(app.config.dataDir, run.id); | |
| 146 | } | |
| 147 | if (sent === undefined) return undefined; | |
| 148 | // Handed over: no verdict here, and not run here either; the forge that comes up waits on it. | |
| 149 | if (!sent.taken && sent.why === HANDED_OVER) { | |
| 150 | write(HANDED_OVER); | |
| 151 | return { ok: false, error: HANDED_OVER }; | |
| 142 | 152 | } |
| 143 | 153 | const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted) : sent.why; |
| 144 | 154 | if (typeof verdict === "string") write(`placement: runner; ${verdict}; running here`); |
src/contract/openapi/routes/postApiV1RunnerJobsId.ts +2 −1
| @@ -10,6 +10,7 @@ export const route: Route = { | ||
| 10 | 10 | auth: false, |
| 11 | 11 | role: "anonymous", |
| 12 | 12 | body: { step: "string", lines: "array", done: "object", abandon: "string" }, |
| 13 | refusals: { not_found: "404: no such job, not this token's job, or its lease is over: stop the job", invalid_result: "422: done is not { steps: [{ name, ok, error?, ms }], contained, note }" }, | |
| 13 | refusals: { not_found: "404: no such job, not this token's job, or its lease is over: stop the job", invalid_result: "422: done is not { steps: [{ name, ok, error?, ms }], contained, note }", adopting: "503: the forge is restarting and no one waits on the job yet: keep it, keep the lines, report again (the lease is pushed out)" }, | |
| 14 | 14 | refuses: [404], |
| 15 | errorStatus: { 503: "`adopting`: the forge is restarting; keep the job and report again" }, | |
| 15 | 16 | }; |
src/http/api/runners.ts +10 −10
| @@ -17,6 +17,7 @@ import { | ||
| 17 | 17 | claimJob, |
| 18 | 18 | deskOf, |
| 19 | 19 | getRunner, |
| 20 | holdForAdoption, | |
| 20 | 21 | holdsClaim, |
| 21 | 22 | jobByToken, |
| 22 | 23 | nextOffer, |
| @@ -32,15 +33,7 @@ import { inFlight } from "../../perf/live.ts"; | ||
| 32 | 33 | import { advertiseRefs, serviceRpc } from "../../git/smart-http.ts"; |
| 33 | 34 | import type { Ctx, Handler } from "../context.ts"; |
| 34 | 35 | import { STRANGER_MAX } from "../limits.ts"; |
| 35 | import { | |
| 36 | apiError, | |
| 37 | body, | |
| 38 | boundedBody, | |
| 39 | json, | |
| 40 | notFound, | |
| 41 | str, | |
| 42 | unauthorized, | |
| 43 | } from "../respond.ts"; | |
| 36 | import { apiError, body, boundedBody, json, notFound, str, tryAgain, unauthorized } from "../respond.ts"; | |
| 44 | 37 | import type { Router } from "../router.ts"; |
| 45 | 38 | import { accountAdmin } from "./admin.ts"; |
| 46 | 39 | |
| @@ -198,7 +191,14 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 198 | 191 | // A runner reports on its job: log lines, then the end. Every report renews the lease. |
| 199 | 192 | router.add("POST", "/api/v1/runner/jobs/:id", async (ctx) => { |
| 200 | 193 | const mine = held(ctx); |
| 201 | if (mine === undefined) return notFound(); | |
| 194 | if (mine === undefined) { | |
| 195 | // Its claim stands but no forge waits on it (one stopping, or one just up): the runner keeps | |
| 196 | // the job and asks again, its lines kept, until a forge takes it back (`checks/adopt.ts`). | |
| 197 | if (holdForAdoption(ctx.app.db, ctx.params.id!, bearer(ctx.request), Date.now())) { | |
| 198 | return tryAgain("adopting", 503, "the forge is restarting: keep the job and report again shortly", 2); | |
| 199 | } | |
| 200 | return notFound(); | |
| 201 | } | |
| 202 | 202 | const input = await boundedBody(ctx.request, REPORT_MAX); |
| 203 | 203 | if (input === "too_large") |
| 204 | 204 | return apiError("too_large", 413, `at most ${REPORT_MAX} bytes`); |
src/runner/main.ts +10 −2
| @@ -54,6 +54,8 @@ const CLAIM_WAIT_S = 20; | ||
| 54 | 54 | /** The pause after a claim the forge could not answer. */ |
| 55 | 55 | const RETRY_MS = 5_000; |
| 56 | 56 | const FETCH_MS = 600_000; |
| 57 | /** How long a job's answer waits for a restarting forge to take the job back. */ | |
| 58 | const HANDOVER_WAIT_MS = 180_000; | |
| 57 | 59 | |
| 58 | 60 | export interface RunnerOptions { |
| 59 | 61 | readonly forgeUrl: string; |
| @@ -198,10 +200,16 @@ export async function runRunner(options: RunnerOptions): Promise<void> { | ||
| 198 | 200 | await reports; |
| 199 | 201 | await flush(); |
| 200 | 202 | if (dropped) return; |
| 201 | // The answer is the job: a forge that did not hear it is told again, while the lease lasts. | |
| 202 | for (let tries = 0; tries < 5; tries++) { | |
| 203 | // The answer is the job: a forge that did not hear it is told again. A forge restarting (not | |
| 204 | // reachable, or 503 while no one waits on the job) is waited for up to `HANDOVER_WAIT_MS`: | |
| 205 | // the forge that comes up takes the job back and wants this answer (`checks/adopt.ts`). | |
| 206 | const until = Date.now() + HANDOVER_WAIT_MS; | |
| 207 | for (let tries = 1; ; tries++) { | |
| 203 | 208 | const res = await post(`/api/v1/runner/jobs/${job.id}`, token, body).catch(() => undefined); |
| 204 | 209 | if (res !== undefined && (res.ok || res.status === 404 || res.status === 422)) return; |
| 210 | await res?.body?.cancel().catch(() => {}); | |
| 211 | const restarting = res === undefined || res.status === 503; | |
| 212 | if (restarting ? Date.now() >= until : tries >= 5) return; | |
| 205 | 213 | await pause(REPORT_MS, new AbortController().signal); |
| 206 | 214 | } |
| 207 | 215 | }; |
test/runner-adopt.test.ts added +124
| @@ -0,0 +1,124 @@ | ||
| 1 | /** | |
| 2 | * A runner's work outlives a forge restart (`checks/adopt.ts`, runner-followups item 3). The | |
| 3 | * forge that stops hands a claimed job over instead of cancelling the check and queueing it again | |
| 4 | * ("interrupted by a release"); the runner's reports are answered 503 while no forge waits on the | |
| 5 | * job, its lease pushed out; the forge that comes up takes the check back and accepts the runner's | |
| 6 | * answer as its verdict. On 2026-12-01 each of three releases cut 9 pull checks of about 15 min. | |
| 7 | */ | |
| 8 | import { beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { openPull } from "../src/actions/pulls.ts"; | |
| 10 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 11 | import { adoptableJobs, deskOf, enrolRunner, viewJob, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 12 | import { startChecks } from "../src/checks/service.ts"; | |
| 13 | import { getRun, RELEASE_SUMMARY } from "../src/core/runs.ts"; | |
| 14 | import { STALE_AFTER_MS } from "../src/runs/lease.ts"; | |
| 15 | import { readRunLog } from "../src/runs/log.ts"; | |
| 16 | import { checkJson, checksForge } from "./helpers/checks-forge.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | const f = checksForge("forge-runner-adopt-"); | |
| 22 | const options = () => ({ forgeUrl: f.servers.url, concurrency: 1, placement: { mode: "runner" as const, waitMs: 300 } }); | |
| 23 | ||
| 24 | const api = (path: string, token: string, body?: unknown): Promise<Response> => | |
| 25 | fetch(`${f.servers.url}${path}`, { | |
| 26 | method: body === undefined ? "GET" : "POST", | |
| 27 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 28 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 29 | }); | |
| 30 | ||
| 31 | async function pull(name: string): Promise<string> { | |
| 32 | const made = await commitToBranch(f.app, f.alice, f.repo, { | |
| 33 | branch: name, | |
| 34 | message: name, | |
| 35 | files: [{ path: `${name}.txt`, content: `${name}\n` }], | |
| 36 | }); | |
| 37 | if (!made.ok) throw new Error(JSON.stringify(made.error)); | |
| 38 | const opened = await openPull(f.app, f.alice, f.repo, { title: name, body: "", baseBranch: "main", headBranch: name }); | |
| 39 | if (!opened.ok) throw new Error(JSON.stringify(opened.error)); | |
| 40 | return made.value.commitOid; | |
| 41 | } | |
| 42 | ||
| 43 | /** A runner of our own claims the next job; the pull `name` is what it gets. */ | |
| 44 | async function claimed(name: string): Promise<{ oid: string; job: RunnerJob; token: string; runId: string }> { | |
| 45 | const box = enrolRunner(f.app.db, `box-${name}`, f.alice.id); | |
| 46 | const asked = api("/api/v1/runner/claim", box.token, { wait: 20, cells: true }); | |
| 47 | await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim"); | |
| 48 | const oid = await pull(name); | |
| 49 | const claim = (await (await asked).json()) as { job: RunnerJob; token: string }; | |
| 50 | return { oid, job: claim.job, token: claim.token, runId: claim.job.run }; | |
| 51 | } | |
| 52 | ||
| 53 | beforeAll(async () => { | |
| 54 | await f.checks.stop(); | |
| 55 | f.checks = startChecks(f.app, options()); | |
| 56 | const gate = await commitToBranch(f.app, f.alice, f.repo, { | |
| 57 | message: "Declare the check", | |
| 58 | files: [{ path: "forge.json", content: checkJson("true") }], | |
| 59 | }); | |
| 60 | if (!gate.ok) throw new Error(JSON.stringify(gate.error)); | |
| 61 | await f.settled((r) => r.commitOid === gate.value.commitOid, 30_000); | |
| 62 | }); | |
| 63 | ||
| 64 | describe("a restart with a job on a runner", () => { | |
| 65 | test("the stopping forge hands the job over; the runner hears 503 and keeps it; the forge that comes up takes it back and its result lands", async () => { | |
| 66 | const c = await claimed("kept"); | |
| 67 | const door = `/api/v1/runner/jobs/${c.job.id}`; | |
| 68 | expect((await api(door, c.token, { step: "check", lines: ["before the restart"] })).status).toBe(200); | |
| 69 | ||
| 70 | // The release: this forge's checks stop. | |
| 71 | await f.checks.stop(); | |
| 72 | const between = getRun(f.app.db, c.runId)!; | |
| 73 | expect(between.state).toBe("running"); | |
| 74 | expect(viewJob(f.app.db, c.job.id)?.state).toBe("claimed"); | |
| 75 | // No forge waits on it: the runner is told to try again, never to drop the job. | |
| 76 | const busy = await api(door, c.token, { step: "check", lines: ["during the restart"] }); | |
| 77 | expect(busy.status).toBe(503); | |
| 78 | expect(busy.headers.get("retry-after")).toBe("2"); | |
| 79 | expect(((await busy.json()) as { error: string }).error).toBe("adopting"); | |
| 80 | // Its claim outlasts a restart and a boot, and a 503 never shortens it. | |
| 81 | const lease = () => f.app.db.query<{ l: number }, [string]>("SELECT lease_until AS l FROM check_job WHERE id = ?1").get(c.job.id)!.l; | |
| 82 | expect(lease()).toBeGreaterThan(Date.now() + 150_000); | |
| 83 | ||
| 84 | // The forge that comes up. | |
| 85 | f.checks = startChecks(f.app, options()); | |
| 86 | await f.until(() => deskOf(f.app).ears.has(c.job.id), "the new forge waiting on the job"); | |
| 87 | expect((await api(door, c.token, { step: "check", lines: ["after the restart"] })).status).toBe(200); | |
| 88 | expect((await api(door, c.token, { done: { steps: [{ name: "check", ok: true, ms: 1 }], contained: true, note: "" } })).status).toBe( | |
| 89 | 200, | |
| 90 | ); | |
| 91 | const run = await f.settled((r) => r.id === c.runId, 30_000); | |
| 92 | expect(run.state).toBe("ok"); | |
| 93 | expect(run.attempt).toBe(between.attempt); | |
| 94 | const log = readRunLog(f.app.config.dataDir, run.id).lines.join("\n"); | |
| 95 | expect(log).toContain("before the restart"); | |
| 96 | expect(log).toContain(`adopted: runner job ${c.job.id} kept running through the forge's restart`); | |
| 97 | expect(log).toContain("after the restart"); | |
| 98 | expect(log).not.toContain(RELEASE_SUMMARY); | |
| 99 | // Nothing was queued again for it. | |
| 100 | expect(f.checksOf(c.oid).filter((r) => r.state === "queued")).toEqual([]); | |
| 101 | // The job is gone with its check, and so is its door. | |
| 102 | expect((await api(door, c.token, { step: "check", lines: ["late"] })).status).toBe(404); | |
| 103 | }); | |
| 104 | ||
| 105 | test("a check whose lease went quiet past the abandoned bound is not taken back", async () => { | |
| 106 | const c = await claimed("quiet"); | |
| 107 | await f.checks.stop(); | |
| 108 | expect(adoptableJobs(f.app.db, Date.now(), STALE_AFTER_MS).map((a) => a.runId)).toContain(c.runId); | |
| 109 | f.app.db | |
| 110 | .query("UPDATE run SET heartbeat_at = ?2 WHERE id = ?1") | |
| 111 | .run(c.runId, new Date(Date.now() - STALE_AFTER_MS - 60_000).toISOString()); | |
| 112 | expect(adoptableJobs(f.app.db, Date.now(), STALE_AFTER_MS).map((a) => a.runId)).not.toContain(c.runId); | |
| 113 | f.checks = startChecks(f.app, options()); | |
| 114 | }); | |
| 115 | ||
| 116 | test("a job a live forge still waits on is never taken back: only one its forge handed over", async () => { | |
| 117 | const c = await claimed("live"); | |
| 118 | // The forge is up and waiting on it: not adoptable, though its heartbeat is fresh. | |
| 119 | expect(adoptableJobs(f.app.db, Date.now(), STALE_AFTER_MS).map((a) => a.runId)).not.toContain(c.runId); | |
| 120 | const door = `/api/v1/runner/jobs/${c.job.id}`; | |
| 121 | expect((await api(door, c.token, { done: { steps: [{ name: "check", ok: true, ms: 1 }], contained: true, note: "" } })).status).toBe(200); | |
| 122 | expect((await f.settled((r) => r.id === c.runId, 30_000)).state).toBe("ok"); | |
| 123 | }); | |
| 124 | }); |
new above
offline