diff --git a/workers/nos-runner-watchdog/src/github.js b/workers/nos-runner-watchdog/src/github.js index 2985f9c..5bfc702 100644 --- a/workers/nos-runner-watchdog/src/github.js +++ b/workers/nos-runner-watchdog/src/github.js @@ -166,6 +166,22 @@ export async function listRuns(token, repo, status, fetchFn) { })); } +/** Failed runs created since sinceIso, newest first, with the run fields lostCandidate() reads. */ +export async function listFailedRuns(token, repo, sinceIso, fetchFn) { + const since = sinceIso.replace(/\.\d{3}Z$/, "Z"); + const path = `/repos/${repo}/actions/runs?status=failure&created=>=${since}&per_page=20&exclude_pull_requests=true`; + const out = await call(token, "GET", path, "runs failure", fetchFn); + return (out.workflow_runs ?? []).map((r) => ({ + id: r.id, + // No default: a run without run_attempt is never re-run. + run_attempt: r.run_attempt, + conclusion: r.conclusion, + head_repository: { full_name: r.head_repository?.full_name ?? null }, + repository: { full_name: r.repository?.full_name ?? null }, + actor: { login: r.actor?.login ?? null }, + })); +} + export async function getJobs(token, repo, runId, fetchFn) { const out = await call( token, diff --git a/workers/nos-runner-watchdog/src/index.js b/workers/nos-runner-watchdog/src/index.js index f2deb49..8c94680 100644 --- a/workers/nos-runner-watchdog/src/index.js +++ b/workers/nos-runner-watchdog/src/index.js @@ -1,6 +1,12 @@ import { decide } from "./decide.js"; import * as gh from "./github.js"; import { APPS, POOLS, poolForCron, appEnv } from "./pools.js"; +import { + LOST_WINDOW_MS, + lostCandidate, + lostRunner, + pruneChecked, +} from "./lost.js"; // Free plan allows 50 subrequests a run; KV calls are counted too, for headroom. export const CAP = 40; @@ -17,6 +23,12 @@ const TOKEN_TTL = 3000; const SKIP_ALERT = 3; // Sends per alert. A tick sends at most two alerts, so retries fit in the CAP headroom. const NTFY_TRIES = 3; +// Lost-runner phase, per probe: the jobs GET, the lostChecked put, the rerun POST, and the last lostChecked put. +const PROBE_COST = 4; +// Left free by the scan on a rerunLost pool: the lostChecked get, one failed-runs list, one probe. +const LOST_SHARE = 1 + 1 + PROBE_COST; +// lostChecked also holds the lost-phase repo cursor under this key; a "#" key can never equal it. +const CURSOR_KEY = "_cursor"; // Logs name the failed call and status only, never a URL, token or topic. const describe = (e) => @@ -148,7 +160,10 @@ export async function runTick(env, { fetch: rawFetch, now, pool = POOLS.nos }) { prev.lastVar === null || (prev.misses ?? 0) >= 1; const scanReserve = - RESERVE_REQUIRED + (skips ? 2 : 0) + (sweepLikely ? OPTIONAL_SHARE : 0); + RESERVE_REQUIRED + + (skips ? 2 : 0) + + (sweepLikely ? OPTIONAL_SHARE : 0) + + (pool.rerunLost ? LOST_SHARE : 0); let observed; let scan; let repoOldest; @@ -320,6 +335,69 @@ export async function runTick(env, { fetch: rawFetch, now, pool = POOLS.nos }) { for (const p of planned) { await optional((t) => gh.cancelRun(t, p.repo, p.runId, fetchFn), 0); } + + // Lost runners, after the cancels so the sweep keeps its budget. NOS has no rerunLost, so its tick ends above. + if (!pool.rerunLost || scan.all.length === 0) return; + if (stopped || !budget.canAfford(LOST_SHARE)) return; + const loaded = parseOr(await kv.get("lostChecked"), {}, "lostChecked"); + const { [CURSOR_KEY]: savedCursor, ...entries } = loaded ?? {}; + const lostChecked = pruneChecked(entries, now); + let dirty = Object.keys(lostChecked).length !== Object.keys(entries).length; + const sinceIso = new Date(now - LOST_WINDOW_MS).toISOString(); + // Runs the pending list re-runs (a down-sweep run can fail first) are left to it, so no run gets two re-runs. + const pendingKeys = new Set([...pending, ...toWrite].map(runKey)); + // Own cursor: the next tick starts after the last repo listed. Mod n, so a changed repo count is safe. + const n = scan.all.length; + const prevCursor = Number.isInteger(savedCursor) ? savedCursor : 0; + const start = ((prevCursor % n) + n) % n; + let cursor = start; + const save = () => + kv.put( + "lostChecked", + JSON.stringify({ ...lostChecked, [CURSOR_KEY]: cursor }), + ); + let out = false; + for (let i = 0; i < n && !out; i += 1) { + const repo = scan.all[(start + i) % n]; + const list = await optional( + (t) => gh.listFailedRuns(t, repo, sinceIso, fetchFn), + PROBE_COST, + ); + if (list.skipped) break; + // Listed (or failed): the next tick starts after this repo, even if its probes are cut short. + cursor = (start + i + 1) % n; + if (!list.ok) continue; + for (const run of list.value) { + const k = `${repo}#${run.id}`; + if (k in lostChecked || pendingKeys.has(k) || !lostCandidate(run)) + continue; + const jobs = await optional( + (t) => gh.getJobs(t, repo, run.id, fetchFn), + PROBE_COST - 1, + ); + if (jobs.skipped) { + out = true; + break; + } + // A failed jobs GET is not marked, so a later tick probes the run again. + if (!jobs.ok) continue; + lostChecked[k] = now; + dirty = true; + if (!lostRunner(run, jobs.value, pool)) continue; + // Marked before the POST: a crash after it can never re-run the run twice. + await save(); + dirty = false; + const rr = await optional( + (t) => gh.rerunFailed(t, repo, run.id, fetchFn), + RESERVE_FINAL, + ); + // No alert (plan decision 9): re-runs after a restart are routine. + log( + rr.ok ? `lost runner re-run: ${k}` : `lost runner re-run failed: ${k}`, + ); + } + } + if ((dirty || cursor !== prevCursor) && budget.canAfford(1)) await save(); } // A run we cancelled is re-run; a failure only when the down sweep cancelled it (a hung job can fail first). diff --git a/workers/nos-runner-watchdog/src/lost.js b/workers/nos-runner-watchdog/src/lost.js new file mode 100644 index 0000000..25409f6 --- /dev/null +++ b/workers/nos-runner-watchdog/src/lost.js @@ -0,0 +1,35 @@ +// Lost runner: a restart stopped the job. It failed, no step did. A hypothesis until the restart drill. + +// Failed runs are listed from this far back, and lostChecked entries are kept this long. +export const LOST_WINDOW_MS = 6 * 3600000; + +/** Run-level checks only: a first attempt that failed, from this repo, not from Dependabot. Read from the runs list. */ +export function lostCandidate(run) { + return ( + run?.run_attempt === 1 && + run.conclusion === "failure" && + typeof run.repository?.full_name === "string" && + run.head_repository?.full_name === run.repository.full_name && + run.actor?.login !== "dependabot[bot]" + ); +} + +/** True when the run is a candidate and one of its pool-label jobs failed with no failed step. */ +export function lostRunner(run, jobs, pool) { + if (!lostCandidate(run)) return false; + return (jobs ?? []).some( + (j) => + (j.labels ?? []).includes(pool.label) && + j.conclusion === "failure" && + !(j.steps ?? []).some((s) => s.conclusion === "failure"), + ); +} + +/** lostChecked without entries older than the window. */ +export function pruneChecked(checked, now) { + const out = {}; + for (const [k, t] of Object.entries(checked ?? {})) { + if (typeof t === "number" && now - t <= LOST_WINDOW_MS) out[k] = t; + } + return out; +} diff --git a/workers/nos-runner-watchdog/test/fixtures/fork-guard-denial.json b/workers/nos-runner-watchdog/test/fixtures/fork-guard-denial.json new file mode 100644 index 0000000..7cc8752 --- /dev/null +++ b/workers/nos-runner-watchdog/test/fixtures/fork-guard-denial.json @@ -0,0 +1,65 @@ +{ + "source": "GET /repos/smartwatermelon/dotfiles/actions/runs/44443375980 and /jobs, captured 2026-11-23, redacted to the fields the predicate reads", + "note": "dotfiles#511 fork-PR drill, Bash Tests: the fork guard refused the job in Set up runner.", + "run": { + "actor": { + "login": "smartwatermelon-agent[bot]" + }, + "conclusion": "failure", + "event": "pull_request", + "head_repository": { + "full_name": "nightowlstudiollc/dotfiles" + }, + "id": 44443375980, + "repository": { + "full_name": "smartwatermelon/dotfiles" + }, + "run_attempt": 1 + }, + "jobs": [ + { + "conclusion": "failure", + "labels": ["mimolette-macos"], + "runner_name": "mimolette-macos-1795054747", + "status": "completed", + "steps": [ + { + "conclusion": "success", + "name": "Set up job" + }, + { + "conclusion": "failure", + "name": "Set up runner" + }, + { + "conclusion": "skipped", + "name": "Checkout" + }, + { + "conclusion": "skipped", + "name": "Install bash 5" + }, + { + "conclusion": "skipped", + "name": "Install linters the lint tests exercise" + }, + { + "conclusion": "skipped", + "name": "Clone github-workflows for the upstream config comparison" + }, + { + "conclusion": "skipped", + "name": "Show bash version" + }, + { + "conclusion": "skipped", + "name": "Run bash test suite" + }, + { + "conclusion": "success", + "name": "Complete job" + } + ] + } + ] +} diff --git a/workers/nos-runner-watchdog/test/fixtures/hypothesis-runner-lost.json b/workers/nos-runner-watchdog/test/fixtures/hypothesis-runner-lost.json new file mode 100644 index 0000000..0c0619a --- /dev/null +++ b/workers/nos-runner-watchdog/test/fixtures/hypothesis-runner-lost.json @@ -0,0 +1,45 @@ +{ + "source": "HYPOTHESIS, not captured. Written 2026-11-23 from the plan (decision 8): no real runner-lost job exists yet. The batch's restart drill (step F) replaces this file with a captured one.", + "note": "Assumed shape: a same-repo push run whose mimolette-macos job stopped when the runner restarted. The job is failure, but no step is failure: the interrupted step and the later ones have no failure conclusion.", + "run": { + "actor": { + "login": "smartwatermelon" + }, + "conclusion": "failure", + "event": "push", + "head_repository": { + "full_name": "smartwatermelon/dotfiles" + }, + "id": 90000000001, + "repository": { + "full_name": "smartwatermelon/dotfiles" + }, + "run_attempt": 1 + }, + "jobs": [ + { + "conclusion": "failure", + "labels": ["mimolette-macos"], + "runner_name": "mimolette-macos-1795099999", + "status": "completed", + "steps": [ + { + "conclusion": "success", + "name": "Set up job" + }, + { + "conclusion": "success", + "name": "Set up runner" + }, + { + "conclusion": "success", + "name": "Checkout" + }, + { + "conclusion": null, + "name": "Run bash test suite" + } + ] + } + ] +} diff --git a/workers/nos-runner-watchdog/test/fixtures/real-test-failure.json b/workers/nos-runner-watchdog/test/fixtures/real-test-failure.json new file mode 100644 index 0000000..8d7936d --- /dev/null +++ b/workers/nos-runner-watchdog/test/fixtures/real-test-failure.json @@ -0,0 +1,57 @@ +{ + "source": "GET /repos/smartwatermelon/mac-server-setup/actions/runs/44651519680 and /jobs, captured 2026-11-23, redacted to the fields the predicate reads", + "note": "A real test failure (Run BATS failed). No failed-step job on mimolette-macos exists yet; this one ran on macos-latest.", + "run": { + "actor": { + "login": "smartwatermelon-agent[bot]" + }, + "conclusion": "failure", + "event": "pull_request", + "head_repository": { + "full_name": "smartwatermelon/mac-server-setup" + }, + "id": 44651519680, + "repository": { + "full_name": "smartwatermelon/mac-server-setup" + }, + "run_attempt": 1 + }, + "jobs": [ + { + "conclusion": "failure", + "labels": ["macos-latest"], + "runner_name": "GitHub Actions 1000012195", + "status": "completed", + "steps": [ + { + "conclusion": "success", + "name": "Set up job" + }, + { + "conclusion": "success", + "name": "Run actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1" + }, + { + "conclusion": "success", + "name": "Install test dependencies" + }, + { + "conclusion": "success", + "name": "Show tool versions" + }, + { + "conclusion": "failure", + "name": "Run BATS" + }, + { + "conclusion": "success", + "name": "Post Run actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1" + }, + { + "conclusion": "success", + "name": "Complete job" + } + ] + } + ] +} diff --git a/workers/nos-runner-watchdog/test/fixtures/user-cancelled.json b/workers/nos-runner-watchdog/test/fixtures/user-cancelled.json new file mode 100644 index 0000000..abbfacb --- /dev/null +++ b/workers/nos-runner-watchdog/test/fixtures/user-cancelled.json @@ -0,0 +1,69 @@ +{ + "source": "GET /repos/smartwatermelon/dotfiles/actions/runs/44395263750 and /jobs, captured 2026-11-23, redacted to the fields the predicate reads", + "note": "Cancelled by smartwatermelon-agent[bot] during Run bash test suite, not by a runner restart.", + "run": { + "actor": { + "login": "smartwatermelon-agent[bot]" + }, + "conclusion": "cancelled", + "event": "pull_request", + "head_repository": { + "full_name": "smartwatermelon/dotfiles" + }, + "id": 44395263750, + "repository": { + "full_name": "smartwatermelon/dotfiles" + }, + "run_attempt": 1 + }, + "jobs": [ + { + "conclusion": "cancelled", + "labels": ["mimolette-macos"], + "runner_name": "mimolette-macos-1795034845", + "status": "completed", + "steps": [ + { + "conclusion": "success", + "name": "Set up job" + }, + { + "conclusion": "success", + "name": "Set up runner" + }, + { + "conclusion": "success", + "name": "Checkout" + }, + { + "conclusion": "success", + "name": "Install bash 5" + }, + { + "conclusion": "success", + "name": "Install linters the lint tests exercise" + }, + { + "conclusion": "success", + "name": "Clone github-workflows for the upstream config comparison" + }, + { + "conclusion": "success", + "name": "Show bash version" + }, + { + "conclusion": "cancelled", + "name": "Run bash test suite" + }, + { + "conclusion": "success", + "name": "Post Checkout" + }, + { + "conclusion": "success", + "name": "Complete job" + } + ] + } + ] +} diff --git a/workers/nos-runner-watchdog/test/lost.test.js b/workers/nos-runner-watchdog/test/lost.test.js new file mode 100644 index 0000000..9ae7130 --- /dev/null +++ b/workers/nos-runner-watchdog/test/lost.test.js @@ -0,0 +1,436 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { NOW, fakeKV } from "./fakes.js"; +import { + worldFor, + setupFor, + st, + keyOf, + repoUrlFor, + failedUrlFor, + subrequests, +} from "./pool-world.js"; +import { CAP } from "../src/index.js"; +import { POOLS } from "../src/pools.js"; +import { lostRunner } from "../src/lost.js"; + +const MAC = POOLS.swmMacos; +const NOS = POOLS.nos; +const HOUR = 3600000; + +// Fixtures: three captured from the GitHub API (source field says which run), one hypothesis. +const load = (name) => + JSON.parse(readFileSync(new URL(`./fixtures/${name}`, import.meta.url))); +const fixture = { + hypothesis: load("hypothesis-runner-lost.json"), + forkGuard: load("fork-guard-denial.json"), + realFailure: load("real-test-failure.json"), + cancelled: load("user-cancelled.json"), +}; +const clone = (x) => structuredClone(x); +// The hypothesis fixture with one field changed, so each test fails for its own clause only. +const mutate = (fn) => { + const f = clone(fixture.hypothesis); + fn(f); + return f; +}; +// A fixture moved into another repo of the world, under a new run id. +const asRun = (f, repo, id) => { + const x = clone(f); + x.run.id = id; + x.run.repository.full_name = `smartwatermelon/${repo}`; + if (f.run.head_repository.full_name === f.run.repository.full_name) { + x.run.head_repository.full_name = `smartwatermelon/${repo}`; + } + return x; +}; + +const rerunKey = (repo, id) => + `POST ${repoUrlFor(MAC, repo)}/${id}/rerun-failed-jobs`; +const jobsKey = (repo, id) => + `GET ${repoUrlFor(MAC, repo)}/${id}/jobs?per_page=100`; +const reruns = (s) => + s.f.calls.filter((c) => c.key.endsWith("/rerun-failed-jobs")); +const healthyKv = (over = {}) => ({ + [keyOf(MAC, "token")]: "ghs_swm", + [keyOf(MAC, "state")]: st(MAC), + ...over, +}); +// lostChecked entries without the repo cursor it also holds. +const checked = (s) => { + const all = JSON.parse(s.store.map.get(keyOf(MAC, "lostChecked")) ?? "{}"); + delete all._cursor; + return all; +}; + +async function tickWith(failed, kv = healthyKv(), now = NOW, store = null) { + const s = setupFor(MAC, worldFor(MAC, { failed, now }), kv, {}, store); + await s.tick(now); + assert.deepEqual(s.f.unexpected, []); + return s; +} + +test("lost_runner_job_is_rerun", async () => { + const h = fixture.hypothesis; + assert.equal(lostRunner(h.run, h.jobs, MAC), true); + const s = await tickWith({ dotfiles: [h] }); + assert.deepEqual( + reruns(s).map((c) => c.key), + [rerunKey("dotfiles", h.run.id)], + ); + assert.equal( + typeof checked(s)[`smartwatermelon/dotfiles#${h.run.id}`], + "number", + ); +}); + +test("lost_fork_guard_denial_not_rerun", async () => { + const f = fixture.forkGuard; + assert.equal(lostRunner(f.run, f.jobs, MAC), false); + // Derived, not captured: the same jobs on a same-repo run. The failed "Set up runner" step alone must refuse it. + const sameRepo = clone(f); + sameRepo.run.head_repository.full_name = sameRepo.run.repository.full_name; + assert.equal(lostRunner(sameRepo.run, sameRepo.jobs, MAC), false); + const s = await tickWith({ dotfiles: [f, asRun(sameRepo, "dotfiles", 7)] }); + assert.equal(reruns(s).length, 0); +}); + +test("lost_real_failure_not_rerun", async () => { + const f = fixture.realFailure; + assert.equal(lostRunner(f.run, f.jobs, MAC), false); + // Derived, not captured: the same failed-step job relabelled to the pool label. The failed step alone must refuse it. + const relabelled = clone(f); + for (const j of relabelled.jobs) j.labels = [MAC.label]; + assert.equal(lostRunner(relabelled.run, relabelled.jobs, MAC), false); + const s = await tickWith({ + "mac-server-setup": [f, asRun(relabelled, "mac-server-setup", 8)], + }); + assert.equal(reruns(s).length, 0); +}); + +test("lost_cancelled_run_not_rerun", async () => { + const f = fixture.cancelled; + assert.equal(lostRunner(f.run, f.jobs, MAC), false); + // Derived: a cancelled run is refused by the run conclusion, even with the hypothesis jobs. + assert.equal(lostRunner(f.run, fixture.hypothesis.jobs, MAC), false); + const s = await tickWith({ dotfiles: [f] }); + assert.equal(reruns(s).length, 0); +}); + +test("lost_fork_run_not_rerun", () => { + const f = mutate((x) => { + x.run.head_repository.full_name = "someone/dotfiles"; + }); + assert.equal(lostRunner(f.run, f.jobs, MAC), false); + // A deleted fork head has no head_repository: refused. + const gone = mutate((x) => { + x.run.head_repository = null; + }); + assert.equal(lostRunner(gone.run, gone.jobs, MAC), false); +}); + +test("lost_dependabot_run_not_rerun", () => { + const f = mutate((x) => { + x.run.actor.login = "dependabot[bot]"; + }); + assert.equal(lostRunner(f.run, f.jobs, MAC), false); +}); + +test("lost_attempt_2_not_rerun", async () => { + const f = mutate((x) => { + x.run.run_attempt = 2; + }); + assert.equal(lostRunner(f.run, f.jobs, MAC), false); + const s = await tickWith({ dotfiles: [f] }); + assert.equal(reruns(s).length, 0); +}); + +test("lost_other_label_not_rerun", () => { + const f = mutate((x) => { + x.jobs[0].labels = ["macos-latest"]; + }); + assert.equal(lostRunner(f.run, f.jobs, MAC), false); + // The NOS label is another label too. + const nos = mutate((x) => { + x.jobs[0].labels = [NOS.label]; + }); + assert.equal(lostRunner(nos.run, nos.jobs, MAC), false); +}); + +test("lost_job_conclusion_must_be_failure", () => { + for (const c of ["success", "cancelled", "skipped", null]) { + const f = mutate((x) => { + x.jobs[0].conclusion = c; + }); + assert.equal(lostRunner(f.run, f.jobs, MAC), false, String(c)); + } + const run = mutate((x) => { + x.run.conclusion = "success"; + }); + assert.equal(lostRunner(run.run, run.jobs, MAC), false); + assert.equal(lostRunner(fixture.hypothesis.run, [], MAC), false); +}); + +test("lost_nos_pool_never_scans", async () => { + const routes = worldFor(NOS, { repos: { a: [] } }); + const s = setupFor(NOS, routes, { token: "ghs_nos", state: st(NOS) }); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + assert.ok(s.f.calls.length > 0); + for (const c of s.f.calls) { + assert.ok(!c.url.includes("status=failure"), c.key); + assert.ok(!c.url.includes("rerun-failed-jobs"), c.key); + } + for (const op of s.store.ops) assert.ok(!op.includes("lostChecked"), op); +}); + +test("lost_checked_written_before_rerun", async () => { + const h = fixture.hypothesis; + const s = setupFor( + MAC, + worldFor(MAC, { failed: { dotfiles: [h] } }), + healthyKv(), + ); + const seq = []; + const put = s.store.put.bind(s.store); + s.store.put = (k, v, o) => { + seq.push(`kv put ${k}`); + return put(k, v, o); + }; + const fetchFn = s.f.fn; + const { runTick } = await import("../src/index.js"); + await runTick(s.env, { + fetch: (url, init = {}) => { + seq.push(`${(init.method || "GET").toUpperCase()} ${url}`); + return fetchFn(url, init); + }, + now: NOW, + pool: MAC, + }); + assert.deepEqual(s.f.unexpected, []); + const putAt = seq.indexOf("kv put swm-macos:lostChecked"); + const rerunAt = seq.indexOf(rerunKey("dotfiles", h.run.id)); + assert.ok(putAt >= 0, "lostChecked put"); + assert.ok(rerunAt >= 0, "rerun POST"); + assert.ok(putAt < rerunAt, seq.join("\n")); + // The put before the POST already holds the run. + const before = s.store.puts.find((p) => p.key === "swm-macos:lostChecked"); + assert.ok(`smartwatermelon/dotfiles#${h.run.id}` in JSON.parse(before.value)); +}); + +test("lost_run_probed_once", async () => { + const h = fixture.hypothesis; + const neg = asRun(fixture.realFailure, "dotfiles", 9); + const failed = { dotfiles: [h, neg] }; + const first = await tickWith(failed); + const second = await tickWith( + failed, + undefined, + NOW + 10 * 60000, + first.store, + ); + // Second tick: a fresh world at the later time, same store. + const probes = [...first.f.calls, ...second.f.calls].map((c) => c.key); + assert.equal( + probes.filter((k) => k === jobsKey("dotfiles", h.run.id)).length, + 1, + ); + assert.equal(probes.filter((k) => k === jobsKey("dotfiles", 9)).length, 1); + assert.equal( + probes.filter((k) => k === rerunKey("dotfiles", h.run.id)).length, + 1, + ); +}); + +test("lost_checked_pruned_after_6h", async () => { + const kv = healthyKv({ + [keyOf(MAC, "lostChecked")]: JSON.stringify({ + "smartwatermelon/old#1": NOW - 7 * HOUR, + "smartwatermelon/edge#2": NOW - 6 * HOUR - 1, + "smartwatermelon/recent#3": NOW - 1 * HOUR, + }), + }); + const s = await tickWith( + { dotfiles: [asRun(fixture.realFailure, "dotfiles", 4)] }, + kv, + ); + assert.deepEqual(Object.keys(checked(s)).sort(), [ + "smartwatermelon/dotfiles#4", + "smartwatermelon/recent#3", + ]); +}); + +// 25 repos with 5 failed runs each. Every run is lost-shaped, so each probe also wants a put and a re-run. +const manyFailed = () => { + const out = {}; + for (let r = 0; r < 25; r += 1) { + out[`r${r}`] = Array.from({ length: 5 }, (_, i) => + asRun(fixture.hypothesis, `r${r}`, 1000 + r * 10 + i), + ); + } + return out; +}; + +test("lost_budget_never_breaks_cap", async () => { + // Healthy pool, and a down tick (zero runners after one miss) that also sweeps. + for (const kv of [ + healthyKv(), + healthyKv({ [keyOf(MAC, "state")]: st(MAC, { misses: 1 }) }), + ]) { + const down = kv[keyOf(MAC, "state")].includes('"misses":1'); + const s = setupFor( + MAC, + worldFor(MAC, { + failed: manyFailed(), + ...(down && { + runners: [], + repos: { r0: [{ id: 1, age: 30 }], r1: [{ id: 2, age: 30 }] }, + }), + }), + kv, + ); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + assert.ok(subrequests(s) <= CAP, `subrequests ${subrequests(s)}`); + } +}); + +test("lost_idle_tick_reaches_rerun", async () => { + // The scan must leave room: with 25 repos an idle healthy tick still re-runs at least one lost run. + const s = await tickWith(manyFailed()); + assert.ok(reruns(s).length >= 1, `subrequests ${subrequests(s)}`); + assert.ok(subrequests(s) <= CAP, `subrequests ${subrequests(s)}`); + // Every re-run run is in lostChecked. + for (const c of reruns(s)) { + const id = c.url.split("/").at(-2); + const repo = c.url.split("/repos/")[1].split("/actions")[0]; + assert.equal(typeof checked(s)[`${repo}#${id}`], "number"); + } +}); + +test("lost_failed_url_shape", async () => { + // The list call asks GitHub for failed runs of the last 6 hours only. + const s = await tickWith({ dotfiles: [] }); + const call = s.f.calls.find((c) => c.url.includes("status=failure")); + assert.ok(call, "failed-runs list"); + assert.equal(call.key, failedUrlFor(MAC, "dotfiles")); + assert.match(call.url, /created=>=2026-11-10T06:00:00Z/); +}); + +test("lost_pending_run_left_to_pending", async () => { + // A down-sweep run that failed first is re-run by the pending list; the lost phase must not re-run it again. + const h = fixture.hypothesis; + const routes = worldFor(MAC, { + varValue: "macos-latest", + failed: { dotfiles: [h] }, + extra: { + [`GET ${repoUrlFor(MAC, "dotfiles")}/${h.run.id}`]: { + json: { status: "completed", conclusion: "failure", run_attempt: 1 }, + }, + }, + }); + const pending = [ + { + repo: "smartwatermelon/dotfiles", + runId: h.run.id, + down: true, + attempts: 0, + }, + ]; + const s = setupFor( + MAC, + routes, + healthyKv({ + [keyOf(MAC, "state")]: st(MAC, { lastVar: "macos-latest" }), + [keyOf(MAC, "pendingReruns")]: JSON.stringify(pending), + }), + ); + await s.tick(); + assert.deepEqual(s.f.unexpected, []); + assert.deepEqual( + reruns(s).map((c) => c.key), + [rerunKey("dotfiles", h.run.id)], + ); + assert.equal( + s.f.calls.filter((c) => c.key === jobsKey("dotfiles", h.run.id)).length, + 0, + ); +}); + +test("lost_any_repo_rerun_within_rotation", async () => { + // 34 repos, as smartwatermelon has. A lost run in any repo is re-run within ceil(34 / 4) = 9 ticks (90 min). + const n = 34; + const names = Array.from({ length: n }, (_, r) => `r${r}`); + for (let j = 0; j < n; j += 1) { + const run = asRun(fixture.hypothesis, `r${j}`, 5000 + j); + const failed = Object.fromEntries(names.map((r) => [r, []])); + failed[`r${j}`] = [run]; + const store = fakeKV(healthyKv()); + let ticks = 0; + let done = false; + while (!done && ticks < 40) { + const now = NOW + ticks * 10 * 60000; + const s = setupFor(MAC, worldFor(MAC, { failed, now }), {}, {}, store); + await s.tick(now); + assert.deepEqual(s.f.unexpected, []); + ticks += 1; + done = reruns(s).length > 0; + } + assert.ok(done && ticks <= 9, `repo r${j}: ${ticks} ticks`); + } +}); + +test("lost_cursor_reaches_every_repo_on_busy_ticks", async () => { + // 34 always-busy repos (20 new runs to probe): 1 list a tick. Every repo, odd ones too, is listed in 34 ticks. + const n = 34; + const names = Array.from({ length: n }, (_, r) => `r${r}`); + const busy = (t) => + Object.fromEntries( + names.map((r, i) => [ + r, + Array.from({ length: 20 }, (_, k) => + asRun(fixture.realFailure, r, 1e6 + t * 1e4 + i * 100 + k), + ), + ]), + ); + const store = fakeKV(healthyKv()); + const listed = new Set(); + const perTick = new Set(); + for (let t = 0; t < n; t += 1) { + const now = NOW + t * 10 * 60000; + const s = setupFor( + MAC, + worldFor(MAC, { failed: busy(t), now }), + {}, + {}, + store, + ); + const opsBefore = store.ops.length; + await s.tick(now); + assert.deepEqual(s.f.unexpected, []); + const used = s.f.calls.length + store.ops.length - opsBefore; + assert.ok(used <= CAP, `subrequests ${used}`); + const lists = s.f.calls + .filter((c) => c.url.includes("status=failure")) + .map((c) => c.url.split("/repos/smartwatermelon/")[1].split("/")[0]); + perTick.add(lists.length); + for (const r of lists) listed.add(r); + } + assert.ok(Math.max(...perTick) <= 2, `lists a tick: ${[...perTick]}`); + assert.deepEqual( + names.filter((r) => !listed.has(r)), + [], + ); +}); + +test("lost_cursor_past_repo_count_is_safe", async () => { + // The installation lost repos since the cursor was saved: start again inside the list. + const kv = healthyKv({ + [keyOf(MAC, "lostChecked")]: JSON.stringify({ _cursor: 99 }), + }); + const s = await tickWith({ dotfiles: [fixture.hypothesis] }, kv); + assert.equal(reruns(s).length, 1); + const saved = JSON.parse(s.store.map.get(keyOf(MAC, "lostChecked"))); + assert.equal(saved._cursor, 0); +}); diff --git a/workers/nos-runner-watchdog/test/pool-world.js b/workers/nos-runner-watchdog/test/pool-world.js index 0a14f80..05ccae9 100644 --- a/workers/nos-runner-watchdog/test/pool-world.js +++ b/workers/nos-runner-watchdog/test/pool-world.js @@ -33,7 +33,16 @@ export const jobFor = (pool, over = {}) => ({ ...over, }); +// The lost-runner phase lists failed runs from 6 hours before the tick. Built here, not imported, so a wrong URL fails. +export const failedUrlFor = (pool, r, now = NOW) => { + const since = new Date(now - 6 * 3600000) + .toISOString() + .replace(/\.\d{3}Z$/, "Z"); + return `GET ${repoUrlFor(pool, r)}?status=failure&created=>=${since}&per_page=20&exclude_pull_requests=true`; +}; + // Same shape as world(): repos/inProgress {name: [{id, age, jobs?, attempt?}]}; jobs default to one pool-label job. +// failed {name: [{run, jobs}]} are the failed runs a rerunLost pool lists; such a pool gets an empty list for every other repo. export function worldFor( pool, { @@ -41,11 +50,17 @@ export function worldFor( runners = [runnerFor(pool, "a", false), runnerFor(pool, "b", false)], repos = {}, inProgress = {}, + failed = {}, + now = NOW, extra = {}, } = {}, ) { const names = [ - ...new Set([...Object.keys(repos), ...Object.keys(inProgress)]), + ...new Set([ + ...Object.keys(repos), + ...Object.keys(inProgress), + ...Object.keys(failed), + ]), ]; const routes = { [runnersKey(pool)]: { json: { runners } }, @@ -89,6 +104,19 @@ export function worldFor( for (const r of names) { addRuns(r, repos[r] ?? [], "queued"); addRuns(r, inProgress[r] ?? [], "in_progress"); + if (!pool.rerunLost) continue; + const list = failed[r] ?? []; + routes[failedUrlFor(pool, r, now)] = { + json: { workflow_runs: list.map((x) => x.run) }, + }; + for (const x of list) { + routes[`GET ${repoUrlFor(pool, r)}/${x.run.id}/jobs?per_page=100`] = { + json: { jobs: x.jobs }, + }; + routes[`POST ${repoUrlFor(pool, r)}/${x.run.id}/rerun-failed-jobs`] = { + status: 201, + }; + } } return { ...routes, ...extra }; }