From 7bcace8a8ab21eef073305b224d3cee34ecb4561 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 01:46:37 -0600 Subject: [PATCH 1/8] feat(github-ci): write the #8580 GitHub mirror from the webhook Worker --- pkgs/github-ci/worker/README.md | 16 + pkgs/github-ci/worker/mirror.sql | 42 +++ pkgs/github-ci/worker/src/index.ts | 85 +++++- pkgs/github-ci/worker/src/mirror.ts | 357 ++++++++++++++++++++++ pkgs/github-ci/worker/test/mirror.test.ts | 231 ++++++++++++++ pkgs/github-ci/worker/test/worker.test.ts | 118 ++++++- 6 files changed, 826 insertions(+), 23 deletions(-) create mode 100644 pkgs/github-ci/worker/mirror.sql create mode 100644 pkgs/github-ci/worker/src/mirror.ts create mode 100644 pkgs/github-ci/worker/test/mirror.test.ts diff --git a/pkgs/github-ci/worker/README.md b/pkgs/github-ci/worker/README.md index db8d6bd794..9e2712a1e6 100644 --- a/pkgs/github-ci/worker/README.md +++ b/pkgs/github-ci/worker/README.md @@ -74,3 +74,19 @@ npm run deploy # wrangler deploy (fleet Cloudflare account) Cutover state lives on #5693: deploy dark → replay smoke → one repo-level dual-run webhook → (later, separately) org/App flip. The Edge Function stays deployed as rollback until then. + +## GitHub mirror (#8580) + +Fleet-repo `issues` / `pull_request` / `issue_comment` deliveries also +upsert the GitHub mirror in **fleet-queue** (`src/mirror.ts`; DDL in +`mirror.sql`): `github_mirror_issues` (title, body hash, state, labels, +assignees, comments count, latest agent-note pointer), +`github_mirror_pull_requests` (+ merged, draft, head/base), and +`github_mirror_meta` (per-repo staleness: `last_webhook_at` / +`last_webhook_event` stamped here; `last_backfill_at` stamped by the +backfill/repair sweep). + +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. diff --git a/pkgs/github-ci/worker/mirror.sql b/pkgs/github-ci/worker/mirror.sql new file mode 100644 index 0000000000..a1f2aee00d --- /dev/null +++ b/pkgs/github-ci/worker/mirror.sql @@ -0,0 +1,42 @@ +-- GitHub mirror schema (#8580, fleet unification slice 2). +-- Home: the fleet-queue Turso database. The github-ci Worker ensures +-- these tables idempotently on every mirror write (src/mirror.ts +-- MIRROR_DDL mirrors this file); this file is the human-readable DDL +-- of record and the rebuild starting point. +-- +-- The mirror is a READ MODEL: rebuildable from GitHub by the +-- backfill/repair sweep, never a second truth. github_mirror_meta +-- carries the staleness readout (last webhook, last successful +-- backfill) — it informs readers; it never gates work (#8575). + +CREATE TABLE IF NOT EXISTS github_mirror_issues ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + title TEXT, body_hash TEXT, state TEXT, + labels TEXT NOT NULL DEFAULT '[]', + assignees TEXT NOT NULL DEFAULT '[]', + comments INTEGER NOT NULL DEFAULT 0, + latest_agent_note_id INTEGER, latest_agent_note_url TEXT, + author TEXT, html_url TEXT, + gh_created_at TEXT, gh_updated_at TEXT, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number)); + +CREATE TABLE IF NOT EXISTS github_mirror_pull_requests ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + title TEXT, body_hash TEXT, state TEXT, + merged INTEGER NOT NULL DEFAULT 0, + draft INTEGER NOT NULL DEFAULT 0, + head_sha TEXT, head_ref TEXT, base_ref TEXT, + labels TEXT NOT NULL DEFAULT '[]', + assignees TEXT NOT NULL DEFAULT '[]', + comments INTEGER NOT NULL DEFAULT 0, + latest_agent_note_id INTEGER, latest_agent_note_url TEXT, + author TEXT, html_url TEXT, + gh_created_at TEXT, gh_updated_at TEXT, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number)); + +CREATE TABLE IF NOT EXISTS github_mirror_meta ( + repo TEXT PRIMARY KEY, + last_webhook_at TEXT, last_webhook_event TEXT, + last_backfill_at TEXT); diff --git a/pkgs/github-ci/worker/src/index.ts b/pkgs/github-ci/worker/src/index.ts index 9545ab207f..8946001d67 100644 --- a/pkgs/github-ci/worker/src/index.ts +++ b/pkgs/github-ci/worker/src/index.ts @@ -17,9 +17,12 @@ * - push: advance agent_repo_snapshots.head_sha in fleet-queue * (default-branch pushes only), stamp fetch_source='webhook', * append a 'push' agent event via the #5690 sink. - * - pull_request / issues: append an agent event via the sink - * and set the agent_watermarks key 'dirty:' in - * fleet-queue. + * - pull_request / issues: append an agent event via the sink, + * set the agent_watermarks key 'dirty:' in fleet-queue, + * and upsert the #8580 GitHub mirror row (src/mirror.ts). + * - issue_comment: append an agent event, stamp the watermark, + * and refresh the mirror row's comments count / latest + * agent-note pointer. * - ping: pong. Everything else: 202 ignored. */ import { Turso, iArg, tArg } from "./turso"; @@ -31,6 +34,7 @@ import { stampDirtyWatermark, type SinkEnv, } from "./sink"; +import { mirrorCommentEvent, mirrorIssueEvent, mirrorPrEvent } from "./mirror"; export interface Env extends SinkEnv { GITHUB_WEBHOOK_SECRET: string; @@ -46,8 +50,14 @@ async function hmacHex(secret: string, body: string): Promise { false, ["sign"], ); - const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body)); - return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join(""); + const sig = await crypto.subtle.sign( + "HMAC", + key, + new TextEncoder().encode(body), + ); + return [...new Uint8Array(sig)] + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); } function timingSafeEqual(a: string, b: string): boolean { @@ -66,13 +76,18 @@ function json(body: unknown, status = 200): Response { export default { async fetch(req: Request, env: Env): Promise { - if (req.method === "GET") return new Response("github-ci worker ok", { status: 200 }); - if (req.method !== "POST") return new Response("method not allowed", { status: 405 }); + if (req.method === "GET") + return new Response("github-ci worker ok", { status: 200 }); + if (req.method !== "POST") + return new Response("method not allowed", { status: 405 }); const raw = await req.text(); const secret = env.GITHUB_WEBHOOK_SECRET ?? ""; if (secret) { - const given = (req.headers.get("x-hub-signature-256") ?? "").replace("sha256=", ""); + const given = (req.headers.get("x-hub-signature-256") ?? "").replace( + "sha256=", + "", + ); const expected = await hmacHex(secret, raw); if (!timingSafeEqual(given, expected)) { return new Response("bad signature", { status: 401 }); @@ -101,23 +116,57 @@ export default { const ref = String(payload.ref ?? ""); const payloadDefaultBranch = typeof repo.default_branch === "string" ? repo.default_branch : null; - await advanceSnapshot(env, repoName, after, ref, nowIso, payloadDefaultBranch); + await advanceSnapshot( + env, + repoName, + after, + ref, + nowIso, + payloadDefaultBranch, + ); await appendAgentEvent(env, "push", { repo: repoName, after, ref }); return json({ ok: true, repo: repoName, after }); } // ---------------------------------------- pull_request / issues --- if ((eventType === "pull_request" || eventType === "issues") && isFleet) { - const obj = (payload.pull_request ?? payload.issue ?? {}) as Record; + const obj = (payload.pull_request ?? payload.issue ?? {}) as Record< + string, + unknown + >; const action = String(payload.action ?? ""); const detail = { repo: repoName, action, number: Number(obj.number ?? 0) || null, title: (obj.title as string) ?? null, + label: + ((payload.label as Record | undefined) + ?.name as string) ?? null, }; await appendAgentEvent(env, eventType, detail); await stampDirtyWatermark(env, repoName, eventType, nowIso); + // #8580: the mirror row is the read model; a failed write is + // fatal like the ci_events insert (500 -> GitHub retries). + if (eventType === "issues") + await mirrorIssueEvent(env, payload, repoName); + else await mirrorPrEvent(env, payload, repoName); + return json({ ok: true, repo: repoName, event: eventType }); + } + + // ------------------------------------------------ issue_comment --- + if (eventType === "issue_comment" && isFleet) { + const issue = (payload.issue ?? {}) as Record; + const comment = (payload.comment ?? {}) as Record; + const detail = { + repo: repoName, + action: String(payload.action ?? ""), + number: Number(issue.number ?? 0) || null, + comment_id: Number(comment.id ?? 0) || null, + }; + await appendAgentEvent(env, "issue_comment", detail); + await stampDirtyWatermark(env, repoName, "issue_comment", nowIso); + await mirrorCommentEvent(env, payload, repoName); return json({ ok: true, repo: repoName, event: eventType }); } @@ -136,7 +185,10 @@ export default { if (skipped) { return json({ ok: true, skipped, repo: repoName, run_id: runId }); } - const platform = new Turso(env.TURSO_PLATFORM_URL, env.TURSO_PLATFORM_TOKEN); + const platform = new Turso( + env.TURSO_PLATFORM_URL, + env.TURSO_PLATFORM_TOKEN, + ); await platform.execute( `INSERT OR IGNORE INTO ci_events (received_at, source, event_type, action, repo, workflow_name, workflow_id, run_id, run_attempt, @@ -165,10 +217,17 @@ export default { tArg(row.dedupe_key), ], ); - return json({ ok: true, repo: repoName, run_id: runId, conclusion: row.conclusion }); + return json({ + ok: true, + repo: repoName, + run_id: runId, + conclusion: row.conclusion, + }); } catch (e) { const msg = e instanceof Error ? e.message : String(e); - console.error(`github-ci worker failed (${eventType} ${repoName}): ${msg}`); + console.error( + `github-ci worker failed (${eventType} ${repoName}): ${msg}`, + ); return new Response(`receiver failed: ${msg}`, { status: 500 }); } }, diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts new file mode 100644 index 0000000000..31deeca456 --- /dev/null +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -0,0 +1,357 @@ +/** + * GitHub mirror (#8580, fleet unification slice 2): the read model of + * GitHub issue / PR state inside the fleet-queue database. + * + * The mirror is a READ MODEL, rebuildable from GitHub at any time (the + * backfill/repair sweep reconciles it; webhooks only keep it warm). It + * is never a second truth: no write path reads it to decide anything, + * and staleness never gates work (#8575 ruling) — github_mirror_meta + * exists so readers can SEE the staleness (last_webhook_at stamped + * here, last_backfill_at stamped by the sweep), not act on it. + * + * Writes reuse the typed-args Turso pipeline client and the + * fleet-queue credentials the Worker already holds for snapshots and + * watermarks — no new secrets. Schema is ensured idempotently in the + * same batch as each upsert (CREATE TABLE IF NOT EXISTS; the DDL also + * ships as mirror.sql) so a fresh or rebuilt database self-heals from + * any single webhook delivery. + */ +import { Turso, iArg, tArg, type TursoArg } from "./turso"; +import { queueNow, type SinkEnv } from "./sink"; + +export const MIRROR_DDL: string[] = [ + `CREATE TABLE IF NOT EXISTS github_mirror_issues ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + title TEXT, body_hash TEXT, state TEXT, + labels TEXT NOT NULL DEFAULT '[]', + assignees TEXT NOT NULL DEFAULT '[]', + comments INTEGER NOT NULL DEFAULT 0, + latest_agent_note_id INTEGER, latest_agent_note_url TEXT, + author TEXT, html_url TEXT, + gh_created_at TEXT, gh_updated_at TEXT, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number))`, + `CREATE TABLE IF NOT EXISTS github_mirror_pull_requests ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + title TEXT, body_hash TEXT, state TEXT, + merged INTEGER NOT NULL DEFAULT 0, + draft INTEGER NOT NULL DEFAULT 0, + head_sha TEXT, head_ref TEXT, base_ref TEXT, + labels TEXT NOT NULL DEFAULT '[]', + assignees TEXT NOT NULL DEFAULT '[]', + comments INTEGER NOT NULL DEFAULT 0, + latest_agent_note_id INTEGER, latest_agent_note_url TEXT, + author TEXT, html_url TEXT, + gh_created_at TEXT, gh_updated_at TEXT, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number))`, + `CREATE TABLE IF NOT EXISTS github_mirror_meta ( + repo TEXT PRIMARY KEY, + last_webhook_at TEXT, last_webhook_event TEXT, + last_backfill_at TEXT)`, +]; + +type Obj = Record; + +function str(o: Obj, k: string): string | null { + const v = o[k]; + return typeof v === "string" ? v : null; +} + +function num(o: Obj, k: string): number | null { + const v = Number(o[k] ?? 0); + return Number.isFinite(v) && v !== 0 ? v : null; +} + +/** Label names, sorted — stable JSON so backfill diffs stay clean. */ +export function labelsOf(obj: Obj): string[] { + const raw = Array.isArray(obj.labels) ? obj.labels : []; + return raw + .map((l) => (typeof l === "string" ? l : str((l ?? {}) as Obj, "name"))) + .filter((n): n is string => !!n) + .sort(); +} + +/** 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); + if (logins.length) return logins.sort(); + const one = str((obj.assignee ?? {}) as Obj, "login"); + return one ? [one] : []; +} + +export interface IssueRow { + repo: string; + number: number | null; + title: string | null; + body_hash: string | null; + state: string | null; + labels: string; + assignees: string; + comments: number; + author: string | null; + html_url: string | null; + gh_created_at: string | null; + gh_updated_at: string | null; +} + +export function buildIssueRow( + payload: Obj, + repo: string, + bodyHash: string | null, +): IssueRow { + const issue = (payload.issue ?? {}) as Obj; + return { + repo, + number: num(issue, "number"), + title: str(issue, "title"), + body_hash: bodyHash, + state: str(issue, "state"), + labels: JSON.stringify(labelsOf(issue)), + assignees: JSON.stringify(assigneesOf(issue)), + comments: Number(issue.comments ?? 0) || 0, + author: str((issue.user ?? {}) as Obj, "login"), + html_url: str(issue, "html_url"), + gh_created_at: str(issue, "created_at"), + gh_updated_at: str(issue, "updated_at"), + }; +} + +export interface PrRow extends IssueRow { + merged: number; + draft: number; + head_sha: string | null; + head_ref: string | null; + base_ref: string | null; +} + +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, + 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"), + head_ref: str((pr.head ?? {}) as Obj, "ref"), + base_ref: str((pr.base ?? {}) as Obj, "ref"), + }; +} + +export interface CommentTouch { + repo: string; + number: number | null; + isPr: boolean; + comments: number; + /** Set only when the comment carries the fleet agent-note marker. */ + agentNoteId: number | null; + agentNoteUrl: string | null; +} + +/** 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("")).toBe(true); + expect(isAgentNote("🤖 **Agent note** · hi")).toBe(true); + expect(isAgentNote("ordinary comment")).toBe(false); + expect(isAgentNote(null)).toBe(false); + }); + + it("buildCommentTouch targets PR rows and only notes agent comments", () => { + const note = buildCommentTouch( + { + action: "created", + issue: { number: 8601, comments: 5, pull_request: { url: "x" } }, + comment: { + id: 4242, + html_url: "https://example.invalid/pull/8601#c4242", + body: "🤖 **Agent note** · done\n", + }, + }, + REPO, + ); + expect(note).toMatchObject({ + isPr: true, + number: 8601, + comments: 5, + agentNoteId: 4242, + }); + const plain = buildCommentTouch( + { + action: "created", + issue: { number: 8580, comments: 4 }, + comment: { id: 99, html_url: "u", body: "thanks!" }, + }, + REPO, + ); + expect(plain).toMatchObject({ + isPr: false, + agentNoteId: null, + agentNoteUrl: null, + }); + }); +}); + +describe("mirror writers (#8580)", () => { + it("mirrorIssueEvent ensures schema, upserts the row, stamps meta", async () => { + const stmts = capturePipeline(); + await mirrorIssueEvent(env, issuePayload, REPO); + const sql = stmts.map((s) => s.sql).join("\n"); + expect(sql).toContain("CREATE TABLE IF NOT EXISTS github_mirror_issues"); + expect(sql).toContain("INSERT INTO github_mirror_issues"); + expect(sql).toContain("ON CONFLICT(repo, number) DO UPDATE"); + expect(sql).toContain("INSERT INTO github_mirror_meta"); + const upsert = stmts.find((s) => + s.sql.includes("INSERT INTO github_mirror_issues"), + ); + const values = (upsert?.args ?? []).map((a) => a.value); + expect(values).toContain(REPO); + expect(values).toContain("8580"); + expect(values).toContain('["priority/high","task/small-fix"]'); + // body hash is a real SHA-256 of the payload body + expect( + values.some((v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v)), + ).toBe(true); + }); + + it("mirrorPrEvent upserts the PR row with merged state", async () => { + const stmts = capturePipeline(); + await mirrorPrEvent(env, prPayload, REPO); + const upsert = stmts.find((s) => + s.sql.includes("INSERT INTO github_mirror_pull_requests"), + ); + expect(upsert).toBeDefined(); + const values = (upsert?.args ?? []).map((a) => a.value); + expect(values).toContain("8601"); + expect(values).toContain("abc123"); + expect(values).toContain("main"); + }); + + it("mirrorCommentEvent seeds-then-updates comment fields only", async () => { + const stmts = capturePipeline(); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { number: 8580, comments: 4 }, + comment: { + id: 777, + html_url: "https://example.invalid/issues/8580#c777", + body: "🤖 **Agent note** · checkpoint\n", + }, + repository: { full_name: REPO }, + }, + REPO, + ); + const sql = stmts.map((s) => s.sql).join("\n"); + expect(sql).toContain("ON CONFLICT(repo, number) DO NOTHING"); + expect(sql).toContain("UPDATE github_mirror_issues SET comments"); + expect(sql).toContain("latest_agent_note_id = COALESCE"); + const update = stmts.find((s) => + s.sql.startsWith("UPDATE github_mirror_issues"), + ); + const values = (update?.args ?? []).map((a) => a.value); + expect(values).toContain("777"); + expect(values).toContain("4"); + }); +}); diff --git a/pkgs/github-ci/worker/test/worker.test.ts b/pkgs/github-ci/worker/test/worker.test.ts index a99cd1ee9a..c07bda4192 100644 --- a/pkgs/github-ci/worker/test/worker.test.ts +++ b/pkgs/github-ci/worker/test/worker.test.ts @@ -1,4 +1,9 @@ -import { createExecutionContext, env, fetchMock, waitOnExecutionContext } from "cloudflare:test"; +import { + createExecutionContext, + env, + fetchMock, + waitOnExecutionContext, +} from "cloudflare:test"; import { describe, expect, it, beforeAll, afterEach } from "vitest"; import worker from "../src/index"; @@ -14,17 +19,33 @@ async function sign(body: string): Promise { false, ["sign"], ); - const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body)); - return "sha256=" + [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join(""); + const sig = await crypto.subtle.sign( + "HMAC", + key, + new TextEncoder().encode(body), + ); + return ( + "sha256=" + + [...new Uint8Array(sig)] + .map((b) => b.toString(16).padStart(2, "0")) + .join("") + ); } function tursoOk() { return JSON.stringify({ - results: [{ type: "success", response: { type: "execute", result: { rows: [] } } }, { type: "success" }], + results: [ + { type: "success", response: { type: "execute", result: { rows: [] } } }, + { type: "success" }, + ], }); } -async function post(body: string, event: string, sig?: string): Promise { +async function post( + body: string, + event: string, + sig?: string, +): Promise { const req = new Request("https://github-ci.test/", { method: "POST", headers: { @@ -34,7 +55,10 @@ async function post(body: string, event: string, sig?: string): Promise[1]); + const res = await worker.fetch( + req, + env as unknown as Parameters[1], + ); await waitOnExecutionContext(ctx); return res; } @@ -94,10 +118,15 @@ describe("github-ci worker", () => { }); it("fails the delivery (500) when Turso answers a results-less 200 for the ci_events insert (#6949)", async () => { - fetchMock.get(PLATFORM).intercept({ path: "/v2/pipeline", method: "POST" }).reply(200, "{}"); + fetchMock + .get(PLATFORM) + .intercept({ path: "/v2/pipeline", method: "POST" }) + .reply(200, "{}"); const res = await post(runPayload, "workflow_run", await sign(runPayload)); expect(res.status).toBe(500); - expect(await res.text()).toContain("turso pipeline failed: malformed response"); + expect(await res.text()).toContain( + "turso pipeline failed: malformed response", + ); }); it("skips non-completed runs without touching Turso", async () => { @@ -108,11 +137,15 @@ describe("github-ci worker", () => { }); const res = await post(p, "workflow_run", await sign(p)); expect(res.status).toBe(200); - expect((await res.json()) as { skipped?: string }).toMatchObject({ skipped: "not_completed" }); + expect((await res.json()) as { skipped?: string }).toMatchObject({ + skipped: "not_completed", + }); }); it("ignores unknown events with 202", async () => { - const p = JSON.stringify({ repository: { full_name: "developing-today/code" } }); + const p = JSON.stringify({ + repository: { full_name: "developing-today/code" }, + }); const res = await post(p, "star", await sign(p)); expect(res.status).toBe(202); }); @@ -141,4 +174,69 @@ describe("github-ci worker", () => { expect(all).toContain("INSERT INTO events"); expect(all).toContain("github-webhook"); }); + + it("issues on a fleet repo upserts the #8580 mirror row", async () => { + const seen: string[] = []; + const queueMock = fetchMock.get(QUEUE); + // sink event insert (1) + watermark (1) + mirror batch (1) + for (let i = 0; i < 3; i++) { + queueMock + .intercept({ path: "/v2/pipeline", method: "POST" }) + .reply(200, (opts) => { + seen.push(String(opts.body)); + return tursoOk(); + }); + } + const p = JSON.stringify({ + action: "opened", + issue: { + number: 8580, + title: "Fleet unification slice 2", + body: "mirror everything", + state: "open", + labels: [{ name: "task/small-fix" }], + assignees: [], + comments: 0, + user: { login: "dezren39" }, + html_url: "https://example.invalid/issues/8580", + created_at: "2026-11-11T01:00:00Z", + updated_at: "2026-11-11T01:00:00Z", + }, + repository: { full_name: "developing-today/code" }, + }); + const res = await post(p, "issues", await sign(p)); + expect(res.status).toBe(200); + const all = seen.join("\n"); + expect(all).toContain("INSERT INTO github_mirror_issues"); + expect(all).toContain("INSERT INTO github_mirror_meta"); + expect(all).toContain("Fleet unification slice 2"); + }); + + it("issue_comment refreshes the mirror comments count and agent-note pointer", async () => { + const seen: string[] = []; + const queueMock = fetchMock.get(QUEUE); + for (let i = 0; i < 3; i++) { + queueMock + .intercept({ path: "/v2/pipeline", method: "POST" }) + .reply(200, (opts) => { + seen.push(String(opts.body)); + return tursoOk(); + }); + } + const p = JSON.stringify({ + action: "created", + issue: { number: 8580, comments: 7 }, + comment: { + id: 31337, + html_url: "https://example.invalid/issues/8580#c31337", + body: "🤖 **Agent note** · checkpoint\n", + }, + repository: { full_name: "developing-today/code" }, + }); + const res = await post(p, "issue_comment", await sign(p)); + expect(res.status).toBe(200); + const all = seen.join("\n"); + expect(all).toContain("UPDATE github_mirror_issues SET comments"); + expect(all).toContain("31337"); + }); }); From 4031dbc64f7a258cd5bedc47a4eeac5c7dd52524 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 02:42:19 -0600 Subject: [PATCH 2/8] fix(github-ci-worker): reject stale mirror snapshots; never point at deleted notes (#8580) Codex P2s on PR #8604: webhook delivery order can differ from event order, so issue/PR upserts now refuse a snapshot whose gh_updated_at is older than the stored row (equal re-applies; NULL stored accepts). issue_comment deletions never assign the latest-agent-note pointer, and a stored pointer naming the deleted comment is cleared. Tests: vitest 41/41 (2 new), tsc clean, prettier clean. --- pkgs/github-ci/worker/src/mirror.ts | 46 ++++++++++++-- pkgs/github-ci/worker/test/mirror.test.ts | 75 +++++++++++++++++++++++ 2 files changed, 117 insertions(+), 4 deletions(-) diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index 31deeca456..f693d80975 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -15,6 +15,12 @@ * same batch as each upsert (CREATE TABLE IF NOT EXISTS; the DDL also * ships as mirror.sql) so a fresh or rebuilt database self-heals from * any single webhook delivery. + * + * Webhook delivery order can differ from event order, so the issue/PR + * upserts refuse a snapshot whose gh_updated_at is older than the + * stored row's (an equal timestamp re-applies, keeping redelivery + * idempotent; a NULL stored timestamp — a comment-seeded row — always + * accepts the first full snapshot). */ import { Turso, iArg, tArg, type TursoArg } from "./turso"; import { queueNow, type SinkEnv } from "./sink"; @@ -153,6 +159,13 @@ export interface CommentTouch { /** Set only when the comment carries the fleet agent-note marker. */ agentNoteId: number | null; agentNoteUrl: string | null; + /** + * Set only on a `deleted` delivery whose comment was an agent note: + * the pointer must never be assigned from a deletion, and a stored + * pointer naming this comment is cleared (the sweep re-derives the + * latest surviving note on its next pass). + */ + deletedNoteId: number | null; } /** Agent notes carry the machine marker; the emoji header is the fallback. */ @@ -167,13 +180,15 @@ export function buildCommentTouch(payload: Obj, repo: string): CommentTouch { const issue = (payload.issue ?? {}) as Obj; const comment = (payload.comment ?? {}) as Obj; const note = isAgentNote(str(comment, "body")); + const deleted = payload.action === "deleted"; return { repo, number: num(issue, "number"), isPr: !!issue.pull_request, comments: Number(issue.comments ?? 0) || 0, - agentNoteId: note ? num(comment, "id") : null, - agentNoteUrl: note ? str(comment, "html_url") : null, + agentNoteId: note && !deleted ? num(comment, "id") : null, + agentNoteUrl: note && !deleted ? str(comment, "html_url") : null, + deletedNoteId: note && deleted ? num(comment, "id") : null, }; } @@ -244,7 +259,10 @@ export async function mirrorIssueEvent( author = excluded.author, html_url = excluded.html_url, gh_created_at = excluded.gh_created_at, gh_updated_at = excluded.gh_updated_at, - mirrored_at = excluded.mirrored_at`, + mirrored_at = excluded.mirrored_at + WHERE excluded.gh_updated_at IS NULL + OR github_mirror_issues.gh_updated_at IS NULL + OR excluded.gh_updated_at >= github_mirror_issues.gh_updated_at`, args: [ tArg(row.repo), iArg(row.number), @@ -292,7 +310,10 @@ export async function mirrorPrEvent( html_url = excluded.html_url, gh_created_at = excluded.gh_created_at, gh_updated_at = excluded.gh_updated_at, - mirrored_at = excluded.mirrored_at`, + mirrored_at = excluded.mirrored_at + WHERE excluded.gh_updated_at IS NULL + OR github_mirror_pull_requests.gh_updated_at IS NULL + OR excluded.gh_updated_at >= github_mirror_pull_requests.gh_updated_at`, args: [ tArg(row.repo), iArg(row.number), @@ -353,5 +374,22 @@ export async function mirrorCommentEvent( iArg(touch.number), ], }, + // A deleted agent note never becomes the pointer (above), and a + // stored pointer naming the deleted comment is cleared here. + ...(touch.deletedNoteId !== null + ? [ + { + 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(touch.repo), + iArg(touch.number), + iArg(touch.deletedNoteId), + ], + }, + ] + : []), ]); } diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index 57fed9c976..a91e3a8c8f 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -164,6 +164,40 @@ describe("mirror builders (#8580)", () => { agentNoteUrl: null, }); }); + + it("buildCommentTouch never assigns the note pointer from a deletion", () => { + const deleted = buildCommentTouch( + { + action: "deleted", + issue: { number: 8580, comments: 2 }, + comment: { + id: 555, + html_url: "https://example.invalid/issues/8580#c555", + body: "🤖 **Agent note** · old\n", + }, + }, + REPO, + ); + expect(deleted).toMatchObject({ + agentNoteId: null, + agentNoteUrl: null, + deletedNoteId: 555, + comments: 2, + }); + const created = buildCommentTouch( + { + action: "created", + issue: { number: 8580, comments: 3 }, + comment: { + id: 556, + html_url: "https://example.invalid/issues/8580#c556", + body: "🤖 **Agent note** · new\n", + }, + }, + REPO, + ); + expect(created).toMatchObject({ agentNoteId: 556, deletedNoteId: null }); + }); }); describe("mirror writers (#8580)", () => { @@ -174,6 +208,10 @@ describe("mirror writers (#8580)", () => { expect(sql).toContain("CREATE TABLE IF NOT EXISTS github_mirror_issues"); expect(sql).toContain("INSERT INTO github_mirror_issues"); expect(sql).toContain("ON CONFLICT(repo, number) DO UPDATE"); + // Out-of-order deliveries must not overwrite a newer stored snapshot. + expect(sql).toContain( + "excluded.gh_updated_at >= github_mirror_issues.gh_updated_at", + ); expect(sql).toContain("INSERT INTO github_mirror_meta"); const upsert = stmts.find((s) => s.sql.includes("INSERT INTO github_mirror_issues"), @@ -195,6 +233,9 @@ describe("mirror writers (#8580)", () => { s.sql.includes("INSERT INTO github_mirror_pull_requests"), ); expect(upsert).toBeDefined(); + expect(upsert?.sql).toContain( + "excluded.gh_updated_at >= github_mirror_pull_requests.gh_updated_at", + ); const values = (upsert?.args ?? []).map((a) => a.value); expect(values).toContain("8601"); expect(values).toContain("abc123"); @@ -228,4 +269,38 @@ describe("mirror writers (#8580)", () => { expect(values).toContain("777"); expect(values).toContain("4"); }); + + it("mirrorCommentEvent clears a pointer naming the deleted note", async () => { + const stmts = capturePipeline(); + await mirrorCommentEvent( + env, + { + action: "deleted", + issue: { number: 8580, comments: 2 }, + comment: { + id: 777, + html_url: "https://example.invalid/issues/8580#c777", + body: "🤖 **Agent note** · checkpoint\n", + }, + repository: { full_name: REPO }, + }, + REPO, + ); + const clear = stmts.find((s) => + s.sql.includes("latest_agent_note_id = NULL"), + ); + expect(clear).toBeDefined(); + const clearValues = (clear?.args ?? []).map((a) => a.value); + expect(clearValues).toContain("777"); + expect(clearValues).toContain("8580"); + // The comments update itself assigns no pointer for a deletion: + // its COALESCE note args carry no value. + const update = stmts.find((s) => + s.sql.startsWith("UPDATE github_mirror_issues SET comments"), + ); + const updateValues = (update?.args ?? []).map((a) => a.value); + expect(updateValues).not.toContain( + "https://example.invalid/issues/8580#c777", + ); + }); }); From f9eff4dc9745004bd21c57f02ec546625f278013 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 03:52:33 -0600 Subject: [PATCH 3/8] fix(github-ci-worker): guard agent-note pointer by creation order; delete mirror row on issues deleted (#8580) --- pkgs/github-ci/worker/src/mirror.ts | 38 ++++++++++++++-- pkgs/github-ci/worker/test/mirror.test.ts | 55 ++++++++++++++++++++++- 2 files changed, 88 insertions(+), 5 deletions(-) diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index f693d80975..a524294bb8 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -21,6 +21,13 @@ * stored row's (an equal timestamp re-applies, keeping redelivery * idempotent; a NULL stored timestamp — a comment-seeded row — always * accepts the first full snapshot). + * + * The agent-note pointer follows the same discipline by comment id + * (GitHub comment ids are issued in creation order): an older or + * redelivered note never replaces a newer stored pointer. An issues + * "deleted" delivery removes the mirror row outright: a deleted + * issue must leave the read model, not be re-upserted by its own + * deletion event (projector precedent, #4210). */ import { Turso, iArg, tArg, type TursoArg } from "./turso"; import { queueNow, type SinkEnv } from "./sink"; @@ -241,6 +248,16 @@ export async function mirrorIssueEvent( payload: Obj, repo: string, ): Promise { + if (payload.action === "deleted") { + const issue = (payload.issue ?? {}) as Obj; + await mirrorBatch(env, "issues", repo, [ + { + sql: "DELETE FROM github_mirror_issues WHERE repo = ? AND number = ?", + args: [tArg(repo), iArg(num(issue, "number"))], + }, + ]); + return; + } const row = buildIssueRow( payload, repo, @@ -340,7 +357,10 @@ export async function mirrorPrEvent( /** * Apply an `issue_comment` payload: refresh the comments count and, when - * the comment is an agent note, the latest-agent-note pointer. Only the + * the comment is an agent note, the latest-agent-note pointer — replaced + * only when the incoming note is at least as new as the stored one + * (comment ids are creation order), so a delayed or redelivered older + * note never overwrites the pointer to a newer note. Only the * comment fields move — title/state stay with the issues/PR events and * the backfill sweep. A row the mirror has never seen is seeded minimal * (the sweep fills the rest). @@ -362,13 +382,25 @@ export async function mirrorCommentEvent( }, { sql: `UPDATE ${table} SET comments = ?, mirrored_at = ?, - latest_agent_note_id = COALESCE(?, latest_agent_note_id), - latest_agent_note_url = COALESCE(?, latest_agent_note_url) + latest_agent_note_id = CASE + WHEN ? IS NOT NULL + AND (latest_agent_note_id IS NULL + OR ? >= latest_agent_note_id) + THEN ? ELSE latest_agent_note_id END, + latest_agent_note_url = CASE + WHEN ? IS NOT NULL + AND (latest_agent_note_id IS NULL + OR ? >= latest_agent_note_id) + THEN ? ELSE latest_agent_note_url END WHERE repo = ? AND number = ?`, args: [ iArg(touch.comments), tArg(queueNow()), iArg(touch.agentNoteId), + iArg(touch.agentNoteId), + iArg(touch.agentNoteId), + iArg(touch.agentNoteId), + iArg(touch.agentNoteId), tArg(touch.agentNoteUrl), tArg(touch.repo), iArg(touch.number), diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index a91e3a8c8f..a5d5de59ea 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -261,7 +261,8 @@ describe("mirror writers (#8580)", () => { const sql = stmts.map((s) => s.sql).join("\n"); expect(sql).toContain("ON CONFLICT(repo, number) DO NOTHING"); expect(sql).toContain("UPDATE github_mirror_issues SET comments"); - expect(sql).toContain("latest_agent_note_id = COALESCE"); + expect(sql).toContain("latest_agent_note_id = CASE"); + expect(sql).toContain("OR ? >= latest_agent_note_id"); const update = stmts.find((s) => s.sql.startsWith("UPDATE github_mirror_issues"), ); @@ -270,6 +271,56 @@ describe("mirror writers (#8580)", () => { expect(values).toContain("4"); }); + it("mirrorIssueEvent deletes the row on an issues deleted delivery", async () => { + const stmts = capturePipeline(); + await mirrorIssueEvent( + env, + { ...issuePayload, action: "deleted" }, + REPO, + ); + const sql = stmts.map((s) => s.sql).join("\n"); + // A deleted issue leaves the read model (projector precedent, #4210): + // no upsert of its final snapshot, and the meta stamp still lands. + expect(sql).toContain( + "DELETE FROM github_mirror_issues WHERE repo = ? AND number = ?", + ); + expect(sql).not.toContain("INSERT INTO github_mirror_issues"); + expect(sql).toContain("INSERT INTO github_mirror_meta"); + const del = stmts.find((s) => s.sql.startsWith("DELETE FROM")); + const values = (del?.args ?? []).map((a) => a.value); + expect(values).toContain(REPO); + expect(values).toContain("8580"); + }); + + it("mirrorCommentEvent guards the note pointer by creation order", async () => { + const stmts = capturePipeline(); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { number: 8580, comments: 4 }, + comment: { + id: 777, + html_url: "https://example.invalid/issues/8580#c777", + body: "🤖 **Agent note** · checkpoint\n", + }, + repository: { full_name: REPO }, + }, + REPO, + ); + const update = stmts.find((s) => + s.sql.startsWith("UPDATE github_mirror_issues SET comments"), + ); + // Both pointer fields move only when the incoming note id is at + // least the stored one, so an older redelivery cannot overwrite + // the pointer to a newer note. + expect(update?.sql).toContain("latest_agent_note_id = CASE"); + expect(update?.sql).toContain("latest_agent_note_url = CASE"); + expect(update?.sql).toContain("OR ? >= latest_agent_note_id"); + const values = (update?.args ?? []).map((a) => a.value); + expect(values.filter((v) => v === "777")).toHaveLength(5); + }); + it("mirrorCommentEvent clears a pointer naming the deleted note", async () => { const stmts = capturePipeline(); await mirrorCommentEvent( @@ -294,7 +345,7 @@ describe("mirror writers (#8580)", () => { expect(clearValues).toContain("777"); expect(clearValues).toContain("8580"); // The comments update itself assigns no pointer for a deletion: - // its COALESCE note args carry no value. + // its CASE note args carry no value. const update = stmts.find((s) => s.sql.startsWith("UPDATE github_mirror_issues SET comments"), ); From ae3752a7900411c527bf5da796bd1f8722ebac90 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 04:03:19 -0600 Subject: [PATCH 4/8] fix(github-ci-worker): version mirror comment counts by object updated_at (#8580) --- pkgs/github-ci/worker/src/mirror.ts | 32 +++++++++++++- pkgs/github-ci/worker/test/mirror.test.ts | 52 +++++++++++++++++++++-- pkgs/github-ci/worker/test/worker.test.ts | 2 +- 3 files changed, 80 insertions(+), 6 deletions(-) diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index a524294bb8..a60f63082c 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -28,6 +28,14 @@ * "deleted" delivery removes the mirror row outright: a deleted * issue must leave the read model, not be re-upserted by its own * deletion event (projector precedent, #4210). + * + * Comment counts carry their own version, independent of the pointer + * guard: an issue_comment delivery sets the count only when the + * carrying object's updated_at is at least the stored gh_updated_at, + * and advances gh_updated_at to it — a delayed delivery reporting a + * smaller count cannot regress a newer one. (Same-second deliveries + * share a timestamp and stay arrival-ordered; the backfill sweep is + * the repair path for that residual, as for every mirror field.) */ import { Turso, iArg, tArg, type TursoArg } from "./turso"; import { queueNow, type SinkEnv } from "./sink"; @@ -163,6 +171,8 @@ export interface CommentTouch { number: number | null; isPr: boolean; comments: number; + /** The carrying issue/PR object's updated_at: the count's version. */ + ghUpdatedAt: string | null; /** Set only when the comment carries the fleet agent-note marker. */ agentNoteId: number | null; agentNoteUrl: string | null; @@ -193,6 +203,7 @@ export function buildCommentTouch(payload: Obj, repo: string): CommentTouch { number: num(issue, "number"), isPr: !!issue.pull_request, comments: Number(issue.comments ?? 0) || 0, + ghUpdatedAt: str(issue, "updated_at"), agentNoteId: note && !deleted ? num(comment, "id") : null, agentNoteUrl: note && !deleted ? str(comment, "html_url") : null, deletedNoteId: note && deleted ? num(comment, "id") : null, @@ -360,7 +371,10 @@ export async function mirrorPrEvent( * the comment is an agent note, the latest-agent-note pointer — replaced * only when the incoming note is at least as new as the stored one * (comment ids are creation order), so a delayed or redelivered older - * note never overwrites the pointer to a newer note. Only the + * note never overwrites the pointer to a newer note. The comments + * count is versioned separately (the carrying object's updated_at + * against the stored gh_updated_at), so a delayed delivery cannot + * regress a newer count either. Only the * comment fields move — title/state stay with the issues/PR events and * the backfill sweep. A row the mirror has never seen is seeded minimal * (the sweep fills the rest). @@ -381,7 +395,16 @@ export async function mirrorCommentEvent( args: [tArg(touch.repo), iArg(touch.number), tArg(queueNow())], }, { - sql: `UPDATE ${table} SET comments = ?, mirrored_at = ?, + sql: `UPDATE ${table} SET + comments = CASE + WHEN ? IS NULL OR gh_updated_at IS NULL + OR ? >= gh_updated_at + THEN ? ELSE comments END, + gh_updated_at = CASE + WHEN ? IS NULL OR gh_updated_at IS NULL + OR ? >= gh_updated_at + THEN COALESCE(?, gh_updated_at) ELSE gh_updated_at END, + mirrored_at = ?, latest_agent_note_id = CASE WHEN ? IS NOT NULL AND (latest_agent_note_id IS NULL @@ -394,7 +417,12 @@ export async function mirrorCommentEvent( THEN ? ELSE latest_agent_note_url END WHERE repo = ? AND number = ?`, args: [ + tArg(touch.ghUpdatedAt), + tArg(touch.ghUpdatedAt), iArg(touch.comments), + tArg(touch.ghUpdatedAt), + tArg(touch.ghUpdatedAt), + tArg(touch.ghUpdatedAt), tArg(queueNow()), iArg(touch.agentNoteId), iArg(touch.agentNoteId), diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index a5d5de59ea..0f106880d0 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -260,7 +260,7 @@ describe("mirror writers (#8580)", () => { ); const sql = stmts.map((s) => s.sql).join("\n"); expect(sql).toContain("ON CONFLICT(repo, number) DO NOTHING"); - expect(sql).toContain("UPDATE github_mirror_issues SET comments"); + expect(sql).toContain("UPDATE github_mirror_issues SET"); expect(sql).toContain("latest_agent_note_id = CASE"); expect(sql).toContain("OR ? >= latest_agent_note_id"); const update = stmts.find((s) => @@ -309,7 +309,7 @@ describe("mirror writers (#8580)", () => { REPO, ); const update = stmts.find((s) => - s.sql.startsWith("UPDATE github_mirror_issues SET comments"), + s.sql.startsWith("UPDATE github_mirror_issues SET"), ); // Both pointer fields move only when the incoming note id is at // least the stored one, so an older redelivery cannot overwrite @@ -321,6 +321,52 @@ describe("mirror writers (#8580)", () => { expect(values.filter((v) => v === "777")).toHaveLength(5); }); + it("mirrorCommentEvent versions the count by the object updated_at", async () => { + const stmts = capturePipeline(); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { + number: 8580, + comments: 5, + updated_at: "2026-11-11T04:00:00Z", + }, + comment: { + id: 888, + html_url: "https://example.invalid/issues/8580#c888", + body: "plain comment", + }, + repository: { full_name: REPO }, + }, + REPO, + ); + const update = stmts.find((s) => + s.sql.startsWith("UPDATE github_mirror_issues SET"), + ); + // The count moves only when the carrying object's updated_at is + // at least the stored gh_updated_at, and the version advances + // with it — independently of the agent-note pointer guard. + expect(update?.sql).toContain("comments = CASE"); + expect(update?.sql).toContain("OR ? >= gh_updated_at"); + expect(update?.sql).toContain( + "THEN COALESCE(?, gh_updated_at) ELSE gh_updated_at END", + ); + const values = (update?.args ?? []).map((a) => a.value); + expect(values.filter((v) => v === "2026-11-11T04:00:00Z")).toHaveLength(5); + expect(values).toContain("5"); + // buildCommentTouch carries the version off the issue object. + const touch = buildCommentTouch( + { + action: "created", + issue: { number: 8580, comments: 5, updated_at: "2026-11-11T04:00:00Z" }, + comment: { id: 888, html_url: "u", body: "hi" }, + }, + REPO, + ); + expect(touch.ghUpdatedAt).toBe("2026-11-11T04:00:00Z"); + }); + it("mirrorCommentEvent clears a pointer naming the deleted note", async () => { const stmts = capturePipeline(); await mirrorCommentEvent( @@ -347,7 +393,7 @@ describe("mirror writers (#8580)", () => { // The comments update itself assigns no pointer for a deletion: // its CASE note args carry no value. const update = stmts.find((s) => - s.sql.startsWith("UPDATE github_mirror_issues SET comments"), + s.sql.startsWith("UPDATE github_mirror_issues SET"), ); const updateValues = (update?.args ?? []).map((a) => a.value); expect(updateValues).not.toContain( diff --git a/pkgs/github-ci/worker/test/worker.test.ts b/pkgs/github-ci/worker/test/worker.test.ts index c07bda4192..3ceca1c110 100644 --- a/pkgs/github-ci/worker/test/worker.test.ts +++ b/pkgs/github-ci/worker/test/worker.test.ts @@ -236,7 +236,7 @@ describe("github-ci worker", () => { const res = await post(p, "issue_comment", await sign(p)); expect(res.status).toBe(200); const all = seen.join("\n"); - expect(all).toContain("UPDATE github_mirror_issues SET comments"); + expect(all).toContain("UPDATE github_mirror_issues SET"); expect(all).toContain("31337"); }); }); From 79c4c7fe8178a0c28af9d59c29b39519a615294c Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 05:13:02 -0600 Subject: [PATCH 5/8] fix(github-ci/worker): separate the comment-count version from the snapshot version (#8580) Codex P2 on PR #8604: the comment update advanced gh_updated_at, so a newer comment landing before a delayed older snapshot (e.g. a close) made that snapshot fail the upsert guard and left the mirror stale until backfill. The count now carries its own version column (comments_gh_updated_at): comment events guard and advance only it, snapshot upserts guard snapshot fields against gh_updated_at and move the count only under the count-version guard. Existing databases gain the column via an idempotent pragma_table_info probe + ALTER in mirrorBatch. Verified: worker suite 45/45, tsc + prettier clean, and a behavioral SQLite simulation of the exact SQL (comment-first seeding, delayed close applies without regressing the count, stale deliveries refused). --- pkgs/github-ci/worker/mirror.sql | 2 + pkgs/github-ci/worker/src/mirror.ts | 121 +++++++++++++++++----- pkgs/github-ci/worker/test/mirror.test.ts | 47 ++++++--- pkgs/github-ci/worker/test/worker.test.ts | 9 +- 4 files changed, 136 insertions(+), 43 deletions(-) diff --git a/pkgs/github-ci/worker/mirror.sql b/pkgs/github-ci/worker/mirror.sql index a1f2aee00d..0bfe55ed2a 100644 --- a/pkgs/github-ci/worker/mirror.sql +++ b/pkgs/github-ci/worker/mirror.sql @@ -15,6 +15,7 @@ CREATE TABLE IF NOT EXISTS github_mirror_issues ( labels TEXT NOT NULL DEFAULT '[]', assignees TEXT NOT NULL DEFAULT '[]', comments INTEGER NOT NULL DEFAULT 0, + comments_gh_updated_at TEXT, latest_agent_note_id INTEGER, latest_agent_note_url TEXT, author TEXT, html_url TEXT, gh_created_at TEXT, gh_updated_at TEXT, @@ -30,6 +31,7 @@ CREATE TABLE IF NOT EXISTS github_mirror_pull_requests ( labels TEXT NOT NULL DEFAULT '[]', assignees TEXT NOT NULL DEFAULT '[]', comments INTEGER NOT NULL DEFAULT 0, + comments_gh_updated_at TEXT, latest_agent_note_id INTEGER, latest_agent_note_url TEXT, author TEXT, html_url TEXT, gh_created_at TEXT, gh_updated_at TEXT, diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index a60f63082c..2574d4fd27 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -29,13 +29,19 @@ * issue must leave the read model, not be re-upserted by its own * deletion event (projector precedent, #4210). * - * Comment counts carry their own version, independent of the pointer - * guard: an issue_comment delivery sets the count only when the - * carrying object's updated_at is at least the stored gh_updated_at, - * and advances gh_updated_at to it — a delayed delivery reporting a - * smaller count cannot regress a newer one. (Same-second deliveries - * share a timestamp and stay arrival-ordered; the backfill sweep is - * the repair path for that residual, as for every mirror field.) + * Comment counts carry their own version, stored separately from the + * snapshot version (comments_gh_updated_at, NOT gh_updated_at): an + * issue_comment delivery sets the count only when the carrying + * object's updated_at is at least the stored count version, and + * advances only that column. A comment event therefore never moves + * the snapshot version, so a delayed older full snapshot (e.g. a + * close) is never refused because a newer comment landed first, and + * a comment-seeded row still accepts its first full snapshot. The + * snapshot upserts move the count (and its version) under the same + * count-version guard, so neither writer can regress the other's + * count. (Same-second deliveries share a timestamp and stay + * arrival-ordered; the backfill sweep is the repair path for that + * residual, as for every mirror field.) */ import { Turso, iArg, tArg, type TursoArg } from "./turso"; import { queueNow, type SinkEnv } from "./sink"; @@ -47,6 +53,7 @@ export const MIRROR_DDL: string[] = [ labels TEXT NOT NULL DEFAULT '[]', assignees TEXT NOT NULL DEFAULT '[]', comments INTEGER NOT NULL DEFAULT 0, + comments_gh_updated_at TEXT, latest_agent_note_id INTEGER, latest_agent_note_url TEXT, author TEXT, html_url TEXT, gh_created_at TEXT, gh_updated_at TEXT, @@ -61,6 +68,7 @@ export const MIRROR_DDL: string[] = [ labels TEXT NOT NULL DEFAULT '[]', assignees TEXT NOT NULL DEFAULT '[]', comments INTEGER NOT NULL DEFAULT 0, + comments_gh_updated_at TEXT, latest_agent_note_id INTEGER, latest_agent_note_url TEXT, author TEXT, html_url TEXT, gh_created_at TEXT, gh_updated_at TEXT, @@ -238,6 +246,38 @@ function metaStamp(repo: string, event: string, at: string): Stmt { }; } +const MIRROR_TABLES = ["github_mirror_issues", "github_mirror_pull_requests"]; + +/** + * Idempotent column migration for databases created before + * comments_gh_updated_at existed: CREATE TABLE IF NOT EXISTS cannot + * add a column to an existing table, so probe pragma_table_info and + * ALTER only when a column is absent. A null probe (no COUNT row) + * means the table state is unreadable — skip and let the writes + * surface any real error rather than guessing. + */ +async function ensureMirrorColumns(q: Turso): Promise { + const present = await q.queryText( + `SELECT (SELECT COUNT(*) FROM pragma_table_info('github_mirror_issues') WHERE name = 'comments_gh_updated_at') + + (SELECT COUNT(*) FROM pragma_table_info('github_mirror_pull_requests') WHERE name = 'comments_gh_updated_at')`, + ); + // "2" = both columns present (the steady state); null = the probe + // returned no row, so the table state is unreadable — skip and let + // the writes surface any real error rather than guessing. + if (present === null || present === "2") return; + for (const table of MIRROR_TABLES) { + try { + await q.execute( + `ALTER TABLE ${table} ADD COLUMN comments_gh_updated_at TEXT`, + ); + } catch (e) { + // One table may already carry the column (mixed state); only a + // duplicate-column error is ignorable here. + if (!String(e).includes("duplicate column")) throw e; + } + } +} + async function mirrorBatch( env: SinkEnv, event: string, @@ -246,11 +286,9 @@ async function mirrorBatch( ): Promise { const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); const at = queueNow(); - await q.batch([ - ...MIRROR_DDL.map((sql) => ({ sql })), - ...stmts, - metaStamp(repo, event, at), - ]); + await q.batch(MIRROR_DDL.map((sql) => ({ sql }))); + await ensureMirrorColumns(q); + await q.batch([...stmts, metaStamp(repo, event, at)]); } /** Upsert the issue mirror row from an `issues` webhook payload. */ @@ -277,13 +315,24 @@ export async function mirrorIssueEvent( await mirrorBatch(env, "issues", repo, [ { sql: `INSERT INTO github_mirror_issues (repo, number, title, body_hash, state, - labels, assignees, comments, author, html_url, - gh_created_at, gh_updated_at, mirrored_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + labels, assignees, comments, comments_gh_updated_at, author, + html_url, gh_created_at, gh_updated_at, mirrored_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(repo, number) DO UPDATE SET title = excluded.title, body_hash = excluded.body_hash, state = excluded.state, labels = excluded.labels, - assignees = excluded.assignees, comments = excluded.comments, + assignees = excluded.assignees, + comments = CASE + WHEN excluded.gh_updated_at IS NULL + OR github_mirror_issues.comments_gh_updated_at IS NULL + OR excluded.gh_updated_at >= github_mirror_issues.comments_gh_updated_at + THEN excluded.comments ELSE github_mirror_issues.comments END, + comments_gh_updated_at = CASE + WHEN excluded.gh_updated_at IS NULL + OR github_mirror_issues.comments_gh_updated_at IS NULL + OR excluded.gh_updated_at >= github_mirror_issues.comments_gh_updated_at + THEN COALESCE(excluded.gh_updated_at, github_mirror_issues.comments_gh_updated_at) + ELSE github_mirror_issues.comments_gh_updated_at END, author = excluded.author, html_url = excluded.html_url, gh_created_at = excluded.gh_created_at, gh_updated_at = excluded.gh_updated_at, @@ -300,6 +349,7 @@ export async function mirrorIssueEvent( tArg(row.labels), tArg(row.assignees), iArg(row.comments), + tArg(row.gh_updated_at), tArg(row.author), tArg(row.html_url), tArg(row.gh_created_at), @@ -325,16 +375,27 @@ export async function mirrorPrEvent( { sql: `INSERT INTO github_mirror_pull_requests (repo, number, title, body_hash, state, merged, draft, head_sha, head_ref, base_ref, labels, - assignees, comments, author, html_url, gh_created_at, - gh_updated_at, mirrored_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + assignees, comments, comments_gh_updated_at, author, html_url, + gh_created_at, gh_updated_at, mirrored_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(repo, number) DO UPDATE SET title = excluded.title, body_hash = excluded.body_hash, state = excluded.state, merged = excluded.merged, draft = excluded.draft, head_sha = excluded.head_sha, head_ref = excluded.head_ref, base_ref = excluded.base_ref, labels = excluded.labels, assignees = excluded.assignees, - comments = excluded.comments, author = excluded.author, + comments = CASE + WHEN excluded.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 excluded.comments ELSE github_mirror_pull_requests.comments END, + comments_gh_updated_at = CASE + WHEN excluded.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) + ELSE github_mirror_pull_requests.comments_gh_updated_at END, + author = excluded.author, html_url = excluded.html_url, gh_created_at = excluded.gh_created_at, gh_updated_at = excluded.gh_updated_at, @@ -356,6 +417,7 @@ export async function mirrorPrEvent( tArg(row.labels), tArg(row.assignees), iArg(row.comments), + tArg(row.gh_updated_at), tArg(row.author), tArg(row.html_url), tArg(row.gh_created_at), @@ -373,8 +435,10 @@ export async function mirrorPrEvent( * (comment ids are creation order), so a delayed or redelivered older * note never overwrites the pointer to a newer note. The comments * count is versioned separately (the carrying object's updated_at - * against the stored gh_updated_at), so a delayed delivery cannot - * regress a newer count either. Only the + * against the stored comments_gh_updated_at — the snapshot version + * gh_updated_at is never read or moved here), so a delayed delivery + * cannot regress a newer count and a comment landing before a delayed + * older snapshot cannot make that snapshot look stale. Only the * comment fields move — title/state stay with the issues/PR events and * the backfill sweep. A row the mirror has never seen is seeded minimal * (the sweep fills the rest). @@ -397,13 +461,14 @@ export async function mirrorCommentEvent( { sql: `UPDATE ${table} SET comments = CASE - WHEN ? IS NULL OR gh_updated_at IS NULL - OR ? >= gh_updated_at + WHEN ? IS NULL OR comments_gh_updated_at IS NULL + OR ? >= comments_gh_updated_at THEN ? ELSE comments END, - gh_updated_at = CASE - WHEN ? IS NULL OR gh_updated_at IS NULL - OR ? >= gh_updated_at - THEN COALESCE(?, gh_updated_at) ELSE gh_updated_at END, + comments_gh_updated_at = CASE + WHEN ? IS NULL OR comments_gh_updated_at IS NULL + OR ? >= comments_gh_updated_at + THEN COALESCE(?, comments_gh_updated_at) + ELSE comments_gh_updated_at END, mirrored_at = ?, latest_agent_note_id = CASE WHEN ? IS NOT NULL diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index 0f106880d0..d604299367 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -273,11 +273,7 @@ describe("mirror writers (#8580)", () => { it("mirrorIssueEvent deletes the row on an issues deleted delivery", async () => { const stmts = capturePipeline(); - await mirrorIssueEvent( - env, - { ...issuePayload, action: "deleted" }, - REPO, - ); + await mirrorIssueEvent(env, { ...issuePayload, action: "deleted" }, REPO); const sql = stmts.map((s) => s.sql).join("\n"); // A deleted issue leaves the read model (projector precedent, #4210): // no upsert of its final snapshot, and the meta stamp still lands. @@ -345,13 +341,14 @@ describe("mirror writers (#8580)", () => { s.sql.startsWith("UPDATE github_mirror_issues SET"), ); // The count moves only when the carrying object's updated_at is - // at least the stored gh_updated_at, and the version advances - // with it — independently of the agent-note pointer guard. + // at least the stored COUNT version (comments_gh_updated_at), + // which advances with it — separately from the snapshot version: + // a comment event never reads or moves gh_updated_at, so a newer + // comment cannot make a delayed older snapshot look stale. expect(update?.sql).toContain("comments = CASE"); - expect(update?.sql).toContain("OR ? >= gh_updated_at"); - expect(update?.sql).toContain( - "THEN COALESCE(?, gh_updated_at) ELSE gh_updated_at END", - ); + expect(update?.sql).toContain("OR ? >= comments_gh_updated_at"); + expect(update?.sql).toContain("THEN COALESCE(?, comments_gh_updated_at)"); + expect(update?.sql).not.toMatch(/\n\s+gh_updated_at = CASE/); const values = (update?.args ?? []).map((a) => a.value); expect(values.filter((v) => v === "2026-11-11T04:00:00Z")).toHaveLength(5); expect(values).toContain("5"); @@ -359,7 +356,11 @@ describe("mirror writers (#8580)", () => { const touch = buildCommentTouch( { action: "created", - issue: { number: 8580, comments: 5, updated_at: "2026-11-11T04:00:00Z" }, + issue: { + number: 8580, + comments: 5, + updated_at: "2026-11-11T04:00:00Z", + }, comment: { id: 888, html_url: "u", body: "hi" }, }, REPO, @@ -367,6 +368,28 @@ describe("mirror writers (#8580)", () => { expect(touch.ghUpdatedAt).toBe("2026-11-11T04:00:00Z"); }); + it("snapshot upserts move the count only under the count-version guard", async () => { + const stmts = capturePipeline(); + await mirrorIssueEvent(env, issuePayload, REPO); + const upsert = stmts.find((s) => + s.sql.includes("INSERT INTO github_mirror_issues"), + ); + // The snapshot's count is guarded by the separate count version, + // not the snapshot version: a snapshot older than the newest + // comment still applies its state but cannot regress the count. + expect(upsert?.sql).toContain("comments_gh_updated_at"); + expect(upsert?.sql).toContain("comments = CASE"); + expect(upsert?.sql).toContain( + "OR excluded.gh_updated_at >= github_mirror_issues.comments_gh_updated_at", + ); + const values = (upsert?.args ?? []).map((a) => a.value); + // The count version inserted with a fresh row is the object's + // own updated_at (the count's version at snapshot time). + expect( + values.filter((v) => v === "2026-11-11T02:00:00Z").length, + ).toBeGreaterThan(1); + }); + it("mirrorCommentEvent clears a pointer naming the deleted note", async () => { const stmts = capturePipeline(); await mirrorCommentEvent( diff --git a/pkgs/github-ci/worker/test/worker.test.ts b/pkgs/github-ci/worker/test/worker.test.ts index 3ceca1c110..fe1972dce6 100644 --- a/pkgs/github-ci/worker/test/worker.test.ts +++ b/pkgs/github-ci/worker/test/worker.test.ts @@ -178,8 +178,9 @@ describe("github-ci worker", () => { it("issues on a fleet repo upserts the #8580 mirror row", async () => { const seen: string[] = []; const queueMock = fetchMock.get(QUEUE); - // sink event insert (1) + watermark (1) + mirror batch (1) - for (let i = 0; i < 3; i++) { + // sink event insert (1) + watermark (1) + mirror DDL batch (1) + // + mirror column probe (1) + mirror writes batch (1) + for (let i = 0; i < 5; i++) { queueMock .intercept({ path: "/v2/pipeline", method: "POST" }) .reply(200, (opts) => { @@ -215,7 +216,9 @@ describe("github-ci worker", () => { it("issue_comment refreshes the mirror comments count and agent-note pointer", async () => { const seen: string[] = []; const queueMock = fetchMock.get(QUEUE); - for (let i = 0; i < 3; i++) { + // sink event insert (1) + watermark (1) + mirror DDL batch (1) + // + mirror column probe (1) + mirror writes batch (1) + for (let i = 0; i < 5; i++) { queueMock .intercept({ path: "/v2/pipeline", method: "POST" }) .reply(200, (opts) => { From 83e498454e013e24ab43d3a9467ee78416efeb08 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 06:31:31 -0600 Subject: [PATCH 6/8] fix(github-ci/worker): preserve a tombstone when deleting a mirrored issue (#8580) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex P2 on PR #8604: the issues deleted handler removed the mirror row outright, so a delayed pre-deletion snapshot (or a comment seed) arriving after the deletion recreated the issue in the live mirror until reconciliation. The deletion now also writes a tombstone (github_mirror_tombstones: repo, number, the deleted issue gh_updated_at), and every insertion path — the issue and PR snapshot upserts, the comment seed, and the comment update — carries the guard in SQL (NOT EXISTS over the tombstone with the incoming source version), the mirror spelling of the projector deletionBlocks rule. A strictly newer snapshot passes, so a genuinely recreated issue is not blocked. Verified: vitest 48/48 (new deletionBlocks rule tests, tombstone write test, guard-presence tests for both insertion paths), tsc + prettier clean, and a behavioral SQLite simulation of the exact guarded upsert (pre-deletion snapshot absorbed, newer snapshot admitted). --- pkgs/github-ci/worker/mirror.sql | 11 +++ pkgs/github-ci/worker/src/mirror.ts | 101 ++++++++++++++++++++-- pkgs/github-ci/worker/test/mirror.test.ts | 78 ++++++++++++++++- 3 files changed, 183 insertions(+), 7 deletions(-) diff --git a/pkgs/github-ci/worker/mirror.sql b/pkgs/github-ci/worker/mirror.sql index 0bfe55ed2a..e215bc7642 100644 --- a/pkgs/github-ci/worker/mirror.sql +++ b/pkgs/github-ci/worker/mirror.sql @@ -42,3 +42,14 @@ CREATE TABLE IF NOT EXISTS github_mirror_meta ( repo TEXT PRIMARY KEY, last_webhook_at TEXT, last_webhook_event TEXT, last_backfill_at TEXT); + +-- Deletion tombstones: an issues "deleted" delivery removes the +-- mirror row and records the deleted issue's updated_at here, so a +-- delayed pre-deletion snapshot or comment is absorbed by the +-- marker instead of resurrecting the row (the projector's +-- deletionBlocks rule; Codex P2 on PR #8604). +CREATE TABLE IF NOT EXISTS github_mirror_tombstones ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + gh_updated_at TEXT, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number)); diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index 2574d4fd27..0c7003d997 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -27,7 +27,15 @@ * redelivered note never replaces a newer stored pointer. An issues * "deleted" delivery removes the mirror row outright: a deleted * issue must leave the read model, not be re-upserted by its own - * deletion event (projector precedent, #4210). + * deletion event (projector precedent, #4210). The deletion also + * leaves a tombstone (github_mirror_tombstones, keyed by repo + + * number, carrying the deleted issue's updated_at): a delayed + * pre-deletion snapshot or comment arriving after the deletion is + * absorbed by the marker instead of resurrecting the row, in both + * insertion paths — the snapshot upsert and the comment seed — as + * the projector's deletionBlocks does (Codex P2, PR #8604). A + * snapshot strictly newer than the marker (the issue genuinely + * recreated or restored afterwards) is not blocked. * * Comment counts carry their own version, stored separately from the * snapshot version (comments_gh_updated_at, NOT gh_updated_at): an @@ -78,6 +86,11 @@ export const MIRROR_DDL: string[] = [ repo TEXT PRIMARY KEY, last_webhook_at TEXT, last_webhook_event TEXT, last_backfill_at TEXT)`, + `CREATE TABLE IF NOT EXISTS github_mirror_tombstones ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + gh_updated_at TEXT, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number))`, ]; type Obj = Record; @@ -278,6 +291,42 @@ async function ensureMirrorColumns(q: Turso): Promise { } } +/** + * The tombstone rule (projector deletionBlocks, #6782, carried to + * the mirror by Codex P2 on PR #8604): a deletion marker whose + * version is at or after the incoming item's source version absorbs + * the item. `markerVersion` is null when no marker row exists, and + * the empty string when a marker row exists without a recorded + * version — that marker still absorbs, because the deletion is a + * fact even when its timestamp was not captured. An item whose own + * version is unknown cannot prove it post-dates the deletion, so a + * marker absorbs it too; only a strictly newer source version + * passes. + */ +export function deletionBlocks( + markerVersion: string | null, + sourceUpdatedAt: string | null, +): boolean { + if (markerVersion === null) return false; + if (sourceUpdatedAt === null) return true; + if (markerVersion === "") return true; + return markerVersion >= sourceUpdatedAt; +} + +/** + * The tombstone guard: the SQL spelling of deletionBlocks, embedded + * in every insertion path (the issue and PR snapshot upserts, the + * comment seed, and the comment update). It binds, in order: repo, + * number, source version, source version. Encoding the check in the + * statement itself keeps it atomic with the write it guards — no + * read-then-write window, and no extra pipeline round-trip. + */ +const TOMBSTONE_GUARD_SQL = `NOT EXISTS ( + SELECT 1 FROM github_mirror_tombstones m + WHERE m.repo = ? AND m.number = ? + AND (? IS NULL OR m.gh_updated_at IS NULL + OR m.gh_updated_at >= ?))`; + async function mirrorBatch( env: SinkEnv, event: string, @@ -304,6 +353,23 @@ export async function mirrorIssueEvent( sql: "DELETE FROM github_mirror_issues WHERE repo = ? AND number = ?", args: [tArg(repo), iArg(num(issue, "number"))], }, + { + // The tombstone: evidence of the deletion, carrying the + // deleted issue's version, so a delayed pre-deletion + // delivery cannot resurrect the row (Codex P2, PR #8604). + // A later deletion of a recreated issue refreshes it. + sql: `INSERT INTO github_mirror_tombstones (repo, number, gh_updated_at, mirrored_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(repo, number) DO UPDATE SET + gh_updated_at = excluded.gh_updated_at, + mirrored_at = excluded.mirrored_at`, + args: [ + tArg(repo), + iArg(num(issue, "number")), + tArg(str(issue, "updated_at")), + tArg(queueNow()), + ], + }, ]); return; } @@ -317,7 +383,8 @@ export async function mirrorIssueEvent( sql: `INSERT INTO github_mirror_issues (repo, number, title, body_hash, state, labels, assignees, comments, comments_gh_updated_at, author, html_url, gh_created_at, gh_updated_at, mirrored_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? + WHERE ${TOMBSTONE_GUARD_SQL} ON CONFLICT(repo, number) DO UPDATE SET title = excluded.title, body_hash = excluded.body_hash, state = excluded.state, labels = excluded.labels, @@ -355,6 +422,10 @@ export async function mirrorIssueEvent( tArg(row.gh_created_at), tArg(row.gh_updated_at), tArg(queueNow()), + tArg(row.repo), + iArg(row.number), + tArg(row.gh_updated_at), + tArg(row.gh_updated_at), ], }, ]); @@ -377,7 +448,8 @@ export async function mirrorPrEvent( state, merged, draft, head_sha, head_ref, base_ref, labels, assignees, comments, comments_gh_updated_at, author, html_url, gh_created_at, gh_updated_at, mirrored_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? + WHERE ${TOMBSTONE_GUARD_SQL} ON CONFLICT(repo, number) DO UPDATE SET title = excluded.title, body_hash = excluded.body_hash, state = excluded.state, merged = excluded.merged, @@ -423,6 +495,10 @@ export async function mirrorPrEvent( tArg(row.gh_created_at), tArg(row.gh_updated_at), tArg(queueNow()), + tArg(row.repo), + iArg(row.number), + tArg(row.gh_updated_at), + tArg(row.gh_updated_at), ], }, ]); @@ -454,9 +530,18 @@ export async function mirrorCommentEvent( : "github_mirror_issues"; await mirrorBatch(env, "issue_comment", repo, [ { - sql: `INSERT INTO ${table} (repo, number, mirrored_at) VALUES (?, ?, ?) + sql: `INSERT INTO ${table} (repo, number, mirrored_at) SELECT ?, ?, ? + WHERE ${TOMBSTONE_GUARD_SQL} ON CONFLICT(repo, number) DO NOTHING`, - args: [tArg(touch.repo), iArg(touch.number), tArg(queueNow())], + args: [ + tArg(touch.repo), + iArg(touch.number), + tArg(queueNow()), + tArg(touch.repo), + iArg(touch.number), + tArg(touch.ghUpdatedAt), + tArg(touch.ghUpdatedAt), + ], }, { sql: `UPDATE ${table} SET @@ -480,7 +565,7 @@ export async function mirrorCommentEvent( AND (latest_agent_note_id IS NULL OR ? >= latest_agent_note_id) THEN ? ELSE latest_agent_note_url END - WHERE repo = ? AND number = ?`, + WHERE repo = ? AND number = ? AND ${TOMBSTONE_GUARD_SQL}`, args: [ tArg(touch.ghUpdatedAt), tArg(touch.ghUpdatedAt), @@ -497,6 +582,10 @@ export async function mirrorCommentEvent( tArg(touch.agentNoteUrl), tArg(touch.repo), iArg(touch.number), + tArg(touch.repo), + iArg(touch.number), + tArg(touch.ghUpdatedAt), + tArg(touch.ghUpdatedAt), ], }, // A deleted agent note never becomes the pointer (above), and a diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index d604299367..99f85a8c79 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { buildCommentTouch, buildIssueRow, + deletionBlocks, buildPrRow, isAgentNote, labelsOf, @@ -288,6 +289,80 @@ describe("mirror writers (#8580)", () => { expect(values).toContain("8580"); }); + it("deletionBlocks absorbs items at or before the marker version", () => { + // Oracle: the projector's deletionBlocks rule (#6782) — a + // deletion marker at or after the incoming item's source + // timestamp absorbs the item; only a strictly newer item passes. + expect(deletionBlocks(null, "2026-11-11T02:00:00Z")).toBe(false); + expect(deletionBlocks("2026-11-11T03:00:00Z", "2026-11-11T02:00:00Z")).toBe( + true, + ); + expect(deletionBlocks("2026-11-11T03:00:00Z", "2026-11-11T03:00:00Z")).toBe( + true, + ); + expect(deletionBlocks("2026-11-11T03:00:00Z", "2026-11-11T04:00:00Z")).toBe( + false, + ); + // No provable order: a marker absorbs an unversioned item, and a + // versionless marker still absorbs. + expect(deletionBlocks("2026-11-11T03:00:00Z", null)).toBe(true); + expect(deletionBlocks("", "2026-11-11T02:00:00Z")).toBe(true); + expect(deletionBlocks(null, null)).toBe(false); + }); + + it("mirrorIssueEvent writes a tombstone on an issues deleted delivery", async () => { + const stmts = capturePipeline(); + await mirrorIssueEvent(env, { ...issuePayload, action: "deleted" }, REPO); + const tomb = stmts.find((s) => + s.sql.includes("INSERT INTO github_mirror_tombstones"), + ); + expect(tomb).toBeDefined(); + const values = (tomb?.args ?? []).map((a) => a.value); + expect(values).toContain(REPO); + expect(values).toContain("8580"); + // The marker carries the deleted issue's own updated_at: that is + // the version delayed pre-deletion deliveries are compared to. + expect(values).toContain("2026-11-11T02:00:00Z"); + }); + + it("both insertion paths carry the tombstone guard in SQL", async () => { + // The guard is encoded in the statements themselves (atomic + // with the write), in every path that can create a mirror row: + // the snapshot upsert and the comment seed + update. + let stmts = capturePipeline(); + await mirrorIssueEvent(env, issuePayload, REPO); + const upsert = stmts.find((s) => + s.sql.includes("INSERT INTO github_mirror_issues"), + ); + expect(upsert?.sql).toContain("FROM github_mirror_tombstones"); + expect(upsert?.sql).toContain("m.gh_updated_at >= ?"); + stmts = capturePipeline(); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { + number: 8580, + comments: 4, + updated_at: "2026-11-11T02:00:00Z", + }, + comment: { id: 777, body: "a plain comment" }, + repository: { full_name: REPO }, + }, + REPO, + ); + const seed = stmts.find((s) => + s.sql.includes( + "INSERT INTO github_mirror_issues (repo, number, mirrored_at)", + ), + ); + expect(seed?.sql).toContain("FROM github_mirror_tombstones"); + const update = stmts.find((s) => + s.sql.startsWith("UPDATE github_mirror_issues"), + ); + expect(update?.sql).toContain("FROM github_mirror_tombstones"); + }); + it("mirrorCommentEvent guards the note pointer by creation order", async () => { const stmts = capturePipeline(); await mirrorCommentEvent( @@ -350,7 +425,8 @@ describe("mirror writers (#8580)", () => { expect(update?.sql).toContain("THEN COALESCE(?, comments_gh_updated_at)"); expect(update?.sql).not.toMatch(/\n\s+gh_updated_at = CASE/); const values = (update?.args ?? []).map((a) => a.value); - expect(values.filter((v) => v === "2026-11-11T04:00:00Z")).toHaveLength(5); + // 5 count-version binds (CASE guards + COALESCE) plus 2 in the tombstone guard. + expect(values.filter((v) => v === "2026-11-11T04:00:00Z")).toHaveLength(7); expect(values).toContain("5"); // buildCommentTouch carries the version off the issue object. const touch = buildCommentTouch( From c4327f3c2328398fec710406e3f98392a276d57b Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 08:03:32 -0600 Subject: [PATCH 7/8] fix(github-ci/worker): write the tombstone before deleting the mirrored issue (#8580) Codex P2 x2 on PR #8604: Turso.batch is a sequence of separate executes, not a transaction, so DELETE-then-marker left a window where a delayed pre-deletion delivery could insert after the DELETE and be left in place by the later marker. The deletion batch now writes the tombstone first (guard blocks every later insert) and deletes second (removing any row inserted before the marker). New test pins the statement order. Worker suite 49/49, typecheck clean. --- pkgs/github-ci/worker/src/mirror.ts | 18 ++++++++++++++---- pkgs/github-ci/worker/test/mirror.test.ts | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index 0c7003d997..6bc22ea675 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -348,11 +348,17 @@ export async function mirrorIssueEvent( ): Promise { if (payload.action === "deleted") { const issue = (payload.issue ?? {}) as Obj; + // Order is the fix (Codex P2, PR #8604, two rounds): the + // tombstone is written BEFORE the row is deleted. Turso.batch + // is a sequence of separate executes, not a transaction, so a + // DELETE-then-marker order leaves a window in which a delayed + // pre-deletion delivery can insert after the DELETE but before + // the marker exists — and the later marker then leaves that + // resurrected row in place forever. Marker first closes the + // window: once the marker lands, every insertion path is + // guard-blocked (TOMBSTONE_GUARD_SQL), and the DELETE that + // follows removes any row inserted before the marker landed. await mirrorBatch(env, "issues", repo, [ - { - sql: "DELETE FROM github_mirror_issues WHERE repo = ? AND number = ?", - args: [tArg(repo), iArg(num(issue, "number"))], - }, { // The tombstone: evidence of the deletion, carrying the // deleted issue's version, so a delayed pre-deletion @@ -370,6 +376,10 @@ export async function mirrorIssueEvent( tArg(queueNow()), ], }, + { + sql: "DELETE FROM github_mirror_issues WHERE repo = ? AND number = ?", + args: [tArg(repo), iArg(num(issue, "number"))], + }, ]); return; } diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index 99f85a8c79..51fe16caa4 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -325,6 +325,24 @@ describe("mirror writers (#8580)", () => { expect(values).toContain("2026-11-11T02:00:00Z"); }); + it("the tombstone is written before the row deletion", async () => { + // Oracle (Codex P2, PR #8604): the batch is a sequence of + // separate executes, not a transaction, so the marker must be + // established first — a delayed delivery inserting after the + // marker is guard-blocked, and one inserting before it is + // removed by the DELETE that follows. DELETE-then-marker would + // leave the window between them unguarded. + const stmts = capturePipeline(); + await mirrorIssueEvent(env, { ...issuePayload, action: "deleted" }, REPO); + const tombIdx = stmts.findIndex((s) => + s.sql.includes("INSERT INTO github_mirror_tombstones"), + ); + const delIdx = stmts.findIndex((s) => s.sql.startsWith("DELETE FROM")); + expect(tombIdx).toBeGreaterThanOrEqual(0); + expect(delIdx).toBeGreaterThanOrEqual(0); + expect(tombIdx).toBeLessThan(delIdx); + }); + it("both insertion paths carry the tombstone guard in SQL", async () => { // The guard is encoded in the statements themselves (atomic // with the write), in every path that can create a mirror row: From fe93f711d1f5fac279c219a1be76f48da1ca35cd Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 08:41:48 -0600 Subject: [PATCH 8/8] fix(github-ci/worker): retain per-comment deletion evidence for the agent-note pointer (#8580) --- pkgs/github-ci/worker/mirror.sql | 12 +++++ pkgs/github-ci/worker/src/mirror.ts | 44 ++++++++++++++++++ pkgs/github-ci/worker/test/mirror.test.ts | 55 ++++++++++++++++++++++- 3 files changed, 110 insertions(+), 1 deletion(-) diff --git a/pkgs/github-ci/worker/mirror.sql b/pkgs/github-ci/worker/mirror.sql index e215bc7642..af18f11e8d 100644 --- a/pkgs/github-ci/worker/mirror.sql +++ b/pkgs/github-ci/worker/mirror.sql @@ -53,3 +53,15 @@ CREATE TABLE IF NOT EXISTS github_mirror_tombstones ( gh_updated_at TEXT, mirrored_at TEXT NOT NULL, PRIMARY KEY (repo, number)); + +-- Deleted agent-note markers: an agent note's "deleted" delivery +-- clears the latest-note pointer AND records the comment id here, so +-- a delayed created/edited redelivery of the same comment cannot +-- resurrect the pointer through the empty-pointer branch (Codex P2 +-- on PR #8604). A recreated note always has a new comment id, so a +-- marker never suppresses a live note. +CREATE TABLE IF NOT EXISTS github_mirror_deleted_notes ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + comment_id INTEGER NOT NULL, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number, comment_id)); diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index 6bc22ea675..51d76fdcf2 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -37,6 +37,18 @@ * snapshot strictly newer than the marker (the issue genuinely * recreated or restored afterwards) is not blocked. * + * The agent-note pointer keeps the same per-comment discipline for + * deletions: clearing the pointer on a note's "deleted" delivery is + * not enough, because the clear erases the only ordering state and a + * delayed created/edited redelivery of that same comment would be + * accepted through the empty-pointer branch and resurrect it. A + * deleted delivery therefore also records the comment id in + * github_mirror_deleted_notes, and the pointer CASE refuses any id + * with a marker — statement-local, like the tombstone guard, so the + * check is atomic with the update it guards (Codex P2, PR #8604). + * (A genuinely recreated note always carries a new, higher comment + * id, so the marker can never suppress a live note.) + * * Comment counts carry their own version, stored separately from the * snapshot version (comments_gh_updated_at, NOT gh_updated_at): an * issue_comment delivery sets the count only when the carrying @@ -91,6 +103,11 @@ export const MIRROR_DDL: string[] = [ gh_updated_at TEXT, mirrored_at TEXT NOT NULL, PRIMARY KEY (repo, number))`, + `CREATE TABLE IF NOT EXISTS github_mirror_deleted_notes ( + repo TEXT NOT NULL, number INTEGER NOT NULL, + comment_id INTEGER NOT NULL, + mirrored_at TEXT NOT NULL, + PRIMARY KEY (repo, number, comment_id))`, ]; type Obj = Record; @@ -567,11 +584,17 @@ export async function mirrorCommentEvent( mirrored_at = ?, latest_agent_note_id = CASE WHEN ? IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM github_mirror_deleted_notes d + WHERE d.repo = ? AND d.number = ? AND d.comment_id = ?) AND (latest_agent_note_id IS NULL OR ? >= latest_agent_note_id) THEN ? ELSE latest_agent_note_id END, latest_agent_note_url = CASE WHEN ? IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM github_mirror_deleted_notes d + WHERE d.repo = ? AND d.number = ? AND d.comment_id = ?) AND (latest_agent_note_id IS NULL OR ? >= latest_agent_note_id) THEN ? ELSE latest_agent_note_url END @@ -585,10 +608,16 @@ export async function mirrorCommentEvent( tArg(touch.ghUpdatedAt), tArg(queueNow()), iArg(touch.agentNoteId), + tArg(touch.repo), + iArg(touch.number), iArg(touch.agentNoteId), iArg(touch.agentNoteId), iArg(touch.agentNoteId), iArg(touch.agentNoteId), + tArg(touch.repo), + iArg(touch.number), + iArg(touch.agentNoteId), + iArg(touch.agentNoteId), tArg(touch.agentNoteUrl), tArg(touch.repo), iArg(touch.number), @@ -602,6 +631,21 @@ export async function mirrorCommentEvent( // stored pointer naming the deleted comment is cleared here. ...(touch.deletedNoteId !== null ? [ + { + // Record the deletion itself: a delayed created/edited + // redelivery of this comment must not resurrect the + // pointer through the empty-pointer branch (Codex P2). + sql: `INSERT INTO github_mirror_deleted_notes + (repo, number, comment_id, mirrored_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(repo, number, comment_id) DO NOTHING`, + args: [ + tArg(touch.repo), + iArg(touch.number), + iArg(touch.deletedNoteId), + tArg(queueNow()), + ], + }, { sql: `UPDATE ${table} SET latest_agent_note_id = NULL, latest_agent_note_url = NULL, mirrored_at = ? diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index 51fe16caa4..951870e523 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -407,7 +407,7 @@ describe("mirror writers (#8580)", () => { expect(update?.sql).toContain("latest_agent_note_url = CASE"); expect(update?.sql).toContain("OR ? >= latest_agent_note_id"); const values = (update?.args ?? []).map((a) => a.value); - expect(values.filter((v) => v === "777")).toHaveLength(5); + expect(values.filter((v) => v === "777")).toHaveLength(7); // 5 ordering binds + 2 deleted-note marker guard binds }); it("mirrorCommentEvent versions the count by the object updated_at", async () => { @@ -517,4 +517,57 @@ describe("mirror writers (#8580)", () => { "https://example.invalid/issues/8580#c777", ); }); + + it("a deleted note leaves a marker the pointer CASE consults (Codex P2)", async () => { + const stmts = capturePipeline(); + const noteComment = { + id: 777, + html_url: "https://example.invalid/issues/8580#c777", + body: "🤖 **Agent note** · checkpoint\n", + }; + await mirrorCommentEvent( + env, + { + action: "deleted", + issue: { number: 8580, comments: 2 }, + comment: noteComment, + repository: { full_name: REPO }, + }, + REPO, + ); + // The deletion records a per-comment marker naming the deleted id. + const marker = stmts.find((s) => + s.sql.includes("INSERT INTO github_mirror_deleted_notes"), + ); + expect(marker).toBeDefined(); + const markerValues = (marker?.args ?? []).map((a) => a.value); + expect(markerValues).toContain("777"); + expect(markerValues).toContain("8580"); + // The schema ships with every batch, like the other mirror tables. + const sql = stmts.map((s) => s.sql).join("\n"); + expect(sql).toContain( + "CREATE TABLE IF NOT EXISTS github_mirror_deleted_notes", + ); + // And the pointer assignment itself refuses a marked id, in the + // same statement: a delayed created redelivery of comment 777 + // cannot resurrect the pointer through the empty-pointer branch. + const created = capturePipeline(); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { number: 8580, comments: 3 }, + comment: noteComment, + repository: { full_name: REPO }, + }, + REPO, + ); + const update = created.find((s) => + s.sql.startsWith("UPDATE github_mirror_issues SET"), + ); + expect(update?.sql).toContain("github_mirror_deleted_notes"); + expect(update?.sql).toContain("d.comment_id = ?"); + const updateValues = (update?.args ?? []).map((a) => a.value); + expect(updateValues).toContain("777"); + }); });