Files
fleet/scripts/ci/deploy-freshness-audit.mjs
CatoandClaude 46aaba39d2 ci: a commit's runs are read to the last page, so a long-lived tip keeps its CI (#528)
actions/runs?head_sha= answers 100 runs a page, and three scripts read
only the first. A tip that stays the tip collects a sweep dispatch every
quarter hour on the same commit, so after about a day its own CI falls to
page two. On 2026-11-12 kivvi's e64eaec carried 129 runs, its green ci.yml
and browser-smoke.yml at positions 124 and 125, and the package rollout
gate held every @bitbaum/limitkit consumer (solon #569) behind 'wait for
bitbaum/kivvi to deploy this artifact and pass CI/browser checks' on a
canary that had deployed, matched its receipt and passed both.

- runs-for-sha.mjs: everyRunForSha reads every page, newest first, and
  throws past ten pages instead of answering from a cut list.
- The rollout gate, the Git package currency check and the deploy
  freshness audit read through it.
- runs-for-sha.test.mjs: the kivvi shape (127 newer dispatches) counts the
  buried green runs; a run created mid-read neither hides nor invents one.

Checked against live data: the gate on solon #569 exits 1 with the message
above before this change and 0 after it.

Claude-Session: https://claude.ai/code/session_019MDtmup8GiNe1XJoj1caTC

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 18:32:36 +01:00

458 lines
20 KiB
JavaScript

#!/usr/bin/env node
/**
* Did what is on main actually reach the box?
*
* WHY THIS EXISTS
*
* Nothing in this fleet asks that question. `uptime-sweep.sh` probes
* /api/health and treats 5xx as DOWN — that proves a process is UP, not that it
* is running the code we merged. CLAUDE.md already says a health check is not a
* feature check; this is the missing half.
*
* It matters because of how merges reach the box. A push made with
* GITHUB_TOKEN triggers no workflows, so an auto-merged PR fires no Deploy:
* measured 2026-09-15 on bitbaum/loki, SIX of the last fifteen commits on main
* had no Deploy run of their own. They shipped anyway, because the auto-merge
* sweep RECONCILES every ten minutes — it compares main's tip against the last
* successful deploy and dispatches when they differ.
*
* That reconciler is therefore the single thing standing between "merged" and
* "live" for most commits, and it has no alarm on it. If it stops — a token
* scope lapses, the workflow is disabled, the input is dropped (deploy.yml
* warns "Removing that input makes merges land and never ship") — then CI stays
* green, PRs keep merging, /api/health keeps returning 200, and the box quietly
* serves last week's code. The failure is invisible by construction.
*
* WHAT IT ASKS
*
* Per repo: is main's tip covered by a successful Deploy? A run for that exact
* SHA counts; so does any successful run that STARTED after the tip was
* committed, because it deployed main as it stood then. Anything else is only a
* finding once it is older than the reconciler's own window — before that it is
* simply pending, and reporting it would be crying wolf every ten minutes.
*
* WHAT IT DELIBERATELY DOES NOT DO
*
* It does not judge whether the deployed code WORKS. And it does not read the
* app's own /api/health `commit` field, tempting as that is: exactly one of
* thirteen live apps publishes one (measured the same day), so a check built on
* it would silently cover a single app while looking fleet-wide.
*
* node scripts/ci/deploy-freshness-audit.mjs # report
* node scripts/ci/deploy-freshness-audit.mjs --check # exit 1 on stale
*/
import { execFileSync } from "node:child_process";
import { everyRunForSha, runsForShaPath } from "./runs-for-sha.mjs";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
/** How long a merged commit may sit undeployed before it is a finding. The
* auto-merge sweep runs every 10 minutes; this is that plus room for a build. */
export const GRACE_MINUTES = 45;
export const FRESHNESS = {
/** main's tip is covered by a successful deploy. */
DEPLOYED: "deployed",
/** Not yet deployed, but still inside the reconciler's window. */
PENDING: "pending",
/** Not deployed, and old enough that the reconciler should have caught it. */
STALE: "stale",
/** No deploy workflow, or no runs at all — cannot judge, must not read clean. */
UNKNOWN: "unknown",
};
/**
* Is main's tip deployed?
*
* `deployRuns` are that repo's Deploy runs, newest first, each
* `{ headSha, status, conclusion, createdAt }`.
*
* Two ways to be covered, and the second one matters more than it looks: most
* commits here never get a run of their own, they ride along on a later
* reconciler dispatch. Requiring an exact-SHA run would report almost the whole
* fleet stale while everything was in fact live — the same mistake as checking
* that the box serves YOUR merge SHA on a main that moves every few minutes.
*/
export function deployFreshness({ tipSha, tipCommittedAt, deployRuns, now, graceMinutes = GRACE_MINUTES }) {
const runs = (deployRuns ?? []).filter((r) => r && r.status === "completed");
const good = runs.filter((r) => r.conclusion === "success");
if (good.length === 0) {
return { state: FRESHNESS.UNKNOWN, reason: "no successful Deploy run on record" };
}
const exact = good.find((r) => r.headSha === tipSha);
if (exact) return { state: FRESHNESS.DEPLOYED, reason: `deployed by a run for ${short(tipSha)}` };
const committed = Date.parse(tipCommittedAt);
const after = good.find((r) => Date.parse(r.createdAt) > committed);
if (after) {
return {
state: FRESHNESS.DEPLOYED,
reason: `covered by a later successful deploy (${after.createdAt})`,
};
}
const ageMin = (Date.parse(now) - committed) / 60000;
if (ageMin <= graceMinutes) {
return {
state: FRESHNESS.PENDING,
reason: `merged ${Math.round(ageMin)}m ago; reconciler window is ${graceMinutes}m`,
};
}
return {
state: FRESHNESS.STALE,
reason: `main tip is ${Math.round(ageMin)}m old and no deploy has run since it`,
};
}
const short = (s) => (typeof s === "string" ? s.slice(0, 7) : String(s));
/**
* Which repos did this run stop looking at?
*
* A count is not coverage. This audit printed "✓ every deploying repo has its
* main tip live" over a run that had silently never looked at `annushka`: the
* repo is PRIVATE, the workflow's token could not enumerate it, and a repo the
* token cannot see is absent from `gh repo list` in exactly the same way as a
* repo that does not exist. Locally, with a token that could see it, the same
* command surveyed 21 repos; in CI it surveyed 20 and called that clean.
*
* That is the failure this whole file exists to prevent, committed by the file
* itself. So the fleet's deploying repos are pinned in a committed baseline and
* coverage becomes a ratchet: it may RISE (a new repo starts deploying, and the
* baseline is updated) but a silent FALL is a finding. A repo that is genuinely
* retired leaves the baseline in the same PR, where a human sees the decision —
* the same shape as the duplication ratchet in SHARED.md.
*/
export function missingFrom(baseline, surveyed) {
const seen = new Set(surveyed);
return (baseline ?? []).filter((name) => !seen.has(name)).sort();
}
/** Repos surveyed now that the baseline does not know about yet. */
export function newlyDeploying(baseline, surveyed) {
const known = new Set(baseline ?? []);
return (surveyed ?? []).filter((name) => !known.has(name)).sort();
}
const BASELINE_PATH = join(dirname(fileURLToPath(import.meta.url)), "deploy-coverage.baseline");
export function readBaseline(path = BASELINE_PATH) {
try {
return readFileSync(path, "utf8")
.split("\n")
.map((l) => l.replace(/#.*$/, "").trim())
.filter(Boolean);
} catch {
return [];
}
}
// ── live data ───────────────────────────────────────────────────────────────
/**
* `gh`, with retries.
*
* This audit makes dozens of sequential API calls and the network is not
* reliable: a single `unexpected EOF` used to be swallowed into an empty run
* list, which the verdict then read as "no successful Deploy run on record" —
* a COULD-NOT-LOOK reported as a fact about the repo. loki and aoz-begleitung were
* both flagged that way while having 2 and 9 successful deploys respectively.
*/
export function gh(args, { attempts = 3 } = {}) {
let last;
for (let i = 0; i < attempts; i++) {
try {
return execFileSync("gh", args, {
encoding: "utf8", timeout: 60000, maxBuffer: 32 * 1024 * 1024,
// CAPTURE stderr rather than letting it through. execFileSync forwards
// the child's stderr to ours by default, so probing 21 repos for a
// .github/workflows directory printed eight bare `gh: Not Found (HTTP
// 404)` lines above the report — expected misses, indistinguishable
// from a real failure, and noisy enough to hide one. Captured, they
// reach the retry predicate and the COULD NOT READ row instead.
stdio: ["ignore", "pipe", "pipe"],
});
} catch (e) {
last = e;
const msg = String(e.stderr || e.message || "");
// Only retry transport failures. A 404 is an answer; retrying it is waste.
if (!/EOF|timeout|timed out|reset by peer|dial tcp|connection refused|502|503|504/i.test(msg)) break;
}
}
throw last;
}
/**
* Is this deploy-named workflow actually a deployer?
*
* Two wrong answers were tried before this one, and the order matters.
*
* Name alone (/deploy/i) was too WIDE: this audit's own
* `deploy-freshness.yml` matched, so the fleet repo — which deploys nothing —
* was reported as a deploying repo with no successful deploy.
*
* Requiring the content to call `selfhost-deploy.yml` or `deploy.sh` was too
* NARROW, and failed on the most important repo: loki's own deploy.yml ships
* inline (checkout, build, rsync) and matched neither, so the control plane
* itself was excluded while holding seven successful deploys.
*
* A false negative is the worse direction — a missed deployer is a repo nobody
* is checking — so the rule is now: include by name, and exclude only what is
* PROVEN not to deploy. Today that is exactly one thing, this audit itself.
*/
const NOT_A_DEPLOYER = /deploy-freshness-audit|deploy-freshness\.yml/;
/**
* The whole decision, as a pure function, because I got it wrong twice and a
* heuristic nobody can test is a heuristic that will be wrong a third time.
*
* `body` is null when the file could not be read.
*/
export function isDeployerSource(file, body) {
// A `.disabled` file is not a workflow: GitHub does not run it, and asking
// the API for its runs 404s. datacat's deploy.yml.disabled matched /deploy/i
// and took the whole repo out of the audit with an unreadable error.
if (!/\.ya?ml$/.test(file)) return false;
// Unreadable. Keep it: an unreadable candidate that IS a deployer must not
// silently drop its repo out of the audit. Erring loud beats erring quiet.
if (body == null) return true;
return !NOT_A_DEPLOYER.test(body);
}
function isDeployWorkflow(owner, repo, file) {
if (!/\.ya?ml$/.test(file)) return false; // do not spend a request on it
let body = null;
try {
body = Buffer.from(
JSON.parse(gh(["api", `repos/${owner}/${repo}/contents/.github/workflows/${file}`, "--jq", "{c: .content}"])).c,
"base64",
).toString("utf8");
} catch {
/* leave body null — isDeployerSource decides what that means */
}
return isDeployerSource(file, body);
}
/** Repos that actually have a deploy workflow — the only ones this can judge. */
export function reposWithDeploy(owner, limit) {
const all = JSON.parse(
gh(["repo", "list", owner, "--limit", String(limit), "--no-archived",
"--json", "name,isFork,defaultBranchRef"]),
).filter((r) => !r.isFork);
const out = [];
for (const r of all) {
// The default branch is per-repo: aoz-begleitung and sbb-fundbuero are on
// `master`. Hardcoding `main` asked for runs on a branch that does not
// exist there, got none back, and reported both as never deployed.
const branch = r.defaultBranchRef?.name || "main";
try {
const files = JSON.parse(
gh(["api", `repos/${owner}/${r.name}/contents/.github/workflows`, "--jq", "[.[].name]"]),
);
const deployFiles = files
// `cd.yml` is a deploy workflow by any reading, and matching only
// /deploy/i never saw it — so orangecat, the largest repo in the org,
// was silently outside this audit from the day it was written. It was
// not reported clean; it was never looked at. Found 2026-09-17, while
// its main had not reached the box since 483cb9e0.
.filter((f) => /deploy|^cd\.ya?ml$/i.test(f))
.filter((f) => isDeployWorkflow(owner, r.name, f));
if (deployFiles.length) out.push({ name: r.name, branch, deployFiles });
} catch {
/* no workflows directory: not a deploying repo */
}
}
return out;
}
export function tipOf(owner, repo, branch) {
const c = JSON.parse(
gh(["api", `repos/${owner}/${repo}/commits?per_page=1&sha=${encodeURIComponent(branch)}`, "--jq",
"[.[0].sha, .[0].commit.committer.date]"]),
);
return { sha: c[0], committedAt: c[1] };
}
/**
* A repo's Deploy runs — asked of the DEPLOY WORKFLOW, not of a window of all
* runs.
*
* The first version read `actions/runs?per_page=40` and filtered by name. On a
* busy repo that window is entirely CI and auto-merge runs, so a perfectly
* healthy Deploy from two days ago falls off the end and the repo reports
* "no successful Deploy run on record". Measured immediately: aoz-begleitung was
* flagged UNKNOWN while its newest Deploy was green.
*
* A window is not an absence. Scoping the query to each deploy workflow's own
* runs makes the answer independent of how chatty the rest of the repo is.
*/
export function deployRunsOf(owner, repo, workflowFiles, branch) {
const runs = [];
for (const file of workflowFiles) {
// Deliberately NOT swallowed. A workflow with no runs returns an empty
// array from the API; only a genuine read failure throws, and the caller
// must be able to tell those apart or a flaky network reads as a verdict.
runs.push(...JSON.parse(
gh(["api", `repos/${owner}/${repo}/actions/workflows/${file}/runs?branch=${encodeURIComponent(branch)}&per_page=20`,
"--jq",
"[.workflow_runs[] | {headSha: .head_sha, status, conclusion, createdAt: .created_at}]"]),
));
}
return runs;
}
/**
* Was this exact commit deployed, according to the run index keyed by COMMIT?
*
* This exists because re-reading the same endpoint twice was not enough.
*
* `actions/workflows/{file}/runs?branch=main` intermittently returns a page
* that omits its own newest runs. Measured 2026-09-15: it happened to datacat
* twice and to evig once inside ninety minutes, and on evig it got past the
* double-read guard and dispatched a real, redundant deploy of a tip that had
* been live since 05:42. Reading a flaky endpoint twice mostly gives you the
* same flake twice; it is not independent evidence.
*
* `actions/runs?head_sha=<sha>` is a DIFFERENT index — keyed by commit rather
* than by workflow and branch — and answers the question actually being asked:
* has this commit had a successful deploy run? On evig it returned the
* deploy-selfhost.yml success that the other endpoint had just denied.
*
* Runs carry `path` (".github/workflows/deploy-selfhost.yml"), so the file is
* compared by basename against the repo's known deploy workflows.
*/
export function deployedByShaIndex(runsForSha, deployFiles) {
const want = new Set((deployFiles ?? []).map((f) => String(f).toLowerCase()));
return (runsForSha ?? []).some(
(r) =>
r &&
r.status === "completed" &&
r.conclusion === "success" &&
want.has(String(r.path ?? "").split("/").pop().toLowerCase()),
);
}
export function runsForSha(owner, repo, sha) {
try {
return everyRunForSha((page) =>
JSON.parse(
gh(["api", runsForShaPath(`${owner}/${repo}`, sha, page), "--jq",
"{total_count, workflow_runs: [.workflow_runs[] | {path, status, conclusion}]}"]),
),
);
} catch {
return null; // unreadable: deployedByShaIndex(null) is false, so it does not
// manufacture a confirmation either way
}
}
function main() {
const owner = process.env.GH_OWNER || "bitbaum";
const limit = Number(process.env.GH_LIMIT || 200);
const check = process.argv.includes("--check");
const now = new Date().toISOString();
const repos = reposWithDeploy(owner, limit);
if (repos.length === 0) {
// A sweep that judged nothing must never read as a clean sweep.
console.error("⊘ deploy-freshness SKIPPED — no repos with a deploy workflow were found.");
process.exit(check ? 1 : 0);
}
const rows = [];
for (const { name: repo, branch, deployFiles } of repos) {
try {
const tip = tipOf(owner, repo, branch);
let verdict = deployFreshness({
tipSha: tip.sha,
tipCommittedAt: tip.committedAt,
deployRuns: deployRunsOf(owner, repo, deployFiles, branch),
now,
});
// Before calling a repo stale, ask a DIFFERENT index.
//
// `actions/workflows/{file}/runs?branch=...` intermittently returns a
// page that omits its own newest runs — measured on datacat twice and
// evig twice on 2026-09-15, each time contradicted seconds later by a
// direct probe. The reconciler already cross-checks, because a wrong
// STALE there costs a real redundant deploy. This gate only reports, so
// the cross-check was left out of it, and that was the wrong call: on the
// first run after the aoz rename it went RED on evig, whose tip had a
// successful deploy-selfhost.yml run sitting in the commit index the
// whole time. A gate that cries wolf gets muted, which is the one thing
// this file cannot afford.
if (verdict.state === FRESHNESS.STALE &&
deployedByShaIndex(runsForSha(owner, repo, tip.sha), deployFiles)) {
verdict = {
state: FRESHNESS.DEPLOYED,
reason: `deployed by a run for ${short(tip.sha)} (found in the commit index, not the workflow listing)`,
};
}
rows.push({ repo, tip: short(tip.sha), ...verdict });
} catch (e) {
rows.push({
repo, tip: "?", state: FRESHNESS.UNKNOWN,
reason: `COULD NOT READ (not a verdict): ${String(e.message).split("\n")[0].slice(0, 90)}`,
});
}
}
// Before any verdict is printed: did this run see the whole fleet?
const baseline = readBaseline();
const surveyed = repos.map((r) => r.name);
const missing = missingFrom(baseline, surveyed);
const added = newlyDeploying(baseline, surveyed);
const order = { stale: 0, unknown: 1, pending: 2, deployed: 3 };
rows.sort((a, b) => order[a.state] - order[b.state] || a.repo.localeCompare(b.repo));
console.log(`deploy-freshness: ${rows.length} repo(s) with a deploy workflow`);
const mark = { deployed: "✓", pending: "·", stale: "✗", unknown: "?" };
for (const r of rows) {
console.log(` ${mark[r.state]} ${r.repo.padEnd(22)} ${r.tip.padEnd(9)} ${r.state.padEnd(9)} ${r.reason}`);
}
const stale = rows.filter((r) => r.state === FRESHNESS.STALE);
const unknown = rows.filter((r) => r.state === FRESHNESS.UNKNOWN);
console.log();
if (added.length) {
console.log(` ${added.length} repo(s) now deploy that the baseline does not list — add them:`);
for (const name of added) console.log(` + ${name}`);
console.log();
}
if (missing.length) {
console.log(`✗ COVERAGE FELL — ${missing.length} baselined repo(s) were not surveyed at all:`);
for (const name of missing) console.log(` - ${name}`);
console.log(" A repo this token cannot see is missing from `gh repo list` in exactly the");
console.log(" same way as a repo that does not exist, so the rows above do NOT describe");
console.log(" the whole fleet. Check the token's scope (a PRIVATE repo needs one that can");
console.log(" read it); if the repo is genuinely retired, drop it from the baseline.");
console.log();
if (check) process.exit(1);
}
if (unknown.length) {
console.log(` ${unknown.length} repo(s) could not be judged — that is not the same as clean:`);
for (const r of unknown) console.log(` ${r.repo}: ${r.reason}`);
}
if (stale.length === 0) {
console.log("✓ every deploying repo has its main tip live (or is inside the reconciler window).");
return;
}
console.log(`✗ ${stale.length} repo(s) merged but NOT LIVE:`);
for (const r of stale) console.log(` ${r.repo} — ${r.reason}`);
console.log();
console.log(" Most commits here never fire their own Deploy; the auto-merge sweep");
console.log(" reconciles every 10 minutes. A repo stuck here means that reconciler");
console.log(" is not running — check auto-merge.yml still passes `deploy_workflow`.");
if (check) process.exit(1);
}
const invokedDirectly = process.argv[1] && import.meta.url === `file://${process.argv[1]}`;
if (invokedDirectly) main();