diff --git a/pkgs/github-ci/worker/.gitignore b/pkgs/github-ci/worker/.gitignore new file mode 100644 index 0000000000..2a11f39f20 --- /dev/null +++ b/pkgs/github-ci/worker/.gitignore @@ -0,0 +1 @@ +.backfill.build.mjs diff --git a/pkgs/github-ci/worker/README.md b/pkgs/github-ci/worker/README.md index 9e2712a1e6..4d694fb20d 100644 --- a/pkgs/github-ci/worker/README.md +++ b/pkgs/github-ci/worker/README.md @@ -90,3 +90,26 @@ The mirror is a **read model**: rebuildable from GitHub at any time, never a second truth. Staleness is reported, never gated on (#8575). Mirror write failures are fatal (500 -> GitHub retries), matching the ci_events policy. + +### Backfill / repair sweep + +`scripts/backfill.ts` reconciles the mirror from the GitHub API — +the repair path for anything the webhooks missed (a Worker outage, +a repo whose hook was added late, a deletion, which GitHub never +replays). It diffs every issue/PR in a repo against the stored rows +on `(gh_updated_at, body_hash)`, re-upserts changed rows through the +same statement builders the webhook paths use (all guards apply +identically), tombstones + deletes stored numbers the API no longer +returns, re-derives the latest-agent-note pointer for changed items +from their surviving comments, and stamps +`github_mirror_meta.last_backfill_at`. It never stamps the webhook +fields. Run it from this directory: + +```sh +GH_TOKEN=$(gh auth token) \ +TURSO_QUEUE_TOKEN=$(fleet secrets get turso.fleet-queue-rw-token) \ +npm run backfill -- [owner/repo ...] # default: every FLEET_REPOS repo +``` + +Output is one JSON summary line per repo (seen / upserted / +vanished_deleted / pointers_set / pointers_cleared / unchanged). diff --git a/pkgs/github-ci/worker/package.json b/pkgs/github-ci/worker/package.json index ee67aa8a31..d8a0843e43 100644 --- a/pkgs/github-ci/worker/package.json +++ b/pkgs/github-ci/worker/package.json @@ -8,7 +8,8 @@ "deploy": "wrangler deploy", "dev": "wrangler dev", "test": "vitest run", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "backfill": "esbuild scripts/backfill.ts --bundle --platform=node --format=esm --outfile=.backfill.build.mjs && node .backfill.build.mjs" }, "devDependencies": { "@cloudflare/vitest-pool-workers": "0.9.14", @@ -19,5 +20,11 @@ }, "overrides": { "undici": "7.30.1" + }, + "allowScripts": { + "esbuild@0.28.2": true, + "esbuild@0.25.4": true, + "sharp@0.33.5": true, + "workerd@1.20251011.0": true } } diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts new file mode 100644 index 0000000000..0aaf821dcf --- /dev/null +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -0,0 +1,557 @@ +/** + * Backfill / repair sweep for the GitHub mirror (#8580, task 16834). + * + * The mirror (src/mirror.ts) is a read model: webhooks keep it warm, + * this sweep reconciles it from the GitHub API. One run per repo: + * + * 1. List every issue and PR (all states) from the REST API. The + * issues list also carries each PR's comment count, which the + * pulls list omits — the two are joined on number. + * 2. Diff against the stored rows on (gh_updated_at, body_hash). + * Changed or missing items are re-upserted through the SAME + * statement builders the webhook paths use, so every guard + * (tombstone, version, comment-count versioning) applies + * identically. Unchanged items are not rewritten. + * 3. Stored numbers the API no longer returns are tombstoned and + * deleted (GitHub deletes are the one event class a missed + * webhook can never replay). + * 4. For every changed item with comments, the item's comments are + * listed and the latest agent-note pointer is re-derived: a + * surviving latest note is applied through the comment-touch + * statements; a stored pointer naming a comment that no longer + * exists is cleared. + * 5. github_mirror_meta.last_backfill_at is stamped for the repo. + * The webhook fields are never touched by the sweep. + * + * Usage (from pkgs/github-ci/worker): + * GH_TOKEN=$(gh auth token) \ + * TURSO_QUEUE_TOKEN=$(fleet secrets get turso.fleet-queue-rw-token) \ + * npm run backfill -- [--max-pointer-repairs=N] [owner/repo ...] + * With no arguments every FLEET_REPOS repo is swept; a repo that + * errors (renamed, no access) is reported and the sweep continues. + * Output is one JSON summary line per repo plus a totals line. + */ +import { + backfillStampStmt, + bodyHashOf, + buildCommentTouch, + buildIssueRow, + buildPrRow, + clearAgentNotePointerStmts, + commentTouchStmts, + forceCommentsStmt, + ensureMirrorSchema, + isAgentNote, + issueUpsertStmt, + mirrorSweepBatch, + prUpsertStmt, + tombstoneDeleteStmts, +} from "../src/mirror"; +import { FLEET_REPOS } from "../src/policy"; +import { queueNow, type SinkEnv } from "../src/sink"; +import { Turso } from "../src/turso"; + +type Obj = Record; + +const TURSO_QUEUE_URL = + process.env.TURSO_QUEUE_URL ?? + "https://fleet-queue-dezren39.aws-us-east-1.turso.io"; + +const env: SinkEnv = { + TURSO_QUEUE_URL, + TURSO_QUEUE_TOKEN: process.env.TURSO_QUEUE_TOKEN ?? "", +}; + +const GH_TOKEN = process.env.GH_TOKEN ?? ""; +if (!GH_TOKEN) + throw new Error("GH_TOKEN is unset (see usage in the file header)"); +if (!env.TURSO_QUEUE_TOKEN) + throw new Error("TURSO_QUEUE_TOKEN is unset (see usage in the file header)"); + +/** + * Retry transient transport failures (socket termination, 5xx) with + * backoff. The fleet's laptop network drops long request sequences + * regularly; a sweep is exactly that, so every call it makes goes + * through here or through sweepBatch. HTTP 4xx is not retried. + */ +/** An HTTP error response; retry() never retries a 4xx. */ +class HttpStatusError extends Error { + readonly status: number; + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +const retry = async (label: string, fn: () => Promise): Promise => { + let lastErr: unknown; + for (let attempt = 1; attempt <= 5; attempt++) { + try { + return await fn(); + } catch (e) { + if (e instanceof HttpStatusError && e.status < 500) throw e; + lastErr = e; + if (attempt < 5) + await new Promise((r) => setTimeout(r, 500 * 2 ** attempt)); + } + } + throw new Error(`${label}: failed after 5 attempts: ${String(lastErr)}`); +}; + +const sweepBatch: typeof mirrorSweepBatch = (e, stmts) => + retry(`turso batch (${stmts.length} stmts)`, () => + mirrorSweepBatch(e, stmts), + ); + +const api = async (path: string): Promise => + retry(`github api ${path}`, async () => { + const res = await fetch(`https://api.github.com${path}`, { + // A wedged connection must fail into the retry loop in + // seconds, not stall the sweep for minutes. + signal: AbortSignal.timeout(60_000), + headers: { + Authorization: `Bearer ${GH_TOKEN}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "github-ci-mirror-backfill", + }, + }); + if (res.status >= 500) + throw new Error(`github api ${path}: HTTP ${res.status}`); + if (!res.ok) + throw new HttpStatusError( + res.status, + `github api ${path}: HTTP ${res.status}`, + ); + return res.json(); + }); + +/** + * Fetch every page of a list endpoint by following Link rel="next" + * URLs verbatim. The issues endpoint is cursor-paginated (the Link + * header carries only an `after` cursor, no rel="last"), while the + * pulls endpoint still uses page numbers — following `next` is the + * one scheme that is correct for both. (The first version of this + * sweep parsed rel="last" and silently stopped after page 1 of the + * issues list: 2 pure issues out of 5430. The summary's seen counts + * are what caught it.) + */ +const apiAll = async (path: string): Promise => { + const out: Obj[] = []; + let url: string | null = + `https://api.github.com${path}${path.includes("?") ? "&" : "?"}per_page=100`; + while (url) { + const page: { items: Obj[]; next: string | null } = await retry( + `github api ${url}`, + async () => { + const res = await fetch(url, { + signal: AbortSignal.timeout(60_000), + headers: { + Authorization: `Bearer ${GH_TOKEN}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "github-ci-mirror-backfill", + }, + }); + if (!res.ok) + throw new HttpStatusError( + res.status, + `github api ${url}: HTTP ${res.status}`, + ); + const link = res.headers.get("link") ?? ""; + const next = /<([^>]+)>; rel="next"/.exec(link); + return { + items: (await res.json()) as Obj[], + next: next ? next[1] : null, + }; + }, + ); + out.push(...page.items); + url = page.next; + } + return out; +}; + +/** HTTP status of a single GET (404 is an answer, not an error). */ +const apiStatus = async (path: string): Promise => + retry(`github api ${path}`, async () => { + const res = await fetch(`https://api.github.com${path}`, { + signal: AbortSignal.timeout(60_000), + headers: { + Authorization: `Bearer ${GH_TOKEN}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "github-ci-mirror-backfill", + }, + }); + if (res.status >= 500) + throw new Error(`github api ${path}: HTTP ${res.status}`); + return res.status; + }); + +interface StoredRow { + number: number; + ghUpdatedAt: string | null; + bodyHash: string | null; + comments: number; + commentsGhUpdatedAt: string | null; + agentNoteId: number | null; +} + +const storedRows = async ( + q: Turso, + table: string, + repo: string, +): Promise> => { + const r = await retry(`read ${table}`, () => + q.execute( + `SELECT number, gh_updated_at, body_hash, comments, comments_gh_updated_at, latest_agent_note_id + FROM ${table} WHERE repo = ?`, + [{ type: "text", value: repo }], + ), + ); + const map = new Map(); + for (const row of r.response?.result?.rows ?? []) { + const cell = (i: number): string | null => { + const c = row[i]; + return !c || c.type === "null" + ? null + : "value" in c + ? String(c.value) + : null; + }; + const number = Number(cell(0)); + map.set(number, { + number, + ghUpdatedAt: cell(1), + bodyHash: cell(2), + comments: Number(cell(3) ?? 0) || 0, + commentsGhUpdatedAt: cell(4), + agentNoteId: cell(5) === null ? null : Number(cell(5)), + }); + } + return map; +}; + +interface RepoSummary { + repo: string; + issues_seen: number; + prs_seen: number; + upserted: number; + vanished_deleted: number; + pointers_set: number; + pointers_cleared: number; + pointers_deferred: number; + pointers_failed: number; + counts_forced: number; + counts_repair_failed: number; + incomplete?: boolean; + vanished_skipped_live: number; + unchanged: number; + error?: string; +} + +const sweepRepo = async (repo: string): Promise => { + const summary: RepoSummary = { + repo, + issues_seen: 0, + prs_seen: 0, + upserted: 0, + vanished_deleted: 0, + vanished_skipped_live: 0, + pointers_set: 0, + pointers_cleared: 0, + pointers_deferred: 0, + pointers_failed: 0, + counts_forced: 0, + counts_repair_failed: 0, + unchanged: 0, + }; + const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); + const issueList = await apiAll( + `/repos/${repo}/issues?state=all&sort=created&direction=asc`, + ); + const pullList = await apiAll( + `/repos/${repo}/pulls?state=all&sort=created&direction=asc`, + ); + const issueByNumber = new Map(); + for (const item of issueList) issueByNumber.set(Number(item.number), item); + const commentsByNumber = new Map(); + for (const item of issueList) { + commentsByNumber.set(Number(item.number), Number(item.comments ?? 0) || 0); + } + const pureIssues = issueList.filter((i) => !i.pull_request); + const storedIssues = await storedRows(q, "github_mirror_issues", repo); + const storedPrs = await storedRows(q, "github_mirror_pull_requests", repo); + summary.issues_seen = pureIssues.length; + summary.prs_seen = pullList.length; + + interface Pending { + number: number; + isPr: boolean; + item: Obj; + stmt: { sql: string; args?: import("../src/turso").TursoArg[] }; + } + interface CountRepair { + number: number; + isPr: boolean; + /** The stored comments version at diff time — the stamp the repair replaces. */ + guardVersion: string | null; + } + const countRepairs: CountRepair[] = []; + const pending: Pending[] = []; + const consider = async ( + item: Obj, + isPr: boolean, + stored: Map, + ): Promise => { + const number = Number(item.number); + const prev = stored.get(number); + const hash = await bodyHashOf(item); + // The diff key is (gh_updated_at, body_hash, comments): the count + // must be in the key because a comment does not move a PR's + // updated_at, and a count written wrong under a newer version + // stamp is invisible to the other two fields. + const apiComments = isPr + ? (commentsByNumber.get(number) ?? Number(item.comments ?? 0)) + : Number(item.comments ?? 0); + if ( + prev && + prev.ghUpdatedAt === String(item.updated_at ?? "") && + prev.bodyHash === hash && + prev.comments === apiComments + ) { + summary.unchanged++; + return; + } + if (prev && prev.comments !== apiComments) { + countRepairs.push({ + number, + isPr, + guardVersion: prev.commentsGhUpdatedAt, + }); + } + if (isPr) { + // Join the comment count from the issues-list object and keep + // THAT object's updated_at as the count's version: the two + // lists are fetched seconds apart, and pairing the count with + // the pulls-list version would let a stale count win the + // version guard (review finding, PR #10062). + const issueObj = issueByNumber.get(number); + const withComments = { + ...item, + comments: commentsByNumber.get(number) ?? Number(item.comments ?? 0), + comments_updated_at: issueObj + ? String(issueObj.updated_at ?? "") + : undefined, + }; + pending.push({ + number, + isPr, + item, + stmt: prUpsertStmt( + buildPrRow({ pull_request: withComments }, repo, hash), + ), + }); + } else { + pending.push({ + number, + isPr, + item, + stmt: issueUpsertStmt(buildIssueRow({ issue: item }, repo, hash)), + }); + } + }; + for (const issue of pureIssues) await consider(issue, false, storedIssues); + for (const pr of pullList) await consider(pr, true, storedPrs); + + // Vanished: stored numbers (one namespace per repo) the API lists + // did not return. Absence from a paginated list is NOT proof of + // deletion — an item created after the list was fetched but before + // the stored rows were read would look identical, and a NULL + // tombstone is permanent. Confirm each candidate against the item + // endpoint first; only a 404 tombstones. + const seen = new Set([ + ...issueList.map((i) => Number(i.number)), + ...pullList.map((p) => Number(p.number)), + ]); + const flush: Pending["stmt"][] = []; + for (const number of new Set([...storedIssues.keys(), ...storedPrs.keys()])) { + if (seen.has(number)) continue; + if ((await apiStatus(`/repos/${repo}/issues/${number}`)) === 404) { + flush.push(...tombstoneDeleteStmts(repo, number)); + summary.vanished_deleted++; + } else { + summary.vanished_skipped_live++; + } + } + + // Pointer re-derivation runs BEFORE the snapshot flush, and a + // failed repair keeps its item out of the flush: the item then + // still diffs as changed on the next run, so the repair stays + // eligible instead of being hidden by snapshot equality. + const failed = new Set(); + const candidates = pending + .filter((p) => { + const stored = (p.isPr ? storedPrs : storedIssues).get(p.number); + return ( + (commentsByNumber.get(p.number) ?? 0) > 0 || stored?.agentNoteId != null + ); + }) + .sort((a, b) => + String(b.item.updated_at ?? "").localeCompare( + String(a.item.updated_at ?? ""), + ), + ); + let pointerBudget = MAX_POINTER_REPAIRS; + for (const cand of candidates) { + const { number, isPr, item } = cand; + if (pointerBudget <= 0) { + summary.pointers_deferred++; + continue; + } + pointerBudget--; + try { + const comments = await apiAll( + `/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`, + ); + const stored = (isPr ? storedPrs : storedIssues).get(number); + const isNote = (c: Obj): boolean => + isAgentNote(typeof c.body === "string" ? c.body : null); + const latestNote = [...comments].reverse().find(isNote); + let pointerNow = stored?.agentNoteId ?? null; + if (pointerNow != null) { + const pointed = comments.find((c) => Number(c.id) === pointerNow); + if (!pointed || !isNote(pointed)) { + // Stale pointer: the comment is deleted, or was edited so + // it is no longer an agent note. Clear conditionally (a + // newer webhook-installed pointer is never erased), and + // record the deletion only when the comment is truly gone. + await sweepBatch( + env, + clearAgentNotePointerStmts( + repo, + number, + isPr, + pointerNow, + !pointed, + ), + ); + summary.pointers_cleared++; + pointerNow = null; + } + } + if (latestNote && Number(latestNote.id) !== pointerNow) { + // buildCommentTouch reads the discriminator + count off the + // carrying object: a pulls-list object has neither, so PR + // items are adapted (explicit pull_request marker + the + // joined count) or the touch would land on the issues table. + const touchIssue = isPr + ? { + ...item, + comments: commentsByNumber.get(number) ?? 0, + pull_request: { url: String(item.url ?? "") }, + } + : item; + const touch = buildCommentTouch( + { issue: touchIssue, comment: latestNote, action: "created" }, + repo, + ); + await sweepBatch(env, commentTouchStmts(touch)); + summary.pointers_set++; + } + } catch { + failed.add(number); + summary.pointers_failed++; + } + } + + for (const p of pending) { + if (!failed.has(p.number)) { + flush.push(p.stmt); + summary.upserted++; + } + } + for (let i = 0; i < flush.length; i += 200) { + await sweepBatch(env, flush.slice(i, i + 200)); + } + + // Count-repair pass: for every row whose count mismatched at diff + // time and that the version guard still rejected, re-fetch the + // item's CURRENT count from the API and force-set it — guarded on + // the stored comments version still being the diff-time stamp, so + // a webhook update that landed in between is never overwritten by + // an older list count. + const afterIssues = countRepairs.some((r) => !r.isPr) + ? await storedRows(q, "github_mirror_issues", repo) + : null; + const afterPrs = countRepairs.some((r) => r.isPr) + ? await storedRows(q, "github_mirror_pull_requests", repo) + : null; + for (const repair of countRepairs) { + const now = (repair.isPr ? afterPrs : afterIssues)?.get(repair.number); + if (!now) continue; + try { + const fresh = (await api( + `/repos/${repo}/issues/${repair.number}`, + )) as Obj; + const freshCount = Number(fresh.comments ?? 0) || 0; + if ( + now.comments !== freshCount && + now.commentsGhUpdatedAt === repair.guardVersion + ) { + await sweepBatch(env, [ + forceCommentsStmt( + repo, + repair.number, + repair.isPr, + freshCount, + typeof fresh.updated_at === "string" ? fresh.updated_at : null, + repair.guardVersion, + ), + ]); + summary.counts_forced++; + } + } catch { + summary.counts_repair_failed++; + } + } + + // A run with failed repairs is incomplete: partial progress is + // kept (snapshots flushed, successful repairs applied) but the + // backfill stamp is withheld and main() reports the repo as failed, + // so the next run re-diffs the same items and retries. + summary.incomplete = + summary.pointers_failed > 0 || summary.counts_repair_failed > 0; + if (!summary.incomplete) { + await sweepBatch(env, [backfillStampStmt(repo, queueNow())]); + } + return summary; +}; + +const MAX_POINTER_REPAIRS = Number( + process.argv + .find((a) => a.startsWith("--max-pointer-repairs=")) + ?.split("=")[1] ?? 400, +); + +const main = async (): Promise => { + const repoArgs = process.argv.slice(2).filter((a) => !a.startsWith("--")); + const repos = repoArgs.length > 0 ? repoArgs : [...FLEET_REPOS]; + await retry("ensure schema", () => ensureMirrorSchema(env)); + let failures = 0; + for (const repo of repos) { + try { + const s = await sweepRepo(repo); + console.log(JSON.stringify(s)); + if (s.incomplete) failures++; + } catch (e) { + failures++; + console.log(JSON.stringify({ repo, error: String(e) })); + } + } + console.log(JSON.stringify({ done: true, repos: repos.length, failures })); + if (failures > 0) process.exitCode = 1; +}; + +await main(); diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index c986aacca3..aaaa923f27 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -134,7 +134,9 @@ export function labelsOf(obj: Obj): string[] { /** Assignee logins: the assignees array, falling back to the single assignee. */ export function assigneesOf(obj: Obj): string[] { const many = Array.isArray(obj.assignees) ? obj.assignees : []; - const logins = many.map((a) => str((a ?? {}) as Obj, "login")).filter((n): n is string => !!n); + const logins = many + .map((a) => str((a ?? {}) as Obj, "login")) + .filter((n): n is string => !!n); if (logins.length) return logins.sort(); const one = str((obj.assignee ?? {}) as Obj, "login"); return one ? [one] : []; @@ -155,7 +157,11 @@ export interface IssueRow { gh_updated_at: string | null; } -export function buildIssueRow(payload: Obj, repo: string, bodyHash: string | null): IssueRow { +export function buildIssueRow( + payload: Obj, + repo: string, + bodyHash: string | null, +): IssueRow { const issue = (payload.issue ?? {}) as Obj; return { repo, @@ -179,13 +185,28 @@ export interface PrRow extends IssueRow { head_sha: string | null; head_ref: string | null; base_ref: string | null; + /** + * The version of the comments count, kept separate from the + * snapshot version (gh_updated_at): the backfill sweep joins the + * count from the issues-list object, whose updated_at is the + * count's own version. Webhook payloads carry no separate field, + * so buildPrRow falls back to the PR's updated_at — the count and + * the snapshot then share one object and one version, as before. + */ + comments_gh_updated_at: string | null; } -export function buildPrRow(payload: Obj, repo: string, bodyHash: string | null): PrRow { +export function buildPrRow( + payload: Obj, + repo: string, + bodyHash: string | null, +): PrRow { const pr = (payload.pull_request ?? {}) as Obj; const base = buildIssueRow({ issue: pr }, repo, bodyHash); return { ...base, + comments_gh_updated_at: + str(pr, "comments_updated_at") ?? base.gh_updated_at, merged: pr.merged === true || typeof pr.merged_at === "string" ? 1 : 0, draft: pr.draft === true ? 1 : 0, head_sha: str((pr.head ?? {}) as Obj, "sha"), @@ -216,7 +237,9 @@ export interface CommentTouch { /** Agent notes carry the machine marker; the emoji header is the fallback. */ export function isAgentNote(body: string | null | undefined): boolean { if (!body) return false; - return body.includes(" note", + html_url: "https://example.invalid/c9", + }, + action: "deleted", + }, + REPO, + ); + expect(commentTouchStmts(deletedNote)).toHaveLength(4); + }); +});