From e52860792387c4041d5c12fb6e0f53d8ff6eb088 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 08:43:03 -0600 Subject: [PATCH 1/7] feat(github-ci): backfill/repair sweep for the #8580 GitHub mirror scripts/backfill.ts reconciles the mirror from the GitHub API: diffs on (gh_updated_at, body_hash), re-upserts through the same statement builders as the webhook paths (extracted in mirror.ts: issueUpsertStmt/prUpsertStmt/commentTouchStmts), tombstones+deletes vanished numbers, re-derives agent-note pointers for changed items, stamps last_backfill_at only. 60/60 worker tests pass (6 new). Task 16834. --- pkgs/github-ci/worker/.gitignore | 1 + pkgs/github-ci/worker/README.md | 23 + pkgs/github-ci/worker/package.json | 9 +- pkgs/github-ci/worker/scripts/backfill.ts | 284 +++++++++++ pkgs/github-ci/worker/src/mirror.ts | 491 +++++++++++++------- pkgs/github-ci/worker/test/backfill.test.ts | 124 +++++ 6 files changed, 764 insertions(+), 168 deletions(-) create mode 100644 pkgs/github-ci/worker/.gitignore create mode 100644 pkgs/github-ci/worker/scripts/backfill.ts create mode 100644 pkgs/github-ci/worker/test/backfill.test.ts 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..8f80727bcd --- /dev/null +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -0,0 +1,284 @@ +/** + * 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 -- [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, + clearAgentNotePointerStmt, + commentTouchStmts, + 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)"); + +const api = async (path: string): Promise => { + const res = await fetch(`https://api.github.com${path}`, { + 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 Error(`github api ${path}: HTTP ${res.status}`); + return res.json(); +}; + +/** Follow ?page= pagination for a list endpoint; returns every item. */ +const apiAll = async (path: string): Promise => { + const out: Obj[] = []; + for (let page = 1; ; page++) { + const sep = path.includes("?") ? "&" : "?"; + const items = (await api( + `${path}${sep}per_page=100&page=${page}`, + )) as Obj[]; + out.push(...items); + if (items.length < 100) return out; + } +}; + +interface StoredRow { + number: number; + ghUpdatedAt: string | null; + bodyHash: string | null; + comments: number; + agentNoteId: number | null; +} + +const storedRows = async ( + q: Turso, + table: string, + repo: string, +): Promise> => { + const r = await q.execute( + `SELECT number, gh_updated_at, body_hash, comments, 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, + agentNoteId: cell(4) === null ? null : Number(cell(4)), + }); + } + return map; +}; + +interface RepoSummary { + repo: string; + issues_seen: number; + prs_seen: number; + upserted: number; + vanished_deleted: number; + pointers_set: number; + pointers_cleared: 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, + pointers_set: 0, + pointers_cleared: 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 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; + + const stmts: Parameters[1] = []; + const changed: { item: Obj; isPr: boolean }[] = []; + 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); + if ( + prev && + prev.ghUpdatedAt === String(item.updated_at ?? "") && + prev.bodyHash === hash + ) { + summary.unchanged++; + return; + } + if (isPr) { + const withComments = { + ...item, + comments: commentsByNumber.get(number) ?? Number(item.comments ?? 0), + }; + stmts.push( + prUpsertStmt(buildPrRow({ pull_request: withComments }, repo, hash)), + ); + } else { + stmts.push(issueUpsertStmt(buildIssueRow({ issue: item }, repo, hash))); + } + summary.upserted++; + changed.push({ item, isPr }); + }; + 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 did + // not return at all — deleted on GitHub while no webhook watched. + const seen = new Set([ + ...issueList.map((i) => Number(i.number)), + ...pullList.map((p) => Number(p.number)), + ]); + for (const number of new Set([...storedIssues.keys(), ...storedPrs.keys()])) { + if (!seen.has(number)) { + stmts.push(...tombstoneDeleteStmts(repo, number)); + summary.vanished_deleted++; + } + } + // Flush snapshot writes in bounded batches before pointer work. + for (let i = 0; i < stmts.length; i += 100) { + await mirrorSweepBatch(env, stmts.slice(i, i + 100)); + } + + // Pointer re-derivation for changed items that carry comments. + for (const { item, isPr } of changed) { + const number = Number(item.number); + if ( + (commentsByNumber.get(number) ?? 0) === 0 && + Number(item.comments ?? 0) === 0 + ) + continue; + const comments = await apiAll( + `/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`, + ); + const stored = (isPr ? storedPrs : storedIssues).get(number); + const latestNote = [...comments] + .reverse() + .find((c) => isAgentNote(typeof c.body === "string" ? c.body : null)); + if (latestNote) { + if (!stored || stored.agentNoteId !== Number(latestNote.id)) { + const touch = buildCommentTouch( + { issue: item, comment: latestNote, action: "created" }, + repo, + ); + await mirrorSweepBatch(env, commentTouchStmts(touch)); + summary.pointers_set++; + } + } else if ( + stored?.agentNoteId != null && + !comments.some((c) => Number(c.id) === stored.agentNoteId) + ) { + await mirrorSweepBatch(env, [ + clearAgentNotePointerStmt(repo, number, isPr), + ]); + summary.pointers_cleared++; + } + } + + await mirrorSweepBatch(env, [backfillStampStmt(repo, queueNow())]); + return summary; +}; + +const main = async (): Promise => { + const repos = + process.argv.slice(2).length > 0 ? process.argv.slice(2) : [...FLEET_REPOS]; + await ensureMirrorSchema(env); + let failures = 0; + for (const repo of repos) { + try { + console.log(JSON.stringify(await sweepRepo(repo))); + } 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..bda841809e 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, @@ -181,7 +187,11 @@ export interface PrRow extends IssueRow { base_ref: 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 { @@ -216,7 +226,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); + }); +}); From 07789e05dc85575465a978822f66a72f4d435f9c Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 08:54:30 -0600 Subject: [PATCH 2/7] fix(github-ci): sweep retries transient transport failures + bounded pointer repair The laptop network terminates long request sequences regularly (first live run died at ~3 min with TypeError: terminated): every GitHub/Turso call in the sweep now retries 5x with backoff (4xx excluded). Pointer re-derivation is recency-ordered and capped (--max-pointer-repairs, default 400) with deferred items counted in the summary. --- pkgs/github-ci/worker/scripts/backfill.ts | 104 ++++++++++++++++------ 1 file changed, 78 insertions(+), 26 deletions(-) diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts index 8f80727bcd..33f1b1afb8 100644 --- a/pkgs/github-ci/worker/scripts/backfill.ts +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -26,7 +26,7 @@ * 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 -- [owner/repo ...] + * 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. @@ -67,19 +67,47 @@ if (!GH_TOKEN) if (!env.TURSO_QUEUE_TOKEN) throw new Error("TURSO_QUEUE_TOKEN is unset (see usage in the file header)"); -const api = async (path: string): Promise => { - const res = await fetch(`https://api.github.com${path}`, { - 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 Error(`github api ${path}: HTTP ${res.status}`); - return res.json(); +/** + * 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. + */ +const retry = async (label: string, fn: () => Promise): Promise => { + let lastErr: unknown; + for (let attempt = 1; attempt <= 5; attempt++) { + try { + return await fn(); + } catch (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}`, { + 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 Error(`github api ${path}: HTTP ${res.status}`); + return res.json(); + }); + /** Follow ?page= pagination for a list endpoint; returns every item. */ const apiAll = async (path: string): Promise => { const out: Obj[] = []; @@ -106,10 +134,12 @@ const storedRows = async ( table: string, repo: string, ): Promise> => { - const r = await q.execute( - `SELECT number, gh_updated_at, body_hash, comments, latest_agent_note_id - FROM ${table} WHERE repo = ?`, - [{ type: "text", value: repo }], + const r = await retry(`read ${table}`, () => + q.execute( + `SELECT number, gh_updated_at, body_hash, comments, latest_agent_note_id + FROM ${table} WHERE repo = ?`, + [{ type: "text", value: repo }], + ), ); const map = new Map(); for (const row of r.response?.result?.rows ?? []) { @@ -141,6 +171,7 @@ interface RepoSummary { vanished_deleted: number; pointers_set: number; pointers_cleared: number; + pointers_deferred: number; unchanged: number; error?: string; } @@ -154,6 +185,7 @@ const sweepRepo = async (repo: string): Promise => { vanished_deleted: 0, pointers_set: 0, pointers_cleared: 0, + pointers_deferred: 0, unchanged: 0, }; const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); @@ -222,10 +254,21 @@ const sweepRepo = async (repo: string): Promise => { } // Flush snapshot writes in bounded batches before pointer work. for (let i = 0; i < stmts.length; i += 100) { - await mirrorSweepBatch(env, stmts.slice(i, i + 100)); + await sweepBatch(env, stmts.slice(i, i + 100)); } - // Pointer re-derivation for changed items that carry comments. + // Pointer re-derivation for changed items that carry comments, + // most recently updated first, capped per run: a first sweep of a + // large repo changes everything, and one comments listing per item + // would exhaust the API budget repairing pointers for items nobody + // has touched in years. Deferred items are counted, and any later + // change to an item (or a rerun with a raised cap) repairs it. + changed.sort((a, b) => + String(b.item.updated_at ?? "").localeCompare( + String(a.item.updated_at ?? ""), + ), + ); + let pointerBudget = MAX_POINTER_REPAIRS; for (const { item, isPr } of changed) { const number = Number(item.number); if ( @@ -233,6 +276,11 @@ const sweepRepo = async (repo: string): Promise => { Number(item.comments ?? 0) === 0 ) continue; + if (pointerBudget <= 0) { + summary.pointers_deferred++; + continue; + } + pointerBudget--; const comments = await apiAll( `/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`, ); @@ -246,28 +294,32 @@ const sweepRepo = async (repo: string): Promise => { { issue: item, comment: latestNote, action: "created" }, repo, ); - await mirrorSweepBatch(env, commentTouchStmts(touch)); + await sweepBatch(env, commentTouchStmts(touch)); summary.pointers_set++; } } else if ( stored?.agentNoteId != null && !comments.some((c) => Number(c.id) === stored.agentNoteId) ) { - await mirrorSweepBatch(env, [ - clearAgentNotePointerStmt(repo, number, isPr), - ]); + await sweepBatch(env, [clearAgentNotePointerStmt(repo, number, isPr)]); summary.pointers_cleared++; } } - await mirrorSweepBatch(env, [backfillStampStmt(repo, queueNow())]); + 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 repos = - process.argv.slice(2).length > 0 ? process.argv.slice(2) : [...FLEET_REPOS]; - await ensureMirrorSchema(env); + 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 { From 07213b60a8aa30b9b42dd823c34750ad5ac1df19 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 09:05:45 -0600 Subject: [PATCH 3/7] fix(github-ci): 20s per-fetch timeout in the sweep so wedged connections fail into retry --- pkgs/github-ci/worker/scripts/backfill.ts | 101 ++++++---------------- 1 file changed, 25 insertions(+), 76 deletions(-) diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts index 33f1b1afb8..c8b3149246 100644 --- a/pkgs/github-ci/worker/scripts/backfill.ts +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -53,8 +53,7 @@ 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"; + process.env.TURSO_QUEUE_URL ?? "https://fleet-queue-dezren39.aws-us-east-1.turso.io"; const env: SinkEnv = { TURSO_QUEUE_URL, @@ -62,10 +61,8 @@ const env: SinkEnv = { }; 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)"); +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 @@ -80,21 +77,21 @@ const retry = async (label: string, fn: () => Promise): Promise => { return await fn(); } catch (e) { lastErr = e; - if (attempt < 5) - await new Promise((r) => setTimeout(r, 500 * 2 ** attempt)); + 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), - ); + 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(20_000), headers: { Authorization: `Bearer ${GH_TOKEN}`, Accept: "application/vnd.github+json", @@ -102,8 +99,7 @@ const api = async (path: string): Promise => "User-Agent": "github-ci-mirror-backfill", }, }); - if (res.status >= 500) - throw new Error(`github api ${path}: HTTP ${res.status}`); + if (res.status >= 500) throw new Error(`github api ${path}: HTTP ${res.status}`); if (!res.ok) throw new Error(`github api ${path}: HTTP ${res.status}`); return res.json(); }); @@ -113,9 +109,7 @@ const apiAll = async (path: string): Promise => { const out: Obj[] = []; for (let page = 1; ; page++) { const sep = path.includes("?") ? "&" : "?"; - const items = (await api( - `${path}${sep}per_page=100&page=${page}`, - )) as Obj[]; + const items = (await api(`${path}${sep}per_page=100&page=${page}`)) as Obj[]; out.push(...items); if (items.length < 100) return out; } @@ -129,11 +123,7 @@ interface StoredRow { agentNoteId: number | null; } -const storedRows = async ( - q: Turso, - table: string, - repo: string, -): Promise> => { +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, latest_agent_note_id @@ -145,11 +135,7 @@ const storedRows = async ( 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; + return !c || c.type === "null" ? null : "value" in c ? String(c.value) : null; }; const number = Number(cell(0)); map.set(number, { @@ -189,12 +175,8 @@ const sweepRepo = async (repo: string): Promise => { 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 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 commentsByNumber = new Map(); for (const item of issueList) { commentsByNumber.set(Number(item.number), Number(item.comments ?? 0) || 0); @@ -207,30 +189,17 @@ const sweepRepo = async (repo: string): Promise => { const stmts: Parameters[1] = []; const changed: { item: Obj; isPr: boolean }[] = []; - const consider = async ( - item: Obj, - isPr: boolean, - stored: Map, - ): Promise => { + 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); - if ( - prev && - prev.ghUpdatedAt === String(item.updated_at ?? "") && - prev.bodyHash === hash - ) { + if (prev && prev.ghUpdatedAt === String(item.updated_at ?? "") && prev.bodyHash === hash) { summary.unchanged++; return; } if (isPr) { - const withComments = { - ...item, - comments: commentsByNumber.get(number) ?? Number(item.comments ?? 0), - }; - stmts.push( - prUpsertStmt(buildPrRow({ pull_request: withComments }, repo, hash)), - ); + const withComments = { ...item, comments: commentsByNumber.get(number) ?? Number(item.comments ?? 0) }; + stmts.push(prUpsertStmt(buildPrRow({ pull_request: withComments }, repo, hash))); } else { stmts.push(issueUpsertStmt(buildIssueRow({ issue: item }, repo, hash))); } @@ -263,44 +232,26 @@ const sweepRepo = async (repo: string): Promise => { // would exhaust the API budget repairing pointers for items nobody // has touched in years. Deferred items are counted, and any later // change to an item (or a rerun with a raised cap) repairs it. - changed.sort((a, b) => - String(b.item.updated_at ?? "").localeCompare( - String(a.item.updated_at ?? ""), - ), - ); + changed.sort((a, b) => String(b.item.updated_at ?? "").localeCompare(String(a.item.updated_at ?? ""))); let pointerBudget = MAX_POINTER_REPAIRS; for (const { item, isPr } of changed) { const number = Number(item.number); - if ( - (commentsByNumber.get(number) ?? 0) === 0 && - Number(item.comments ?? 0) === 0 - ) - continue; + if ((commentsByNumber.get(number) ?? 0) === 0 && Number(item.comments ?? 0) === 0) continue; if (pointerBudget <= 0) { summary.pointers_deferred++; continue; } pointerBudget--; - const comments = await apiAll( - `/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`, - ); + const comments = await apiAll(`/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`); const stored = (isPr ? storedPrs : storedIssues).get(number); - const latestNote = [...comments] - .reverse() - .find((c) => isAgentNote(typeof c.body === "string" ? c.body : null)); + const latestNote = [...comments].reverse().find((c) => isAgentNote(typeof c.body === "string" ? c.body : null)); if (latestNote) { if (!stored || stored.agentNoteId !== Number(latestNote.id)) { - const touch = buildCommentTouch( - { issue: item, comment: latestNote, action: "created" }, - repo, - ); + const touch = buildCommentTouch({ issue: item, comment: latestNote, action: "created" }, repo); await sweepBatch(env, commentTouchStmts(touch)); summary.pointers_set++; } - } else if ( - stored?.agentNoteId != null && - !comments.some((c) => Number(c.id) === stored.agentNoteId) - ) { + } else if (stored?.agentNoteId != null && !comments.some((c) => Number(c.id) === stored.agentNoteId)) { await sweepBatch(env, [clearAgentNotePointerStmt(repo, number, isPr)]); summary.pointers_cleared++; } @@ -311,9 +262,7 @@ const sweepRepo = async (repo: string): Promise => { }; const MAX_POINTER_REPAIRS = Number( - process.argv - .find((a) => a.startsWith("--max-pointer-repairs=")) - ?.split("=")[1] ?? 400, + process.argv.find((a) => a.startsWith("--max-pointer-repairs="))?.split("=")[1] ?? 400, ); const main = async (): Promise => { From c5b8ef09be07e8b3be05fd8ec484efd5a2ebca3c Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 09:08:43 -0600 Subject: [PATCH 4/7] perf(github-ci): parallel page fetch in the sweep (4 workers, Link-header page count) --- pkgs/github-ci/worker/scripts/backfill.ts | 146 +++++++++++++++++----- 1 file changed, 115 insertions(+), 31 deletions(-) diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts index c8b3149246..c302f0b8a6 100644 --- a/pkgs/github-ci/worker/scripts/backfill.ts +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -53,7 +53,8 @@ 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"; + process.env.TURSO_QUEUE_URL ?? + "https://fleet-queue-dezren39.aws-us-east-1.turso.io"; const env: SinkEnv = { TURSO_QUEUE_URL, @@ -61,8 +62,10 @@ const env: SinkEnv = { }; 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)"); +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 @@ -77,14 +80,17 @@ const retry = async (label: string, fn: () => Promise): Promise => { return await fn(); } catch (e) { lastErr = e; - if (attempt < 5) await new Promise((r) => setTimeout(r, 500 * 2 ** attempt)); + 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)); + retry(`turso batch (${stmts.length} stmts)`, () => + mirrorSweepBatch(e, stmts), + ); const api = async (path: string): Promise => retry(`github api ${path}`, async () => { @@ -99,20 +105,53 @@ const api = async (path: string): Promise => "User-Agent": "github-ci-mirror-backfill", }, }); - if (res.status >= 500) throw new Error(`github api ${path}: HTTP ${res.status}`); + if (res.status >= 500) + throw new Error(`github api ${path}: HTTP ${res.status}`); if (!res.ok) throw new Error(`github api ${path}: HTTP ${res.status}`); return res.json(); }); -/** Follow ?page= pagination for a list endpoint; returns every item. */ +/** One list page plus the last page number from the Link header. */ +const apiPage = async ( + path: string, + page: number, +): Promise<{ items: Obj[]; lastPage: number }> => { + const sep = path.includes("?") ? "&" : "?"; + const full = `${path}${sep}per_page=100&page=${page}`; + return retry(`github api ${full}`, async () => { + const res = await fetch(`https://api.github.com${full}`, { + signal: AbortSignal.timeout(20_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 Error(`github api ${full}: HTTP ${res.status}`); + const link = res.headers.get("link") ?? ""; + const last = /[?&]page=(\d+)>; rel="last"/.exec(link); + return { + items: (await res.json()) as Obj[], + lastPage: last ? Number(last[1]) : page, + }; + }); +}; + +/** Fetch every page of a list endpoint, pages 2..N four at a time. */ const apiAll = async (path: string): Promise => { - const out: Obj[] = []; - for (let page = 1; ; page++) { - const sep = path.includes("?") ? "&" : "?"; - const items = (await api(`${path}${sep}per_page=100&page=${page}`)) as Obj[]; - out.push(...items); - if (items.length < 100) return out; - } + const first = await apiPage(path, 1); + if (first.lastPage <= 1) return first.items; + const pages: Obj[][] = [first.items]; + let next = 2; + const worker = async (): Promise => { + while (next <= first.lastPage) { + const page = next++; + pages[page - 1] = (await apiPage(path, page)).items; + } + }; + await Promise.all([worker(), worker(), worker(), worker()]); + return pages.flat(); }; interface StoredRow { @@ -123,7 +162,11 @@ interface StoredRow { agentNoteId: number | null; } -const storedRows = async (q: Turso, table: string, repo: string): Promise> => { +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, latest_agent_note_id @@ -135,7 +178,11 @@ const storedRows = async (q: Turso, table: string, repo: string): Promise { const c = row[i]; - return !c || c.type === "null" ? null : "value" in c ? String(c.value) : null; + return !c || c.type === "null" + ? null + : "value" in c + ? String(c.value) + : null; }; const number = Number(cell(0)); map.set(number, { @@ -175,8 +222,12 @@ const sweepRepo = async (repo: string): Promise => { 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 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 commentsByNumber = new Map(); for (const item of issueList) { commentsByNumber.set(Number(item.number), Number(item.comments ?? 0) || 0); @@ -189,17 +240,30 @@ const sweepRepo = async (repo: string): Promise => { const stmts: Parameters[1] = []; const changed: { item: Obj; isPr: boolean }[] = []; - const consider = async (item: Obj, isPr: boolean, stored: Map): Promise => { + 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); - if (prev && prev.ghUpdatedAt === String(item.updated_at ?? "") && prev.bodyHash === hash) { + if ( + prev && + prev.ghUpdatedAt === String(item.updated_at ?? "") && + prev.bodyHash === hash + ) { summary.unchanged++; return; } if (isPr) { - const withComments = { ...item, comments: commentsByNumber.get(number) ?? Number(item.comments ?? 0) }; - stmts.push(prUpsertStmt(buildPrRow({ pull_request: withComments }, repo, hash))); + const withComments = { + ...item, + comments: commentsByNumber.get(number) ?? Number(item.comments ?? 0), + }; + stmts.push( + prUpsertStmt(buildPrRow({ pull_request: withComments }, repo, hash)), + ); } else { stmts.push(issueUpsertStmt(buildIssueRow({ issue: item }, repo, hash))); } @@ -222,8 +286,8 @@ const sweepRepo = async (repo: string): Promise => { } } // Flush snapshot writes in bounded batches before pointer work. - for (let i = 0; i < stmts.length; i += 100) { - await sweepBatch(env, stmts.slice(i, i + 100)); + for (let i = 0; i < stmts.length; i += 200) { + await sweepBatch(env, stmts.slice(i, i + 200)); } // Pointer re-derivation for changed items that carry comments, @@ -232,26 +296,44 @@ const sweepRepo = async (repo: string): Promise => { // would exhaust the API budget repairing pointers for items nobody // has touched in years. Deferred items are counted, and any later // change to an item (or a rerun with a raised cap) repairs it. - changed.sort((a, b) => String(b.item.updated_at ?? "").localeCompare(String(a.item.updated_at ?? ""))); + changed.sort((a, b) => + String(b.item.updated_at ?? "").localeCompare( + String(a.item.updated_at ?? ""), + ), + ); let pointerBudget = MAX_POINTER_REPAIRS; for (const { item, isPr } of changed) { const number = Number(item.number); - if ((commentsByNumber.get(number) ?? 0) === 0 && Number(item.comments ?? 0) === 0) continue; + if ( + (commentsByNumber.get(number) ?? 0) === 0 && + Number(item.comments ?? 0) === 0 + ) + continue; if (pointerBudget <= 0) { summary.pointers_deferred++; continue; } pointerBudget--; - const comments = await apiAll(`/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`); + const comments = await apiAll( + `/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`, + ); const stored = (isPr ? storedPrs : storedIssues).get(number); - const latestNote = [...comments].reverse().find((c) => isAgentNote(typeof c.body === "string" ? c.body : null)); + const latestNote = [...comments] + .reverse() + .find((c) => isAgentNote(typeof c.body === "string" ? c.body : null)); if (latestNote) { if (!stored || stored.agentNoteId !== Number(latestNote.id)) { - const touch = buildCommentTouch({ issue: item, comment: latestNote, action: "created" }, repo); + const touch = buildCommentTouch( + { issue: item, comment: latestNote, action: "created" }, + repo, + ); await sweepBatch(env, commentTouchStmts(touch)); summary.pointers_set++; } - } else if (stored?.agentNoteId != null && !comments.some((c) => Number(c.id) === stored.agentNoteId)) { + } else if ( + stored?.agentNoteId != null && + !comments.some((c) => Number(c.id) === stored.agentNoteId) + ) { await sweepBatch(env, [clearAgentNotePointerStmt(repo, number, isPr)]); summary.pointers_cleared++; } @@ -262,7 +344,9 @@ const sweepRepo = async (repo: string): Promise => { }; const MAX_POINTER_REPAIRS = Number( - process.argv.find((a) => a.startsWith("--max-pointer-repairs="))?.split("=")[1] ?? 400, + process.argv + .find((a) => a.startsWith("--max-pointer-repairs=")) + ?.split("=")[1] ?? 400, ); const main = async (): Promise => { From b7d2dd93ee82bb2463584e212480d57b1d6d521a Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 09:18:56 -0600 Subject: [PATCH 5/7] fix(github-ci): disposition PR #10062 review findings on the sweep All nine CodeRabbit findings verified against the code and fixed: (1) pointer repair runs before the snapshot flush and a failed repair excludes its item from the flush, so snapshot equality can never hide unfinished pointer work; (2) PR comment counts keep the issues-list updated_at as their own version (PrRow.comments_gh_updated_at; the upsert CASE now compares the comments version, webhook fallback unchanged); (3) vanished candidates are confirmed 404 via the item endpoint before a permanent tombstone is written; (4) zero-comment items with a stored pointer now clear it; (5) PR comment touches adapt the pulls-list object (discriminator + joined count) so repairs land on the PR table; (6) a deleted stored pointer is cleared before a surviving older note is applied; (7) a pointer to an edited non-note comment is cleared without a deletion marker; (8) clearing records github_mirror_deleted_notes when the comment is truly gone; (9) the clear is conditional on the pointer still naming the inspected comment. 62/62 tests. --- pkgs/github-ci/worker/scripts/backfill.ts | 192 ++++++++++++++------ pkgs/github-ci/worker/src/mirror.ts | 68 +++++-- pkgs/github-ci/worker/test/backfill.test.ts | 42 ++++- 3 files changed, 228 insertions(+), 74 deletions(-) diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts index c302f0b8a6..7b363862f5 100644 --- a/pkgs/github-ci/worker/scripts/backfill.ts +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -37,7 +37,7 @@ import { buildCommentTouch, buildIssueRow, buildPrRow, - clearAgentNotePointerStmt, + clearAgentNotePointerStmts, commentTouchStmts, ensureMirrorSchema, isAgentNote, @@ -154,6 +154,23 @@ const apiAll = async (path: string): Promise => { return pages.flat(); }; +/** 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(20_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; @@ -205,6 +222,8 @@ interface RepoSummary { pointers_set: number; pointers_cleared: number; pointers_deferred: number; + pointers_failed: number; + vanished_skipped_live: number; unchanged: number; error?: string; } @@ -216,9 +235,11 @@ const sweepRepo = async (repo: string): Promise => { prs_seen: 0, upserted: 0, vanished_deleted: 0, + vanished_skipped_live: 0, pointers_set: 0, pointers_cleared: 0, pointers_deferred: 0, + pointers_failed: 0, unchanged: 0, }; const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); @@ -228,6 +249,8 @@ const sweepRepo = async (repo: string): Promise => { 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); @@ -238,8 +261,13 @@ const sweepRepo = async (repo: string): Promise => { summary.issues_seen = pureIssues.length; summary.prs_seen = pullList.length; - const stmts: Parameters[1] = []; - const changed: { item: Obj; isPr: boolean }[] = []; + interface Pending { + number: number; + isPr: boolean; + item: Obj; + stmt: { sql: string; args?: import("../src/turso").TursoArg[] }; + } + const pending: Pending[] = []; const consider = async ( item: Obj, isPr: boolean, @@ -257,88 +285,150 @@ const sweepRepo = async (repo: string): Promise => { return; } 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, }; - stmts.push( - prUpsertStmt(buildPrRow({ pull_request: withComments }, repo, hash)), - ); + pending.push({ + number, + isPr, + item, + stmt: prUpsertStmt( + buildPrRow({ pull_request: withComments }, repo, hash), + ), + }); } else { - stmts.push(issueUpsertStmt(buildIssueRow({ issue: item }, repo, hash))); + pending.push({ + number, + isPr, + item, + stmt: issueUpsertStmt(buildIssueRow({ issue: item }, repo, hash)), + }); } - summary.upserted++; - changed.push({ item, isPr }); }; 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 did - // not return at all — deleted on GitHub while no webhook watched. + // 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)) { - stmts.push(...tombstoneDeleteStmts(repo, number)); + 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++; } } - // Flush snapshot writes in bounded batches before pointer work. - for (let i = 0; i < stmts.length; i += 200) { - await sweepBatch(env, stmts.slice(i, i + 200)); - } - // Pointer re-derivation for changed items that carry comments, - // most recently updated first, capped per run: a first sweep of a - // large repo changes everything, and one comments listing per item - // would exhaust the API budget repairing pointers for items nobody - // has touched in years. Deferred items are counted, and any later - // change to an item (or a rerun with a raised cap) repairs it. - changed.sort((a, b) => - String(b.item.updated_at ?? "").localeCompare( - String(a.item.updated_at ?? ""), - ), - ); + // 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 { item, isPr } of changed) { - const number = Number(item.number); - if ( - (commentsByNumber.get(number) ?? 0) === 0 && - Number(item.comments ?? 0) === 0 - ) - continue; + for (const cand of candidates) { + const { number, isPr, item } = cand; if (pointerBudget <= 0) { summary.pointers_deferred++; continue; } pointerBudget--; - const comments = await apiAll( - `/repos/${repo}/issues/${number}/comments?sort=created&direction=asc`, - ); - const stored = (isPr ? storedPrs : storedIssues).get(number); - const latestNote = [...comments] - .reverse() - .find((c) => isAgentNote(typeof c.body === "string" ? c.body : null)); - if (latestNote) { - if (!stored || stored.agentNoteId !== Number(latestNote.id)) { + 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: item, comment: latestNote, action: "created" }, + { issue: touchIssue, comment: latestNote, action: "created" }, repo, ); await sweepBatch(env, commentTouchStmts(touch)); summary.pointers_set++; } - } else if ( - stored?.agentNoteId != null && - !comments.some((c) => Number(c.id) === stored.agentNoteId) - ) { - await sweepBatch(env, [clearAgentNotePointerStmt(repo, number, isPr)]); - summary.pointers_cleared++; + } 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)); + } + await sweepBatch(env, [backfillStampStmt(repo, queueNow())]); return summary; }; diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index bda841809e..c41b925152 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -185,6 +185,15 @@ 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( @@ -196,6 +205,8 @@ export function buildPrRow( 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"), @@ -421,24 +432,43 @@ export function tombstoneDeleteStmts(repo: string, number: number): Stmt[] { } /** - * Clear a stored agent-note pointer the sweep proved stale: the - * pointed-at comment no longer exists on the item (deleted while the - * webhooks were down — the deletion the comment path would have - * recorded in github_mirror_deleted_notes never arrived). The sweep - * re-derives the surviving latest note separately when one exists. + * Clear a stored agent-note pointer the sweep proved stale — the + * pointed-at comment was deleted, or edited so it is no longer an + * agent note. The clear is CONDITIONAL on the pointer still naming + * the inspected comment: a webhook may have installed a newer note + * after the sweep listed comments, and stale sweep work must never + * erase it. When the comment is gone (not merely edited), its + * deletion is also recorded in github_mirror_deleted_notes, so a + * delayed created/edited delivery of that comment cannot resurrect + * the pointer through the comment path's empty-pointer branch. */ -export function clearAgentNotePointerStmt( +export function clearAgentNotePointerStmts( repo: string, number: number, isPr: boolean, -): Stmt { + noteId: number, + recordDeletion: boolean, +): Stmt[] { const table = isPr ? "github_mirror_pull_requests" : "github_mirror_issues"; - return { - sql: `UPDATE ${table} SET latest_agent_note_id = NULL, - latest_agent_note_url = NULL, mirrored_at = ? - WHERE repo = ? AND number = ?`, - args: [tArg(queueNow()), tArg(repo), iArg(number)], - }; + return [ + ...(recordDeletion + ? [ + { + sql: `INSERT INTO github_mirror_deleted_notes + (repo, number, comment_id, mirrored_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(repo, number, comment_id) DO NOTHING`, + args: [tArg(repo), iArg(number), iArg(noteId), tArg(queueNow())], + }, + ] + : []), + { + sql: `UPDATE ${table} SET latest_agent_note_id = NULL, + latest_agent_note_url = NULL, mirrored_at = ? + WHERE repo = ? AND number = ? AND latest_agent_note_id = ?`, + args: [tArg(queueNow()), tArg(repo), iArg(number), iArg(noteId)], + }, + ]; } /** The issue snapshot upsert as a statement (shared by the webhook path and the sweep). */ @@ -560,15 +590,15 @@ export function prUpsertStmt(row: PrRow): Stmt { head_ref = excluded.head_ref, base_ref = excluded.base_ref, labels = excluded.labels, assignees = excluded.assignees, comments = CASE - WHEN excluded.gh_updated_at IS NULL + WHEN excluded.comments_gh_updated_at IS NULL OR github_mirror_pull_requests.comments_gh_updated_at IS NULL - OR excluded.gh_updated_at >= github_mirror_pull_requests.comments_gh_updated_at + OR excluded.comments_gh_updated_at >= github_mirror_pull_requests.comments_gh_updated_at THEN excluded.comments ELSE github_mirror_pull_requests.comments END, comments_gh_updated_at = CASE - WHEN excluded.gh_updated_at IS NULL + WHEN excluded.comments_gh_updated_at IS NULL OR github_mirror_pull_requests.comments_gh_updated_at IS NULL - OR excluded.gh_updated_at >= github_mirror_pull_requests.comments_gh_updated_at - THEN COALESCE(excluded.gh_updated_at, github_mirror_pull_requests.comments_gh_updated_at) + OR excluded.comments_gh_updated_at >= github_mirror_pull_requests.comments_gh_updated_at + THEN COALESCE(excluded.comments_gh_updated_at, github_mirror_pull_requests.comments_gh_updated_at) ELSE github_mirror_pull_requests.comments_gh_updated_at END, author = excluded.author, html_url = excluded.html_url, @@ -592,7 +622,7 @@ export function prUpsertStmt(row: PrRow): Stmt { tArg(row.labels), tArg(row.assignees), iArg(row.comments), - tArg(row.gh_updated_at), + tArg(row.comments_gh_updated_at), tArg(row.author), tArg(row.html_url), tArg(row.gh_created_at), diff --git a/pkgs/github-ci/worker/test/backfill.test.ts b/pkgs/github-ci/worker/test/backfill.test.ts index c96b5f4cc3..37bd9eb09c 100644 --- a/pkgs/github-ci/worker/test/backfill.test.ts +++ b/pkgs/github-ci/worker/test/backfill.test.ts @@ -4,7 +4,7 @@ import { buildCommentTouch, buildIssueRow, buildPrRow, - clearAgentNotePointerStmt, + clearAgentNotePointerStmts, commentTouchStmts, issueUpsertStmt, prUpsertStmt, @@ -88,15 +88,49 @@ describe("sweep statement builders (#8580 backfill)", () => { expect(stmts[2].sql).toContain("DELETE FROM github_mirror_pull_requests"); }); - it("clear-pointer targets the right table per kind", () => { - expect(clearAgentNotePointerStmt(REPO, 1, false).sql).toContain( + it("clear-pointer is conditional on the inspected note and targets the right table", () => { + const issueStmts = clearAgentNotePointerStmts(REPO, 1, false, 777, false); + expect(issueStmts).toHaveLength(1); + expect(issueStmts[0].sql).toContain( "UPDATE github_mirror_issues SET latest_agent_note_id = NULL", ); - expect(clearAgentNotePointerStmt(REPO, 1, true).sql).toContain( + // Conditional: a newer pointer installed after the sweep's read survives. + expect(issueStmts[0].sql).toContain("latest_agent_note_id = ?"); + expect(issueStmts[0].args?.[3]).toEqual({ type: "integer", value: "777" }); + const prStmts = clearAgentNotePointerStmts(REPO, 1, true, 777, false); + expect(prStmts[0].sql).toContain( "UPDATE github_mirror_pull_requests SET latest_agent_note_id = NULL", ); }); + it("clear-pointer records the deletion marker first when the comment is gone", () => { + const stmts = clearAgentNotePointerStmts(REPO, 1, false, 777, true); + expect(stmts).toHaveLength(2); + expect(stmts[0].sql).toContain("INSERT INTO github_mirror_deleted_notes"); + expect(stmts[0].args?.[2]).toEqual({ type: "integer", value: "777" }); + expect(stmts[1].sql).toContain("UPDATE github_mirror_issues"); + }); + + it("PR comments version comes from comments_updated_at when the sweep joins it", () => { + const joined = { ...prObj, comments_updated_at: "2026-11-11T02:30:00Z" }; + const stmt = prUpsertStmt( + buildPrRow({ pull_request: joined }, REPO, "cafe"), + ); + // Bind 13 is the comments_gh_updated_at slot: the count's own version. + expect(stmt.args?.[13]).toEqual({ + type: "text", + value: "2026-11-11T02:30:00Z", + }); + expect(stmt.sql).toContain( + "excluded.comments_gh_updated_at >= github_mirror_pull_requests.comments_gh_updated_at", + ); + // Without the join field (webhook path) it falls back to updated_at. + const plain = prUpsertStmt( + buildPrRow({ pull_request: prObj }, REPO, "cafe"), + ); + expect(plain.args?.[13]).toEqual({ type: "text", value: prObj.updated_at }); + }); + it("comment touch: plain comment is seed+update; deleted note adds marker+clear", () => { const plain = buildCommentTouch( { From 8a0afa46ecad40487c6973d8b76f0bdd90e9b33f Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 10:14:00 -0600 Subject: [PATCH 6/7] fix(github-ci): sweep diff includes comment counts + force-repair pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drill verification caught it: a comment does not move a PR updated_at, and the first (cursor-truncated) code run had stamped zeroed PR counts under fresh versions, so the (updated_at, body_hash) diff could not see the corruption and the version guard could not repair it. The diff key now includes comments, and a post-flush pass force-sets any count the guard still rejects (forceCommentsStmt, sweep-only). Also: pagination follows Link rel=next verbatim — the issues endpoint is cursor-paginated (no rel=last), which is what truncated the first run; the seen-count summary is what caught that too. 63/63 tests. --- pkgs/github-ci/worker/scripts/backfill.ts | 140 ++++++++++++++------ pkgs/github-ci/worker/src/mirror.ts | 31 +++++ pkgs/github-ci/worker/test/backfill.test.ts | 22 +++ 3 files changed, 150 insertions(+), 43 deletions(-) diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts index 7b363862f5..38fb4583c1 100644 --- a/pkgs/github-ci/worker/scripts/backfill.ts +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -39,6 +39,7 @@ import { buildPrRow, clearAgentNotePointerStmts, commentTouchStmts, + forceCommentsStmt, ensureMirrorSchema, isAgentNote, issueUpsertStmt, @@ -97,7 +98,7 @@ const api = async (path: string): Promise => 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(20_000), + signal: AbortSignal.timeout(60_000), headers: { Authorization: `Bearer ${GH_TOKEN}`, Accept: "application/vnd.github+json", @@ -111,54 +112,53 @@ const api = async (path: string): Promise => return res.json(); }); -/** One list page plus the last page number from the Link header. */ -const apiPage = async ( - path: string, - page: number, -): Promise<{ items: Obj[]; lastPage: number }> => { - const sep = path.includes("?") ? "&" : "?"; - const full = `${path}${sep}per_page=100&page=${page}`; - return retry(`github api ${full}`, async () => { - const res = await fetch(`https://api.github.com${full}`, { - signal: AbortSignal.timeout(20_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 Error(`github api ${full}: HTTP ${res.status}`); - const link = res.headers.get("link") ?? ""; - const last = /[?&]page=(\d+)>; rel="last"/.exec(link); - return { - items: (await res.json()) as Obj[], - lastPage: last ? Number(last[1]) : page, - }; - }); -}; - -/** Fetch every page of a list endpoint, pages 2..N four at a time. */ +/** + * 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 first = await apiPage(path, 1); - if (first.lastPage <= 1) return first.items; - const pages: Obj[][] = [first.items]; - let next = 2; - const worker = async (): Promise => { - while (next <= first.lastPage) { - const page = next++; - pages[page - 1] = (await apiPage(path, page)).items; - } - }; - await Promise.all([worker(), worker(), worker(), worker()]); - return pages.flat(); + 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 Error(`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(20_000), + signal: AbortSignal.timeout(60_000), headers: { Authorization: `Bearer ${GH_TOKEN}`, Accept: "application/vnd.github+json", @@ -223,6 +223,7 @@ interface RepoSummary { pointers_cleared: number; pointers_deferred: number; pointers_failed: number; + counts_forced: number; vanished_skipped_live: number; unchanged: number; error?: string; @@ -240,6 +241,7 @@ const sweepRepo = async (repo: string): Promise => { pointers_cleared: 0, pointers_deferred: 0, pointers_failed: 0, + counts_forced: 0, unchanged: 0, }; const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); @@ -267,6 +269,13 @@ const sweepRepo = async (repo: string): Promise => { item: Obj; stmt: { sql: string; args?: import("../src/turso").TursoArg[] }; } + interface CountRepair { + number: number; + isPr: boolean; + comments: number; + version: string; + } + const countRepairs: CountRepair[] = []; const pending: Pending[] = []; const consider = async ( item: Obj, @@ -276,14 +285,34 @@ const sweepRepo = async (repo: string): 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.bodyHash === hash && + prev.comments === apiComments ) { summary.unchanged++; return; } + if (prev && prev.comments !== apiComments) { + countRepairs.push({ + number, + isPr, + comments: apiComments, + version: isPr + ? String( + issueByNumber.get(number)?.updated_at ?? item.updated_at ?? "", + ) + : String(item.updated_at ?? ""), + }); + } 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 @@ -429,6 +458,31 @@ const sweepRepo = async (repo: string): Promise => { await sweepBatch(env, flush.slice(i, i + 200)); } + // Count-repair pass: re-read every row whose count mismatched at + // diff time; any the version guard still rejected (a wrong count + // carrying a newer stamp) is force-set from the API truth. + 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 && now.comments !== repair.comments) { + await sweepBatch(env, [ + forceCommentsStmt( + repo, + repair.number, + repair.isPr, + repair.comments, + repair.version || null, + ), + ]); + summary.counts_forced++; + } + } + await sweepBatch(env, [backfillStampStmt(repo, queueNow())]); return summary; }; diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index c41b925152..380d25246c 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -442,6 +442,37 @@ export function tombstoneDeleteStmts(repo: string, number: number): Stmt[] { * delayed created/edited delivery of that comment cannot resurrect * the pointer through the comment path's empty-pointer branch. */ +/** + * Sweep-only repair: set a row's comments count + version directly. + * The version guard on the upserts is the right rule for webhooks, + * but it cannot repair a count that a previous sweep wrote with a + * WRONG count under a NEWER version stamp (the 2026-11-14 truncated + * list run stamped pulls-list versions onto zeroed counts). The + * sweep has just read the true count and its true version from the + * API, so it may overwrite unconditionally — this statement is never + * used by a webhook path. + */ +export function forceCommentsStmt( + repo: string, + number: number, + isPr: boolean, + comments: number, + commentsGhUpdatedAt: string | null, +): Stmt { + const table = isPr ? "github_mirror_pull_requests" : "github_mirror_issues"; + return { + sql: `UPDATE ${table} SET comments = ?, comments_gh_updated_at = ?, mirrored_at = ? + WHERE repo = ? AND number = ?`, + args: [ + iArg(comments), + tArg(commentsGhUpdatedAt), + tArg(queueNow()), + tArg(repo), + iArg(number), + ], + }; +} + export function clearAgentNotePointerStmts( repo: string, number: number, diff --git a/pkgs/github-ci/worker/test/backfill.test.ts b/pkgs/github-ci/worker/test/backfill.test.ts index 37bd9eb09c..aa16a4a204 100644 --- a/pkgs/github-ci/worker/test/backfill.test.ts +++ b/pkgs/github-ci/worker/test/backfill.test.ts @@ -6,6 +6,7 @@ import { buildPrRow, clearAgentNotePointerStmts, commentTouchStmts, + forceCommentsStmt, issueUpsertStmt, prUpsertStmt, tombstoneDeleteStmts, @@ -131,6 +132,27 @@ describe("sweep statement builders (#8580 backfill)", () => { expect(plain.args?.[13]).toEqual({ type: "text", value: prObj.updated_at }); }); + it("force-comments targets the right table and binds count + version", () => { + const stmt = forceCommentsStmt( + REPO, + 10056, + true, + 4, + "2026-11-14T14:35:00Z", + ); + expect(stmt.sql).toContain( + "UPDATE github_mirror_pull_requests SET comments = ?", + ); + expect(stmt.args?.[0]).toEqual({ type: "integer", value: "4" }); + expect(stmt.args?.[1]).toEqual({ + type: "text", + value: "2026-11-14T14:35:00Z", + }); + expect(forceCommentsStmt(REPO, 1, false, 0, null).sql).toContain( + "UPDATE github_mirror_issues", + ); + }); + it("comment touch: plain comment is seed+update; deleted note adds marker+clear", () => { const plain = buildCommentTouch( { From ae80231e0729e7c069d56d584ce3058b55f88059 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 10:36:35 -0600 Subject: [PATCH 7/7] fix(github-ci): disposition second CodeRabbit round on PR #10062 All three verified and fixed: (1) retry() no longer retries 4xx (HttpStatusError carries the status; 5xx/transport still retry); (2) a run with failed pointer/count repairs is incomplete - partial progress kept, backfill stamp withheld, repo reported failed so the next run retries the same items; (3) the count force-repair is race-safe: it re-fetches the item count at repair time and the write is guarded on the stored comments version still being the diff-time stamp, so a newer webhook count is never overwritten by an older list count. 63/63 tests. --- pkgs/github-ci/worker/scripts/backfill.ts | 100 ++++++++++++++------ pkgs/github-ci/worker/src/mirror.ts | 14 ++- pkgs/github-ci/worker/test/backfill.test.ts | 13 ++- 3 files changed, 93 insertions(+), 34 deletions(-) diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts index 38fb4583c1..0aaf821dcf 100644 --- a/pkgs/github-ci/worker/scripts/backfill.ts +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -74,12 +74,22 @@ if (!env.TURSO_QUEUE_TOKEN) * 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)); @@ -108,7 +118,11 @@ const api = async (path: string): Promise => }); if (res.status >= 500) throw new Error(`github api ${path}: HTTP ${res.status}`); - if (!res.ok) 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(); }); @@ -139,7 +153,11 @@ const apiAll = async (path: string): Promise => { "User-Agent": "github-ci-mirror-backfill", }, }); - if (!res.ok) throw new Error(`github api ${url}: HTTP ${res.status}`); + 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 { @@ -176,6 +194,7 @@ interface StoredRow { ghUpdatedAt: string | null; bodyHash: string | null; comments: number; + commentsGhUpdatedAt: string | null; agentNoteId: number | null; } @@ -186,7 +205,7 @@ const storedRows = async ( ): Promise> => { const r = await retry(`read ${table}`, () => q.execute( - `SELECT number, gh_updated_at, body_hash, comments, latest_agent_note_id + `SELECT number, gh_updated_at, body_hash, comments, comments_gh_updated_at, latest_agent_note_id FROM ${table} WHERE repo = ?`, [{ type: "text", value: repo }], ), @@ -207,7 +226,8 @@ const storedRows = async ( ghUpdatedAt: cell(1), bodyHash: cell(2), comments: Number(cell(3) ?? 0) || 0, - agentNoteId: cell(4) === null ? null : Number(cell(4)), + commentsGhUpdatedAt: cell(4), + agentNoteId: cell(5) === null ? null : Number(cell(5)), }); } return map; @@ -224,6 +244,8 @@ interface RepoSummary { pointers_deferred: number; pointers_failed: number; counts_forced: number; + counts_repair_failed: number; + incomplete?: boolean; vanished_skipped_live: number; unchanged: number; error?: string; @@ -242,6 +264,7 @@ const sweepRepo = async (repo: string): Promise => { 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); @@ -272,8 +295,8 @@ const sweepRepo = async (repo: string): Promise => { interface CountRepair { number: number; isPr: boolean; - comments: number; - version: string; + /** The stored comments version at diff time — the stamp the repair replaces. */ + guardVersion: string | null; } const countRepairs: CountRepair[] = []; const pending: Pending[] = []; @@ -305,12 +328,7 @@ const sweepRepo = async (repo: string): Promise => { countRepairs.push({ number, isPr, - comments: apiComments, - version: isPr - ? String( - issueByNumber.get(number)?.updated_at ?? item.updated_at ?? "", - ) - : String(item.updated_at ?? ""), + guardVersion: prev.commentsGhUpdatedAt, }); } if (isPr) { @@ -458,9 +476,12 @@ const sweepRepo = async (repo: string): Promise => { await sweepBatch(env, flush.slice(i, i + 200)); } - // Count-repair pass: re-read every row whose count mismatched at - // diff time; any the version guard still rejected (a wrong count - // carrying a newer stamp) is force-set from the API truth. + // 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; @@ -469,21 +490,42 @@ const sweepRepo = async (repo: string): Promise => { : null; for (const repair of countRepairs) { const now = (repair.isPr ? afterPrs : afterIssues)?.get(repair.number); - if (now && now.comments !== repair.comments) { - await sweepBatch(env, [ - forceCommentsStmt( - repo, - repair.number, - repair.isPr, - repair.comments, - repair.version || null, - ), - ]); - summary.counts_forced++; + 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++; } } - await sweepBatch(env, [backfillStampStmt(repo, queueNow())]); + // 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; }; @@ -500,7 +542,9 @@ const main = async (): Promise => { let failures = 0; for (const repo of repos) { try { - console.log(JSON.stringify(await sweepRepo(repo))); + 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) })); diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index 380d25246c..aaaa923f27 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -448,9 +448,13 @@ export function tombstoneDeleteStmts(repo: string, number: number): Stmt[] { * but it cannot repair a count that a previous sweep wrote with a * WRONG count under a NEWER version stamp (the 2026-11-14 truncated * list run stamped pulls-list versions onto zeroed counts). The - * sweep has just read the true count and its true version from the - * API, so it may overwrite unconditionally — this statement is never - * used by a webhook path. + * write is conditional on the stored comments version still being + * the exact stamp the sweep diffed against (guardVersion): if a + * webhook has updated the row since, its version differs and this + * statement is a no-op — a repair never overwrites a newer webhook + * count with an older API count. The sweep re-reads the API count + * immediately before repairing, so the value written is current. + * Never used by a webhook path. */ export function forceCommentsStmt( repo: string, @@ -458,17 +462,19 @@ export function forceCommentsStmt( isPr: boolean, comments: number, commentsGhUpdatedAt: string | null, + guardVersion: string | null, ): Stmt { const table = isPr ? "github_mirror_pull_requests" : "github_mirror_issues"; return { sql: `UPDATE ${table} SET comments = ?, comments_gh_updated_at = ?, mirrored_at = ? - WHERE repo = ? AND number = ?`, + WHERE repo = ? AND number = ? AND comments_gh_updated_at IS ?`, args: [ iArg(comments), tArg(commentsGhUpdatedAt), tArg(queueNow()), tArg(repo), iArg(number), + tArg(guardVersion), ], }; } diff --git a/pkgs/github-ci/worker/test/backfill.test.ts b/pkgs/github-ci/worker/test/backfill.test.ts index aa16a4a204..7f92d1c056 100644 --- a/pkgs/github-ci/worker/test/backfill.test.ts +++ b/pkgs/github-ci/worker/test/backfill.test.ts @@ -132,23 +132,32 @@ describe("sweep statement builders (#8580 backfill)", () => { expect(plain.args?.[13]).toEqual({ type: "text", value: prObj.updated_at }); }); - it("force-comments targets the right table and binds count + version", () => { + it("force-comments targets the right table and is version-guarded", () => { const stmt = forceCommentsStmt( REPO, 10056, true, 4, "2026-11-14T14:35:00Z", + "2026-11-14T15:40:00Z", ); expect(stmt.sql).toContain( "UPDATE github_mirror_pull_requests SET comments = ?", ); + // The write only lands if the stored comments version is still + // the stamp the sweep diffed against — a newer webhook count is + // never overwritten by an older API count. + expect(stmt.sql).toContain("comments_gh_updated_at IS ?"); expect(stmt.args?.[0]).toEqual({ type: "integer", value: "4" }); expect(stmt.args?.[1]).toEqual({ type: "text", value: "2026-11-14T14:35:00Z", }); - expect(forceCommentsStmt(REPO, 1, false, 0, null).sql).toContain( + expect(stmt.args?.[5]).toEqual({ + type: "text", + value: "2026-11-14T15:40:00Z", + }); + expect(forceCommentsStmt(REPO, 1, false, 0, null, null).sql).toContain( "UPDATE github_mirror_issues", ); });