Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

Merge main (GitHub runner fixes #15 and #16) into claude/diffinery-runners-ci

altug authored 2 parents 8e4cb8506d0101commit 600b333850ccf8bc9f231c3e8fe156d1a2e339b1Browse files
7 files changed+269−35
Files (7)
modifiedapps/diffinery/docs/actions/github-runners.md+6−4View file
@@ -1,7 +1,7 @@
11 ---
22 title: GitHub runners
33 description: Keep your code on GitHub and run its Actions jobs on Diffinery's hosted runners: install the app, link the account that pays, and set runs-on to diffinery.
4-updated: 2026-10-30
4+updated: 2026-10-31
55 ---
66
77 You don't have to move your code to use Diffinery's runners. Keep your repositories and workflows on GitHub, install Diffinery's GitHub App, and change a job's `runs-on` to `diffinery`. The job then runs on a Diffinery hosted runner (a fresh Ubuntu 24.04 container with 4 vCPUs on Cloudflare) instead of a GitHub-hosted one. Logs, checks, caches, artifacts and `GITHUB_TOKEN` stay on GitHub, as with any self-hosted runner.
@@ -103,10 +103,10 @@
103103 | starting | The runner is registered and its container is starting, or it waits for GitHub to hand it the job. |
104104 | running | GitHub handed the runner a job. |
105105 | done | The container stopped. The GitHub job's conclusion is shown under it. |
106-| skipped | The job ended before its runner started (cancelled, or another runner took it), or the installation was suspended or unlinked. |
106+| skipped | The job ended before its runner started (cancelled, or run by a runner that isn't one of this account's Diffinery runners), or the installation was suspended or unlinked. |
107107 | failed | No runner was started: the reason is shown, such as a kill switch, minutes used up, or GitHub refusing to register a runner. |
108108
109-GitHub hands a runner any queued job of the repository whose labels it has, so the job a runner ran may be another one with the same labels than the job it was started for. Each queued job still gets one runner.
109+GitHub hands a runner any queued job of the repository whose labels it has, so a runner may run a different queued job with the same labels instead of the one it was started for. Each queued job still gets one runner: the runner's row then shows the job it ran, and the job it was started for waits for the next runner, in its place in line, with its own labels and size.
110110
111111 ## Security
112112
@@ -134,8 +134,10 @@
134134
135135 **"Could not register a runner on GitHub: ... Resource not accessible by integration".** The app lacks the **Administration: Read and write** permission on the repository. An owner of the GitHub account reviews and accepts the app's new permissions in the installation's settings on GitHub (**Choose repositories on GitHub** opens them).
136136
137-**"No job took this runner within 10 minutes".** The job it was started for was cancelled, or ran on another runner with the same labels, and GitHub had no other job for it. Diffinery stopped the runner and removed it from GitHub; nothing to do.
137+**"No job took this runner within 10 minutes".** The job it was started for was cancelled, or ran on another runner with the same labels, and GitHub had no other job for it. This also happens, rarely, when a job is cancelled just as the runner started for it takes a different queued job: Diffinery then starts one more runner for the cancelled job. Diffinery stopped the runner and removed it from GitHub; nothing to do.
138138
139139 **"The runner stopped before it took a job (exit code N); starting another".** GitHub's runner exited before a job started, for example because GitHub was unreachable. Diffinery tries up to 3 runners for a job.
140140
141+**"The runner's container stopped before it took a job; starting another".** The runner's container stopped without an error before GitHub handed it a job, for example because Cloudflare lost the machine it ran on. GitHub still had the job queued, so Diffinery started another runner for it. As with a runner that exited with an error, Diffinery tries up to 3 runners for a job.
142+
141143 **Settings → GitHub runners says "This Diffinery has no GitHub App".** The instance's administrator hasn't set the app up. See [Configuration](/docs/self-hosting/configuration#github-runners).
modifiedapps/diffinery/src/github-runners/GitHubRunnersDO.ts+3−3View file
@@ -40,11 +40,11 @@
4040 await this.wake(accountId, 0);
4141 }
4242
43- /** A runner's container stopped (runner/containers.ts onStop). */
44- async stopped(accountId: string, runnerId: string, exitCode: number | null): Promise<void> {
43+ /** A runner's container stopped (runner/containers.ts onStop); containers started before it said which don't. */
44+ async stopped(accountId: string, runnerId: string, exitCode: number | null, container?: string): Promise<void> {
4545 const r = this.runners();
4646 if (!r) return;
47- await r.stopped(runnerId, exitCode);
47+ await r.stopped(runnerId, exitCode, container);
4848 await this.wake(accountId, 0);
4949 }
5050
modifiedapps/diffinery/src/github-runners/github.ts+10−0View file
@@ -193,6 +193,16 @@
193193 }
194194 }
195195
196+ /** A job's status on GitHub (queued, in_progress, completed and others); null once GitHub no longer has it. */
197+ async jobStatus(installationId: number, repo: string, jobId: number): Promise<string | null> {
198+ try {
199+ return (await this.asInstallation<{ status: string }>(installationId, "GET", `repos/${repo}/actions/jobs/${jobId}`)).status;
200+ } catch (e) {
201+ if (e instanceof GitHubApiError && e.status === 404) return null;
202+ throw e;
203+ }
204+ }
205+
196206 /** Removes a runner that never took a job (one that did removes itself). */
197207 async removeRunner(installationId: number, repo: string, runnerId: number): Promise<void> {
198208 try {
modifiedapps/diffinery/src/github-runners/service.ts+55−14View file
@@ -107,7 +107,7 @@
107107 export function containerHost(env: Env): RunnerHost {
108108 const ns = (container: string) => env[RUNNER_SIZES[sizeOfContainer(container)].binding] ?? env.RUNNER;
109109 return {
110- start: (container, input) => ns(container).get(ns(container).idFromName(container)).startGitHubRunner(input),
110+ start: (container, input) => ns(container).get(ns(container).idFromName(container)).startGitHubRunner({ ...input, container }),
111111 stop: (container) => ns(container).get(ns(container).idFromName(container)).stopJob(false),
112112 has: (size) => size === "large" || !!env[RUNNER_SIZES[size].binding],
113113 };
@@ -170,9 +170,10 @@
170170 .bind(ev.conclusion, ev.githubJobId, ev.jobName, ev.installationId, ev.runnerName)
171171 .run();
172172 }
173+ await this.took(ev.installationId, ev.runnerName, ev.githubJobId);
173174 }
174- // Cancelled before its runner started, or taken by another runner (one started for another job with the same labels):
175- // a runner started for it now would only wait for IDLE_MS.
175+ // Cancelled before its runner started, or ran on a runner that isn't one of this account's: a runner started
176+ // for it now would only wait for IDLE_MS.
176177 if (ev.action === "completed" || ev.runnerName) {
177178 await this.db
178179 .prepare("UPDATE github_runner_jobs SET status = 'skipped', message = ?, conclusion = ?, ended_at = ? WHERE installation_id = ? AND github_job_id = ? AND status = 'queued'")
@@ -182,6 +183,30 @@
182183 }
183184
184185 /**
186+ * A runner took `jobId`, which may not be the job its row was started for. When that job's own row still waits,
187+ * the two rows trade jobs: the runner's row describes the job it runs, and the other row waits for the job the
188+ * runner was started for, which still needs a runner, in that job's place in line.
189+ */
190+ private async took(installationId: number, runnerName: string, jobId: number): Promise<void> {
191+ const a = await this.db.prepare("SELECT * FROM github_runner_jobs WHERE installation_id = ? AND runner_name = ?").bind(installationId, runnerName).first<RunnerJobRow>();
192+ if (!a || a.github_job_id === jobId) return;
193+ const b = await this.db.prepare("SELECT * FROM github_runner_jobs WHERE installation_id = ? AND repo = ? AND github_job_id = ? AND status = 'queued'").bind(installationId, a.repo, jobId).first<RunnerJobRow>();
194+ if (!b) return;
195+ // (installation_id, github_job_id) is unique, so b's job id is negated (GitHub's never are) while a takes it.
196+ // The first step changes nothing unless both rows still hold the jobs they were read with, and the other two
197+ // only follow it. a keeps its size, which is its container's.
198+ const set = "github_job_id = ?, run_id = ?, workflow_name = ?, job_name = ?, html_url = ?, labels = ?, created_at = ?";
199+ const job = (r: RunnerJobRow) => [r.github_job_id, r.run_id, r.workflow_name, r.job_name, r.html_url, r.labels, r.created_at];
200+ await this.db.batch([
201+ this.db
202+ .prepare("UPDATE github_runner_jobs SET github_job_id = -github_job_id WHERE id = ? AND github_job_id = ? AND status = 'queued' AND EXISTS (SELECT 1 FROM github_runner_jobs WHERE id = ? AND github_job_id = ?)")
203+ .bind(b.id, b.github_job_id, a.id, a.github_job_id),
204+ this.db.prepare(`UPDATE github_runner_jobs SET ${set} WHERE id = ? AND EXISTS (SELECT 1 FROM github_runner_jobs WHERE id = ? AND github_job_id = ?)`).bind(...job(b), a.id, b.id, -b.github_job_id),
205+ this.db.prepare(`UPDATE github_runner_jobs SET ${set}, size = ? WHERE id = ? AND github_job_id = ?`).bind(...job(a), a.size, b.id, -b.github_job_id),
206+ ]);
207+ }
208+
209+ /**
185210 * Starts runners for the account's queued jobs, oldest first, and stops runners that took no job or ran too
186211 * long. Returns how soon to look again: null when nothing waits or runs.
187212 */
@@ -330,23 +355,39 @@
330355 await this.ended(row.id, null);
331356 }
332357
333- /** A runner's container stopped (runner/containers.ts onStop), or Diffinery stopped it. */
334- async stopped(rowId: string, exitCode: number | null): Promise<void> {
358+ /** A runner's container stopped (runner/containers.ts onStop), or Diffinery stopped it. `container` is the one that stopped, when it says. */
359+ async stopped(rowId: string, exitCode: number | null, container?: string): Promise<void> {
335360 const row = await this.row(rowId);
336361 if (!row) return;
337- // A runner that crashed before it took a job (nothing of the job ran) is replaced, a few times.
338- if (row.status === "starting" && !row.stop_reason && exitCode !== 0 && exitCode !== null && row.tries < MAX_TRIES) {
339- if (row.container) await endCompute(this.env, row.container).catch(() => {});
340- if (row.github_runner_id) await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id).catch(() => {});
341- await this.db
342- .prepare("UPDATE github_runner_jobs SET status = 'queued', container = NULL, message = ? WHERE id = ? AND status = 'starting'")
343- .bind(`The runner stopped before it took a job (exit code ${exitCode}); starting another`, row.id)
344- .run();
345- return;
362+ // A container the row no longer runs in: one given up on (back in line, or replaced) that stopped late.
363+ if (container && row.container !== container) return;
364+ // A runner that stopped before it took a job (nothing of the job ran) is replaced, a few times: one that crashed,
365+ // and one that stopped without crashing while GitHub still has its job queued. The containers library reports
366+ // exit code 0 for a container the platform lost, and no runner took the job then.
367+ if (row.status === "starting" && !row.stop_reason && row.tries < MAX_TRIES) {
368+ const crashed = exitCode !== 0 && exitCode !== null;
369+ if (crashed || (await this.stillQueued(row))) {
370+ if (row.container) await endCompute(this.env, row.container).catch(() => {});
371+ if (row.github_runner_id) await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id).catch(() => {});
372+ await this.db
373+ .prepare("UPDATE github_runner_jobs SET status = 'queued', container = NULL, message = ? WHERE id = ? AND status = 'starting'")
374+ .bind(crashed ? `The runner stopped before it took a job (exit code ${exitCode}); starting another` : "The runner's container stopped before it took a job; starting another", row.id)
375+ .run();
376+ return;
377+ }
346378 }
347379 await this.ended(rowId, exitCode);
348380 }
349381
382+ /**
383+ * Whether GitHub still has a row's job queued. When GitHub doesn't answer, it counts as queued: a job left
384+ * without a runner waits 24 hours, a runner started for nothing only IDLE_MS.
385+ */
386+ private async stillQueued(row: RunnerJobRow): Promise<boolean> {
387+ const status = await this.gh.jobStatus(row.installation_id, row.repo, row.github_job_id).catch(() => "queued");
388+ return status === "queued";
389+ }
390+
350391 private async ended(rowId: string, exitCode: number | null): Promise<void> {
351392 const row = await this.row(rowId);
352393 if (!row) return;
modifiedapps/diffinery/src/runner/containers.ts+25−13View file
@@ -40,7 +40,7 @@
4040 /** The job a runner container runs; stopRequested once Diffinery asked it to stop (stopJob). */
4141 type RunnerJob = { repoId: string; jobId: string; container?: string; stopRequested?: boolean };
4242 /** A GitHub job's runner (github-runners/): GitHub's own runner, for the account that pays. */
43-type GitHubRunner = { accountId: string; runnerId: string };
43+type GitHubRunner = { accountId: string; runnerId: string; container?: string };
4444
4545 /** How long a job's container may take to come up, and how often it is checked meanwhile. */
4646 const START_WAIT_MS = 180_000;
@@ -53,6 +53,8 @@
5353 export class RunnerContainer extends HostedContainer {
5454 // Jobs make no inbound requests, so activity-based sleep must not stop them.
5555 override sleepAfter = "6h";
56+ /** True while start() runs (startRunner). */
57+ private starting = false;
5658
5759 async startJob(input: { repoId: string; jobId: string; container?: string; token: string; apiUrl: string; egress?: Egress; vcpu?: number }): Promise<void> {
5860 await this.ctx.storage.put("job", { repoId: input.repoId, jobId: input.jobId, container: input.container });
@@ -71,21 +73,26 @@
7173 * configuration GitHub made for it, which holds the runner's credentials, so it is only ever in the
7274 * container's environment.
7375 */
74- async startGitHubRunner(input: { accountId: string; runnerId: string; jitConfig: string; egress: Egress; vcpu: number }): Promise<void> {
75- await this.ctx.storage.put("github", { accountId: input.accountId, runnerId: input.runnerId } satisfies GitHubRunner);
76+ async startGitHubRunner(input: { accountId: string; runnerId: string; container?: string; jitConfig: string; egress: Egress; vcpu: number }): Promise<void> {
77+ await this.ctx.storage.put("github", { accountId: input.accountId, runnerId: input.runnerId, container: input.container } satisfies GitHubRunner);
7678 await this.startRunner({ DIFFINERY_GITHUB_JIT_CONFIG: input.jitConfig, DIFFINERY_RUNNER_VCPU: String(input.vcpu), ...(await this.useEgress(input.egress)) });
7779 }
7880
7981 private async startRunner(envVars: Record<string, string>): Promise<void> {
80- await this.start(
81- { envVars },
82- // The library gives up after 8 s and reports "no container instance", but a container on a host
83- // that hasn't pulled the runner image yet takes longer than that to come up: such jobs went back
84- // in line for 30 to 90 s more (measured on 10-leg matrices). Wait for it instead.
85- // The runner listens on no port: the library's own fallback port (33) answers "not listening" once it is up.
86- // Each check can itself take up to 5 s, so the signal bounds the whole wait.
87- { portToCheck: 33, waitInterval: START_POLL_MS, retries: Math.ceil(START_WAIT_MS / START_POLL_MS), signal: AbortSignal.timeout(START_WAIT_MS + 60_000) },
88- );
82+ this.starting = true;
83+ try {
84+ await this.start(
85+ { envVars },
86+ // The library gives up after 8 s and reports "no container instance", but a container on a host
87+ // that hasn't pulled the runner image yet takes longer than that to come up: such jobs went back
88+ // in line for 30 to 90 s more (measured on 10-leg matrices). Wait for it instead.
89+ // The runner listens on no port: the library's own fallback port (33) answers "not listening" once it is up.
90+ // Each check can itself take up to 5 s, so the signal bounds the whole wait.
91+ { portToCheck: 33, waitInterval: START_POLL_MS, retries: Math.ceil(START_WAIT_MS / START_POLL_MS), signal: AbortSignal.timeout(START_WAIT_MS + 60_000) },
92+ );
93+ } finally {
94+ this.starting = false;
95+ }
8996 }
9097
9198 /**
@@ -106,8 +113,13 @@
106113 override async onStop(params: StopParams): Promise<void> {
107114 const gh = await this.ctx.storage.get<GitHubRunner>("github");
108115 if (gh) {
116+ // While a start the platform had no machine for is tried again, the library's alarm reports the container
117+ // stopped with exit code 0, though nothing ran and the start goes on. Told so, Diffinery removed the runner
118+ // from GitHub and its job waited 24 hours for another (2 or 3 jobs of 10 started at once). The start ends in
119+ // a running runner, or in an error that github-runners/service.ts place() handles.
120+ if (this.starting) return;
109121 const ns = this.env.GITHUB_RUNNERS;
110- if (ns) await ns.get(ns.idFromName(gh.accountId)).stopped(gh.accountId, gh.runnerId, params.exitCode ?? null);
122+ if (ns) await ns.get(ns.idFromName(gh.accountId)).stopped(gh.accountId, gh.runnerId, params.exitCode ?? null, gh.container);
111123 await this.ctx.storage.delete("github");
112124 return;
113125 }
modifiedapps/diffinery/test/unit/github-runners.test.ts+110−1View file
@@ -41,6 +41,7 @@
4141 const gh = {
4242 fail: null as Error | null,
4343 busy: false as boolean | null,
44+ jobState: "queued" as string | Error | null,
4445 async jitRunner(installationId: number, repo: string, name: string, labels: string[]) {
4546 calls.push({ op: "jit", args: [installationId, repo, name, labels] });
4647 if (gh.fail) throw gh.fail;
@@ -53,6 +54,11 @@
5354 async removeRunner(installationId: number, repo: string, runnerId: number) {
5455 calls.push({ op: "remove", args: [installationId, repo, runnerId] });
5556 },
57+ async jobStatus(installationId: number, repo: string, jobId: number) {
58+ calls.push({ op: "job", args: [installationId, repo, jobId] });
59+ if (gh.jobState instanceof Error) throw gh.jobState;
60+ return gh.jobState;
61+ },
5662 };
5763 return { gh, calls, client: gh as unknown as GitHubAppClient };
5864 }
@@ -187,7 +193,7 @@
187193 await w.svc.queued("ann", job(1), "large");
188194 await w.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "completed", runnerName: null, jobName: "test 1", conclusion: "cancelled" });
189195 expect(w.rows()[0]).toMatchObject({ status: "skipped", conclusion: "cancelled", message: "The job ended before a runner started for it" });
190- // Another Diffinery runner, started for another job with the same labels, took it.
196+ // A Diffinery runner this account didn't start (another instance's, say) took it.
191197 await w.svc.queued("ann", job(2), "large");
192198 await w.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: "diffinery-other-1", jobName: "test 2", conclusion: null });
193199 expect(w.rows()[1]).toMatchObject({ status: "skipped", message: "The job ran on diffinery-other-1 before a runner started for it" });
@@ -203,6 +209,68 @@
203209 expect(v.rows()[1]).toMatchObject({ status: "skipped", message: "The GitHub installation is no longer linked to this account" });
204210 });
205211
212+ it("still start a runner for a job when the runner started for it took another queued job", async () => {
213+ const w = world();
214+ const byJob = (id: number) => w.rows().find((r) => r.github_job_id === id)!;
215+ await w.svc.queued("ann", job(1, ["diffinery-small", "diffinery-medium"]), "medium");
216+ await w.svc.pump("ann");
217+ const first = w.rows()[0]!;
218+ // Job 2 is queued after job 1, and GitHub hands it to job 1's runner before a runner starts for it.
219+ w.clock.advance(1000);
220+ await w.svc.queued("ann", job(2, ["diffinery-small"]), "small");
221+ const queued2 = byJob(2).created_at;
222+ await w.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: first.runner_name, jobName: "test 2", conclusion: null });
223+ // The rows trade jobs: the runner's row shows the job it runs, the other waits for job 1 in job 1's place in line.
224+ expect(byJob(2)).toMatchObject({ id: first.id, status: "running", job_name: "test 2", html_url: job(2).htmlUrl, labels: '["diffinery-small"]', size: "medium", created_at: queued2, ran_job_id: 2, container: first.container });
225+ expect(byJob(1)).toMatchObject({ status: "queued", job_name: "test 1", html_url: job(1).htmlUrl, labels: '["diffinery-small","diffinery-medium"]', size: "medium", created_at: first.created_at, runner_name: null, ran_job_id: null });
226+ const waiting = byJob(1);
227+
228+ await w.svc.pump("ann");
229+ expect(byJob(1)).toMatchObject({ id: waiting.id, status: "starting", runner_name: `diffinery-${waiting.id}-1`, container: `gh-${waiting.id}-1.medium` });
230+ expect(w.calls.filter((c) => c.op === "jit").map((c) => c.args[3])).toEqual([
231+ ["diffinery-small", "diffinery-medium"],
232+ ["diffinery-small", "diffinery-medium"],
233+ ]);
234+ expect(w.compute().map((c) => [c.id, c.ended_at])).toEqual([
235+ [first.container, null],
236+ [`gh-${waiting.id}-1.medium`, null],
237+ ]);
238+ // Each runner's row ends with its own container.
239+ await w.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "completed", runnerName: first.runner_name, jobName: "test 2", conclusion: "success" });
240+ await w.svc.stopped(first.id, 0);
241+ expect(byJob(2)).toMatchObject({ status: "completed", conclusion: "success", exit_code: 0 });
242+ expect(byJob(1)).toMatchObject({ status: "starting" });
243+ expect(w.compute().map((c) => c.ended_at === null)).toEqual([false, true]);
244+
245+ // Job 1 cancelled while its row waits: the row is skipped and no runner starts for it.
246+ const v = world();
247+ await v.svc.queued("ann", job(1), "large");
248+ await v.svc.pump("ann");
249+ const runner = v.rows()[0]!.runner_name;
250+ await v.svc.queued("ann", job(2), "large");
251+ await v.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: runner, jobName: "test 2", conclusion: null });
252+ await v.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "completed", runnerName: null, jobName: "test 1", conclusion: "cancelled" });
253+ expect(v.rows().map((r) => [r.github_job_id, r.status, r.message])).toEqual([
254+ [1, "skipped", "The job ended before a runner started for it"],
255+ [2, "running", null],
256+ ]);
257+ await v.svc.pump("ann");
258+ expect(v.started).toHaveLength(1);
259+
260+ // A job whose own runner already started keeps it: GitHub hands that runner the job the other was started for.
261+ const u = world();
262+ await u.svc.queued("ann", job(1), "large");
263+ await u.svc.queued("ann", job(2), "large");
264+ await u.svc.pump("ann");
265+ const [r1, r2] = u.rows();
266+ await u.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: r1!.runner_name, jobName: "test 2", conclusion: null });
267+ await u.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "in_progress", runnerName: r2!.runner_name, jobName: "test 1", conclusion: null });
268+ expect(u.rows().map((r) => [r.id, r.github_job_id, r.status, r.ran_job_id])).toEqual([
269+ [r1!.id, 1, "running", 2],
270+ [r2!.id, 2, "running", 1],
271+ ]);
272+ });
273+
206274 it("run a size this Diffinery doesn't have on a large runner", async () => {
207275 const w = world({}, ["large"]);
208276 await w.svc.queued("ann", job(1, ["diffinery-tiny"]), "tiny");
@@ -257,6 +325,47 @@
257325 expect(w.started.map((s) => s.container)).toEqual([1, 2, 3].map((n) => `gh-${w.rows()[0]!.id}-${n}`));
258326 });
259327
328+ it("replace a runner whose container stopped before it took a job while GitHub still has the job queued", async () => {
329+ const w = world();
330+ await w.svc.queued("ann", job(1), "large");
331+ await w.svc.pump("ann");
332+ const first = w.rows()[0]!;
333+ // The library reports exit code 0 for a container the platform lost: the job still waits on GitHub.
334+ await w.svc.stopped(first.id, 0, first.container!);
335+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: 1, container: null, message: "The runner's container stopped before it took a job; starting another" });
336+ expect(w.calls.filter((c) => c.op === "job" || c.op === "remove")).toEqual([
337+ { op: "job", args: [11, "ann-gh/app", 1] },
338+ { op: "remove", args: [11, "ann-gh/app", 501] },
339+ ]);
340+ expect(w.compute()[0]!.ended_at).not.toBeNull();
341+ // The lost container's stop again, late: the row no longer runs in it.
342+ await w.svc.stopped(first.id, 0, first.container!);
343+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: 1 });
344+
345+ // GitHub doesn't answer: the job counts as queued. Without an exit code it is the same.
346+ await w.svc.pump("ann");
347+ w.gh.jobState = new GitHubApiError(502, "bad gateway");
348+ await w.svc.stopped(first.id, null, w.rows()[0]!.container!);
349+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: 2 });
350+
351+ // The job ran on another runner or was cancelled meanwhile: the row ends.
352+ await w.svc.pump("ann");
353+ w.gh.jobState = "completed";
354+ await w.svc.stopped(first.id, 0, w.rows()[0]!.container!);
355+ expect(w.rows()[0]).toMatchObject({ status: "completed", tries: 3, exit_code: 0, message: null });
356+ expect(w.started.map((s) => s.container)).toEqual([1, 2, 3].map((n) => `gh-${first.id}-${n}`));
357+
358+ // A runner that took its job and stopped isn't asked about.
359+ const v = world();
360+ await v.svc.queued("ann", job(1), "large");
361+ await v.svc.pump("ann");
362+ const row = v.rows()[0]!;
363+ await v.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "in_progress", runnerName: row.runner_name, jobName: "test 1", conclusion: null });
364+ await v.svc.stopped(row.id, 0, row.container!);
365+ expect(v.rows()[0]).toMatchObject({ status: "completed", exit_code: 0 });
366+ expect(v.calls.filter((c) => c.op === "job")).toEqual([]);
367+ });
368+
260369 it("stop a runner no job took within the idle time, unless GitHub says it is busy", async () => {
261370 const w = world();
262371 await w.svc.queued("ann", job(1), "large");
addedapps/diffinery/test/unit/runner-containers.test.ts+60−0View file
@@ -1,0 +1,60 @@
1+import { describe, expect, it, vi } from "vitest";
2+import type { Env } from "../../src/env.js";
3+
4+// The containers library's Container, with a start() each test gives: the real one needs the Workers runtime.
5+const lib = vi.hoisted(() => ({ start: async (_self: { onStop(p: { exitCode?: number; reason: string }): Promise<void> }): Promise<void> => {} }));
6+vi.mock("@cloudflare/containers", () => ({
7+ Container: class {
8+ constructor(
9+ protected ctx: unknown,
10+ protected env: unknown,
11+ ) {}
12+ async start(): Promise<void> {
13+ await lib.start(this as never);
14+ }
15+ async setAllowedHosts(): Promise<void> {}
16+ },
17+}));
18+
19+const { RunnerContainer } = await import("../../src/runner/containers.js");
20+
21+function runner() {
22+ const kept = new Map<string, unknown>();
23+ const ctx = {
24+ storage: {
25+ kv: { get: () => undefined, put: () => {} },
26+ put: async (k: string, v: unknown) => void kept.set(k, v),
27+ get: async (k: string) => kept.get(k),
28+ delete: async (k: string) => kept.delete(k),
29+ },
30+ };
31+ const stops: unknown[][] = [];
32+ const env = { GITHUB_RUNNERS: { idFromName: (n: string) => n, get: () => ({ stopped: async (...a: unknown[]) => void stops.push(a) }) } };
33+ return { c: new RunnerContainer(ctx as never, env as unknown as Env), stops, kept };
34+}
35+
36+const input = { accountId: "ann", runnerId: "row1", container: "gh-row1-1", jitConfig: "jit", egress: "open" as const, vcpu: 4 };
37+
38+describe("a GitHub runner's container", () => {
39+ it("isn't reported stopped while its start is still under way", async () => {
40+ const { c, stops } = runner();
41+ // The platform had no machine for the first try: the library's alarm reports the container stopped with
42+ // exit code 0 while start() tries again, and the second try starts it.
43+ lib.start = async (self) => self.onStop({ exitCode: 0, reason: "exit" });
44+ await c.startGitHubRunner(input);
45+ expect(stops).toEqual([]);
46+ // Its real stop, after the job, with the container that stopped.
47+ await c.onStop({ exitCode: 0, reason: "exit" });
48+ expect(stops).toEqual([["ann", "row1", 0, "gh-row1-1"]]);
49+ });
50+
51+ it("is reported stopped after a start that failed", async () => {
52+ const { c, stops } = runner();
53+ lib.start = async () => {
54+ throw new Error("there is no container instance that can be provided to this durable object");
55+ };
56+ await expect(c.startGitHubRunner(input)).rejects.toThrow(/no container instance/);
57+ await c.onStop({ exitCode: 1, reason: "exit" });
58+ expect(stops).toEqual([["ann", "row1", 1, "gh-row1-1"]]);
59+ });
60+});