diff --git a/pkgs/github-ci/worker/mirror.sql b/pkgs/github-ci/worker/mirror.sql index af18f11e8d..82f519069b 100644 --- a/pkgs/github-ci/worker/mirror.sql +++ b/pkgs/github-ci/worker/mirror.sql @@ -19,6 +19,7 @@ CREATE TABLE IF NOT EXISTS github_mirror_issues ( latest_agent_note_id INTEGER, latest_agent_note_url TEXT, author TEXT, html_url TEXT, gh_created_at TEXT, gh_updated_at TEXT, + parent_number INTEGER, mirrored_at TEXT NOT NULL, PRIMARY KEY (repo, number)); @@ -65,3 +66,28 @@ CREATE TABLE IF NOT EXISTS github_mirror_deleted_notes ( comment_id INTEGER NOT NULL, mirrored_at TEXT NOT NULL, PRIMARY KEY (repo, number, comment_id)); + +-- GitHub-side change history (#14170 Q7; design +-- doc/2026-11-24T07-23-14Z_design_queue-metadata-history §8): one +-- append-only row per observed change the mirror's upserts would +-- otherwise overwrite silently — body edits (hashes only, never +-- bodies), comment-count deltas (counts only, never comment +-- bodies), and sub-issue parent changes (parent_number above is the +-- projection; this table is its change log). kind is one of +-- body_edited | comment_added | comment_removed | +-- comment_count_changed | parent_changed (linked | unlinked | +-- state_changed are reserved vocabulary, not written by Q7). +-- Capture is FAIL-OPEN: a failed history write never fails the +-- mirror upsert it describes, so history reads as "as observed" +-- and the backfill sweep's own diff rows repair missed deliveries. +CREATE TABLE IF NOT EXISTS github_issue_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo TEXT NOT NULL, number INTEGER NOT NULL, + is_pr INTEGER NOT NULL DEFAULT 0, + kind TEXT NOT NULL, + detail TEXT NOT NULL DEFAULT '{}', + actor TEXT, gh_updated_at TEXT, + mirrored_at TEXT NOT NULL); + +CREATE INDEX IF NOT EXISTS github_issue_history_issue + ON github_issue_history(repo, number, id); diff --git a/pkgs/github-ci/worker/scripts/backfill.ts b/pkgs/github-ci/worker/scripts/backfill.ts index a3a85d205d..371c25d824 100644 --- a/pkgs/github-ci/worker/scripts/backfill.ts +++ b/pkgs/github-ci/worker/scripts/backfill.ts @@ -7,11 +7,16 @@ * 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. + * 2. Diff against the stored rows on (gh_updated_at, body_hash, + * comments, parent). 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. For + * items that already had a stored row, the diff also produces + * the #14170 Q7 history rows (body edits, count deltas, parent + * changes) a missed webhook would have written — actor + * "backfill" — flushed fail-open after the snapshots: a failed + * history write never fails the sweep. * 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). @@ -41,11 +46,17 @@ import { commentTouchStmts, forceCommentsStmt, ensureMirrorSchema, + historyInsertStmt, isAgentNote, issueUpsertStmt, mirrorSweepBatch, + parentOf, prUpsertStmt, + snapshotHistory, tombstoneDeleteStmts, + type IssueRow, + type PrRow, + type StoredMirrorRow, } from "../src/mirror"; import { FLEET_REPOS } from "../src/policy"; import { queueNow, type SinkEnv } from "../src/sink"; @@ -175,12 +186,20 @@ interface StoredRow { comments: number; commentsGhUpdatedAt: string | null; agentNoteId: number | null; + /** The sub-issue parent projection; issues table only (null for PRs). */ + parentNumber: number | null; } -const storedRows = async (q: Turso, table: string, repo: string): Promise> => { +const storedRows = async ( + q: Turso, + table: string, + repo: string, + withParent = false, +): Promise> => { const r = await retry(`read ${table}`, () => q.execute( - `SELECT number, gh_updated_at, body_hash, comments, comments_gh_updated_at, latest_agent_note_id + `SELECT number, gh_updated_at, body_hash, comments, comments_gh_updated_at, latest_agent_note_id, + ${withParent ? "parent_number" : "NULL"} FROM ${table} WHERE repo = ?`, [{ type: "text", value: repo }], ), @@ -199,6 +218,7 @@ const storedRows = async (q: Turso, table: string, repo: string): Promise => { pointers_failed: 0, counts_forced: 0, counts_repair_failed: 0, + history_rows: 0, + history_failed: 0, unchanged: 0, }; const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); @@ -248,7 +272,7 @@ const sweepRepo = async (repo: string): Promise => { 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 storedIssues = await storedRows(q, "github_mirror_issues", repo, true); const storedPrs = await storedRows(q, "github_mirror_pull_requests", repo); summary.issues_seen = pureIssues.length; summary.prs_seen = pullList.length; @@ -258,6 +282,8 @@ const sweepRepo = async (repo: string): Promise => { isPr: boolean; item: Obj; stmt: { sql: string; args?: import("../src/turso").TursoArg[] }; + /** Q7 history rows this item's diff implies (empty on first sight). */ + history: { sql: string; args?: import("../src/turso").TursoArg[] }[]; } interface CountRepair { number: number; @@ -271,18 +297,25 @@ 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. + // The diff key is (gh_updated_at, body_hash, comments, parent): + // 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; the + // parent (issues only, #14170 Q7) is in the key because a + // re-parenting can be an issue's only change, and the first + // sweep after Q7 must populate the projection on rows whose + // parent was never observed. const apiComments = isPr ? (commentsByNumber.get(number) ?? Number(item.comments ?? 0)) : Number(item.comments ?? 0); + const parent = isPr ? { known: false, parent: null } : parentOf(item); + const parentMoved = !!prev && parent.known && prev.parentNumber !== parent.parent; if ( prev && prev.ghUpdatedAt === String(item.updated_at ?? "") && prev.bodyHash === hash && - prev.comments === apiComments + prev.comments === apiComments && + !parentMoved ) { summary.unchanged++; return; @@ -294,6 +327,8 @@ const sweepRepo = async (repo: string): Promise => { guardVersion: prev.commentsGhUpdatedAt, }); } + let row: IssueRow | PrRow; + let stmt: Pending["stmt"]; 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 @@ -306,20 +341,31 @@ const sweepRepo = async (repo: string): Promise => { comments: commentsByNumber.get(number) ?? Number(item.comments ?? 0), comments_updated_at: issueObj ? String(issueObj.updated_at ?? "") : undefined, }; - pending.push({ - number, - isPr, - item, - stmt: prUpsertStmt(buildPrRow({ pull_request: withComments }, repo, hash)), - }); + row = buildPrRow({ pull_request: withComments }, repo, hash); + stmt = prUpsertStmt(row as PrRow); } else { - pending.push({ - number, - isPr, - item, - stmt: issueUpsertStmt(buildIssueRow({ issue: item }, repo, hash)), - }); + row = buildIssueRow({ issue: item }, repo, hash); + stmt = issueUpsertStmt(row); + } + // Q7 history for the changes this upsert lands, diffed against + // the stored row exactly as the webhook path diffs (the shared + // snapshotHistory applies the same acceptance rules, so a sweep + // item the upsert's guards would refuse yields no rows). First + // sights (no prev) write none. + let history: Pending["history"] = []; + if (prev) { + const storedView: StoredMirrorRow = { + bodyHash: prev.bodyHash, + comments: prev.comments, + commentsGhUpdatedAt: prev.commentsGhUpdatedAt, + ghUpdatedAt: prev.ghUpdatedAt, + parentNumber: prev.parentNumber, + tombstoneVersion: null, + }; + const countVersion = isPr ? (row as PrRow).comments_gh_updated_at : row.gh_updated_at; + history = snapshotHistory(storedView, row, countVersion, isPr, "backfill").map(historyInsertStmt); } + pending.push({ number, isPr, item, stmt, history }); }; for (const issue of pureIssues) await consider(issue, false, storedIssues); for (const pr of pullList) await consider(pr, true, storedPrs); @@ -401,16 +447,36 @@ const sweepRepo = async (repo: string): Promise => { } } + const historyFlush: Pending["stmt"][] = []; for (const p of pending) { if (!failed.has(p.number)) { flush.push(p.stmt); summary.upserted++; + // History rides only with an upsert that actually flushed: an + // item withheld for a failed pointer repair keeps its diff — + // and its history — eligible for the next run. + historyFlush.push(...p.history); } } for (let i = 0; i < flush.length; i += 200) { await sweepBatch(env, flush.slice(i, i + 200)); } + // Q7 history flush, FAIL-OPEN (design §10.3): history never gates + // the sweep, so a failed history batch is counted and logged, not + // propagated — the repo is not marked incomplete for it. + if (historyFlush.length > 0) { + try { + for (let i = 0; i < historyFlush.length; i += 200) { + await sweepBatch(env, historyFlush.slice(i, i + 200)); + } + summary.history_rows += historyFlush.length; + } catch (e) { + summary.history_failed++; + console.error(`backfill ${repo}: history write failed open: ${String(e)}`); + } + } + // 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 @@ -437,6 +503,25 @@ const sweepRepo = async (repo: string): Promise => { ), ]); summary.counts_forced++; + // The forced count is a change the sweep observed: it gets + // its history row too, fail-open like all history. + try { + await sweepBatch(env, [ + historyInsertStmt({ + repo, + number: repair.number, + isPr: repair.isPr, + kind: "comment_count_changed", + detail: { from: now.comments, to: freshCount }, + actor: "backfill", + ghUpdatedAt: typeof fresh.updated_at === "string" ? fresh.updated_at : null, + }), + ]); + summary.history_rows++; + } catch (e) { + summary.history_failed++; + console.error(`backfill ${repo}: repair history write failed open: ${String(e)}`); + } } } catch { summary.counts_repair_failed++; diff --git a/pkgs/github-ci/worker/src/index.ts b/pkgs/github-ci/worker/src/index.ts index 7c49292989..449469e658 100644 --- a/pkgs/github-ci/worker/src/index.ts +++ b/pkgs/github-ci/worker/src/index.ts @@ -22,13 +22,17 @@ * - issue_comment: append an agent event, stamp the watermark, * and refresh the mirror row's comments count / latest * agent-note pointer. + * - sub_issues: append an agent event, stamp the watermark, and + * move the child issue's parent projection in the mirror + * (#14170 Q7; the projector also records the change in + * github_issue_history, fail-open). * - ping: pong. Everything else: 202 ignored. */ import { readBodyUpTo } from "./body"; import { Turso, iArg, tArg } from "./turso"; import { FLEET_REPOS, buildRunRow, skipReason } from "./policy"; import { advanceSnapshot, appendAgentEvent, queueNow, stampDirtyWatermark, type SinkEnv } from "./sink"; -import { mirrorCommentEvent, mirrorIssueEvent, mirrorPrEvent } from "./mirror"; +import { mirrorCommentEvent, mirrorIssueEvent, mirrorPrEvent, mirrorSubIssueEvent } from "./mirror"; export interface Env extends SinkEnv { GITHUB_WEBHOOK_SECRET: string; @@ -153,6 +157,22 @@ export default { return json({ ok: true, repo: repoName, event: eventType }); } + // --------------------------------------------------- sub_issues --- + if (eventType === "sub_issues" && isFleet) { + const child = (payload.sub_issue ?? {}) as Record; + const parent = (payload.parent_issue ?? {}) as Record; + const detail = { + repo: repoName, + action: String(payload.action ?? ""), + number: Number(child.number ?? 0) || null, + parent: Number(parent.number ?? 0) || null, + }; + await appendAgentEvent(env, "sub_issues", detail); + await stampDirtyWatermark(env, repoName, "sub_issues", nowIso); + await mirrorSubIssueEvent(env, payload, repoName); + return json({ ok: true, repo: repoName, event: eventType }); + } + if (eventType !== "workflow_run") { return new Response(`ignored event ${eventType}`, { status: 202 }); } diff --git a/pkgs/github-ci/worker/src/mirror.ts b/pkgs/github-ci/worker/src/mirror.ts index abf189def0..b2a4d60927 100644 --- a/pkgs/github-ci/worker/src/mirror.ts +++ b/pkgs/github-ci/worker/src/mirror.ts @@ -62,6 +62,24 @@ * 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.) + * + * GitHub-side history (#14170 Q7, design §8): the upserts above + * overwrite body_hash, the comments count, and (for issues) the + * sub-issue parent projection in place, so the projector also + * records what changed in github_issue_history — body_edited + * (hashes only), comment_added / comment_removed / + * comment_count_changed (counts only; the direction kinds only + * when the delivery itself is an issue_comment action), and + * parent_changed. The diff is computed in TS from a pre-upsert + * read, applying the same acceptance rules the upsert SQL encodes + * (deletionBlocks + the version guards, spelled in TS beside their + * SQL twins). Capture is FAIL-OPEN: history rows are written in + * their own batch AFTER the mirror batch lands, inside a catch — + * a killed history write never fails the mirror upsert, and the + * backfill sweep writes its own diff rows for changes whose + * webhook was missed, so history degrades to "as observed", never + * to fiction. First sights write no rows: a row's first observed + * state is a defined start, not a change. */ import { Turso, iArg, tArg, type TursoArg } from "./turso"; import { queueNow, type SinkEnv } from "./sink"; @@ -77,6 +95,7 @@ export const MIRROR_DDL: string[] = [ latest_agent_note_id INTEGER, latest_agent_note_url TEXT, author TEXT, html_url TEXT, gh_created_at TEXT, gh_updated_at TEXT, + parent_number INTEGER, mirrored_at TEXT NOT NULL, PRIMARY KEY (repo, number))`, `CREATE TABLE IF NOT EXISTS github_mirror_pull_requests ( @@ -108,6 +127,16 @@ export const MIRROR_DDL: string[] = [ comment_id INTEGER NOT NULL, mirrored_at TEXT NOT NULL, PRIMARY KEY (repo, number, comment_id))`, + `CREATE TABLE IF NOT EXISTS github_issue_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo TEXT NOT NULL, number INTEGER NOT NULL, + is_pr INTEGER NOT NULL DEFAULT 0, + kind TEXT NOT NULL, + detail TEXT NOT NULL DEFAULT '{}', + actor TEXT, gh_updated_at TEXT, + mirrored_at TEXT NOT NULL)`, + `CREATE INDEX IF NOT EXISTS github_issue_history_issue + ON github_issue_history(repo, number, id)`, ]; type Obj = Record; @@ -140,6 +169,37 @@ export function assigneesOf(obj: Obj): string[] { return one ? [one] : []; } +export interface ParentInfo { + /** + * True when the object states its parent: the field is present + * and either null (no parent) or a parseable URL. An absent or + * unparseable field means the payload does not say — the stored + * projection must stand, never be cleared by silence. + */ + known: boolean; + parent: number | null; + /** The parent's repo (owner/name) parsed from the URL, when named. */ + parentRepo: string | null; +} + +/** + * The sub-issue parent of an issue object, from `parent_issue_url` + * (the REST issue schema field; webhook issue objects and the + * backfill's API objects carry the same shape). A parent can live + * in another repo under the same owner, so the URL is parsed for + * both repo and number; the projection column stores the number + * (design §8.4) and history details carry the repo. + */ +export function parentOf(obj: Obj): ParentInfo { + if (!("parent_issue_url" in obj)) return { known: false, parent: null, parentRepo: null }; + const url = obj.parent_issue_url; + if (url === null) return { known: true, parent: null, parentRepo: null }; + if (typeof url !== "string") return { known: false, parent: null, parentRepo: null }; + const m = /\/repos\/([^/]+\/[^/]+)\/issues\/(\d+)$/.exec(url); + if (!m) return { known: false, parent: null, parentRepo: null }; + return { known: true, parent: Number(m[2]), parentRepo: m[1] }; +} + export interface IssueRow { repo: string; number: number | null; @@ -153,10 +213,21 @@ export interface IssueRow { html_url: string | null; gh_created_at: string | null; gh_updated_at: string | null; + /** + * Sub-issue parent projection (#14170 Q7): parent_number is + * meaningful only when parent_known — an object that does not + * state a parent must not overwrite the stored projection. + * parent_repo is not a column; it rides parent_changed history + * details (a parent may live in another repo). + */ + parent_number: number | null; + parent_known: boolean; + parent_repo: string | null; } export function buildIssueRow(payload: Obj, repo: string, bodyHash: string | null): IssueRow { const issue = (payload.issue ?? {}) as Obj; + const parent = parentOf(issue); return { repo, number: num(issue, "number"), @@ -170,6 +241,9 @@ export function buildIssueRow(payload: Obj, repo: string, bodyHash: string | nul html_url: str(issue, "html_url"), gh_created_at: str(issue, "created_at"), gh_updated_at: str(issue, "updated_at"), + parent_number: parent.parent, + parent_known: parent.known, + parent_repo: parent.parentRepo, }; } @@ -273,24 +347,31 @@ 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. + * comments_gh_updated_at (and, later, parent_number) 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')`, + + (SELECT COUNT(*) FROM pragma_table_info('github_mirror_pull_requests') WHERE name = 'comments_gh_updated_at') + + (SELECT COUNT(*) FROM pragma_table_info('github_mirror_issues') WHERE name = 'parent_number')`, ); - // "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) { + // "3" = every migrated column 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 === "3") return; + const alters: [string, string][] = [ + ...MIRROR_TABLES.map((t): [string, string] => [t, "comments_gh_updated_at TEXT"]), + ["github_mirror_issues", "parent_number INTEGER"], + ]; + for (const [table, column] of alters) { try { - await q.execute(`ALTER TABLE ${table} ADD COLUMN comments_gh_updated_at TEXT`); + await q.execute(`ALTER TABLE ${table} ADD COLUMN ${column}`); } catch (e) { // One table may already carry the column (mixed state); only a // duplicate-column error is ignorable here. @@ -332,6 +413,203 @@ const TOMBSTONE_GUARD_SQL = `NOT EXISTS ( AND (? IS NULL OR m.gh_updated_at IS NULL OR m.gh_updated_at >= ?))`; +function cellText(row: TursoArg[], i: number): string | null { + const c = row[i]; + return !c || c.type === "null" ? null : "value" in c ? String(c.value) : null; +} + +/** + * The stored mirror row as the history diff reads it (#14170 Q7), + * plus the deletion marker for the item: tombstoneVersion is null + * when no marker row exists, and "" when a marker exists without a + * recorded version — deletionBlocks' three-state spelling. + */ +export interface StoredMirrorRow { + bodyHash: string | null; + comments: number; + commentsGhUpdatedAt: string | null; + ghUpdatedAt: string | null; + /** Issues table only; always null for PR rows. */ + parentNumber: number | null; + tombstoneVersion: string | null; +} + +/** + * Read the stored row BEFORE an upsert lands (the upsert overwrites + * exactly the values the history diff compares), in one pipeline + * round-trip with the item's deletion marker. Callers ensure the + * schema first: the read names parent_number, which pre-Q7 + * databases gain only via ensureMirrorColumns. A failed read fails + * the event like any mirror read/write failure — only the history + * WRITE is fail-open (writeHistoryFailOpen). + */ +export async function readStoredMirrorRow( + q: Turso, + isPr: boolean, + repo: string, + number: number, +): Promise { + const table = isPr ? "github_mirror_pull_requests" : "github_mirror_issues"; + const results = await q.batch([ + { + sql: `SELECT body_hash, comments, comments_gh_updated_at, gh_updated_at, + ${isPr ? "NULL" : "parent_number"} + FROM ${table} WHERE repo = ? AND number = ?`, + args: [tArg(repo), iArg(number)], + }, + { + sql: `SELECT gh_updated_at FROM github_mirror_tombstones WHERE repo = ? AND number = ?`, + args: [tArg(repo), iArg(number)], + }, + ]); + const row = results[0]?.response?.result?.rows?.[0]; + if (!row) return null; + const tRow = results[1]?.response?.result?.rows?.[0]; + return { + bodyHash: cellText(row, 0), + comments: Number(cellText(row, 1) ?? 0) || 0, + commentsGhUpdatedAt: cellText(row, 2), + ghUpdatedAt: cellText(row, 3), + parentNumber: cellText(row, 4) === null ? null : Number(cellText(row, 4)), + tombstoneVersion: !tRow ? null : (cellText(tRow, 0) ?? ""), + }; +} + +/** + * The TS spelling of the upserts' version guard (cf. deletionBlocks, + * the other dual-spelled rule): an incoming version applies when it + * is unknown, the stored version is unknown, or it is at least the + * stored version. + */ +function versionAccepts(incoming: string | null, stored: string | null): boolean { + return incoming === null || stored === null || incoming >= stored; +} + +/** The history kinds Q7 writes (design §8; the rest are reserved). */ +export type HistoryKind = + | "body_edited" + | "comment_added" + | "comment_removed" + | "comment_count_changed" + | "parent_changed"; + +export interface HistoryRow { + repo: string; + number: number; + isPr: boolean; + kind: HistoryKind; + detail: Obj; + /** Webhook sender login, or "backfill" for sweep-written rows. */ + actor: string | null; + ghUpdatedAt: string | null; +} + +export function historyInsertStmt(h: HistoryRow): Stmt { + return { + sql: `INSERT INTO github_issue_history + (repo, number, is_pr, kind, detail, actor, gh_updated_at, mirrored_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + args: [ + tArg(h.repo), + iArg(h.number), + iArg(h.isPr ? 1 : 0), + tArg(h.kind), + tArg(JSON.stringify(h.detail)), + tArg(h.actor), + tArg(h.ghUpdatedAt), + tArg(queueNow()), + ], + }; +} + +/** + * The history rows a snapshot upsert implies, or none when the + * upsert itself would be refused (tombstone-blocked or version- + * stale): history never records a change that did not land. The + * count follows its own version guard, exactly as the upsert's + * CASE does — an accepted snapshot can still leave the count (and + * its history) untouched. The parent moves only when the incoming + * object states one (parent_known). + */ +export function snapshotHistory( + stored: StoredMirrorRow, + row: IssueRow, + countVersion: string | null, + isPr: boolean, + actor: string | null, +): HistoryRow[] { + const number = row.number; + if (number === null) return []; + if (deletionBlocks(stored.tombstoneVersion, row.gh_updated_at)) return []; + if (!versionAccepts(row.gh_updated_at, stored.ghUpdatedAt)) return []; + const base = { repo: row.repo, number, isPr, actor, ghUpdatedAt: row.gh_updated_at }; + const out: HistoryRow[] = []; + // Hashes only, never bodies (design §8.1); a first observed hash + // (stored null) is the row's defined start, not an edit. + if (stored.bodyHash !== null && row.body_hash !== null && stored.bodyHash !== row.body_hash) { + out.push({ ...base, kind: "body_edited", detail: { old_hash: stored.bodyHash, new_hash: row.body_hash } }); + } + if (versionAccepts(countVersion, stored.commentsGhUpdatedAt) && stored.comments !== row.comments) { + out.push({ ...base, kind: "comment_count_changed", detail: { from: stored.comments, to: row.comments } }); + } + if (!isPr && row.parent_known && stored.parentNumber !== row.parent_number) { + const detail: Obj = { from: stored.parentNumber, to: row.parent_number }; + if (row.parent_number !== null && row.parent_repo !== null) detail.parent_repo = row.parent_repo; + out.push({ ...base, kind: "parent_changed", detail }); + } + return out; +} + +/** + * The history row an issue_comment delivery implies. Counts only + * (design §8.2): the direction kinds are used because the delivery + * itself names the direction; any other action that moves the + * count is comment_count_changed. A delivery that also moves the + * agent-note pointer carries the note id in the same row's detail + * (pointer moves always coincide with count moves: a new note is + * +1, a deleted note is −1). + */ +export function commentHistory( + stored: StoredMirrorRow, + touch: CommentTouch, + action: string | null, + actor: string | null, +): HistoryRow[] { + const number = touch.number; + if (number === null) return []; + if (deletionBlocks(stored.tombstoneVersion, touch.ghUpdatedAt)) return []; + if (!versionAccepts(touch.ghUpdatedAt, stored.commentsGhUpdatedAt)) return []; + if (stored.comments === touch.comments) return []; + const kind: HistoryKind = + action === "created" ? "comment_added" : action === "deleted" ? "comment_removed" : "comment_count_changed"; + const detail: Obj = { from: stored.comments, to: touch.comments }; + const noteId = touch.agentNoteId ?? touch.deletedNoteId; + if (noteId !== null) detail.agent_note_id = noteId; + return [{ repo: touch.repo, number, isPr: touch.isPr, kind, detail, actor, ghUpdatedAt: touch.ghUpdatedAt }]; +} + +/** + * Write history rows FAIL-OPEN (design §10.3): their own batch, + * after the mirror batch has landed, inside a catch. The mirror + * never gates work and neither does its history — a killed history + * write is logged and dropped, and the backfill sweep's diff rows + * are the repair path. + */ +export async function writeHistoryFailOpen(env: SinkEnv, rows: HistoryRow[]): Promise { + if (rows.length === 0) return; + try { + const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); + await q.batch([...MIRROR_DDL.map((sql) => ({ sql })), ...rows.map(historyInsertStmt)]); + } catch (e) { + console.error(`github mirror: history write failed open (${rows.length} row(s) dropped): ${String(e)}`); + } +} + +/** The webhook sender login, when the payload carries one. */ +function senderOf(payload: Obj): string | null { + return str((payload.sender ?? {}) as Obj, "login"); +} + async function mirrorBatch(env: SinkEnv, event: string, repo: string, stmts: Stmt[]): Promise { const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); const at = queueNow(); @@ -340,6 +618,33 @@ async function mirrorBatch(env: SinkEnv, event: string, repo: string, stmts: Stm await q.batch([...stmts, metaStamp(repo, event, at)]); } +/** + * The Q7 event flow shared by the webhook paths that record + * history: ensure the schema, read the stored row, let the caller + * plan the mirror statements and the history rows from it (the + * sub_issues path's statement choice itself depends on the stored + * row), land the mirror batch, then write the history fail-open. + * Same pipeline shape as mirrorBatch plus the one read — the DDL + * batch and the column probe are shared, not repeated. + */ +async function mirrorEvent( + env: SinkEnv, + event: string, + repo: string, + isPr: boolean, + number: number | null, + plan: (stored: StoredMirrorRow | null) => { stmts: Stmt[]; history: HistoryRow[] }, +): Promise { + const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); + const at = queueNow(); + await q.batch(MIRROR_DDL.map((sql) => ({ sql }))); + await ensureMirrorColumns(q); + const stored = number !== null ? await readStoredMirrorRow(q, isPr, repo, number) : null; + const { stmts, history } = plan(stored); + await q.batch([...stmts, metaStamp(repo, event, at)]); + await writeHistoryFailOpen(env, history); +} + /** * Sweep support (#8580 remainder, task 16834): the backfill/repair * sweep (scripts/backfill.ts) reconciles the mirror from the GitHub @@ -475,13 +780,15 @@ export function issueUpsertStmt(row: IssueRow): Stmt { return { 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) - SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? + html_url, gh_created_at, gh_updated_at, parent_number, mirrored_at) + 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, assignees = excluded.assignees, + parent_number = CASE WHEN ? = 1 THEN ? + ELSE github_mirror_issues.parent_number END, comments = CASE WHEN excluded.gh_updated_at IS NULL OR github_mirror_issues.comments_gh_updated_at IS NULL @@ -514,11 +821,16 @@ export function issueUpsertStmt(row: IssueRow): Stmt { tArg(row.html_url), tArg(row.gh_created_at), tArg(row.gh_updated_at), + iArg(row.parent_number), tArg(queueNow()), tArg(row.repo), iArg(row.number), tArg(row.gh_updated_at), tArg(row.gh_updated_at), + // The parent CASE binds: an object that does not state a + // parent (parent_known = 0) keeps the stored projection. + iArg(row.parent_known ? 1 : 0), + iArg(row.parent_number), ], }; } @@ -558,7 +870,13 @@ export async function mirrorIssueEvent(env: SinkEnv, payload: Obj, repo: string) return; } const row = buildIssueRow(payload, repo, await bodyHashOf((payload.issue ?? {}) as Obj)); - await mirrorBatch(env, "issues", repo, [issueUpsertStmt(row)]); + // Q7 history: the diff is computed from the stored row read + // inside mirrorEvent, before the upsert overwrites the compared + // values; the history write is fail-open (mirrorEvent). + await mirrorEvent(env, "issues", repo, false, row.number, (stored) => ({ + stmts: [issueUpsertStmt(row)], + history: stored ? snapshotHistory(stored, row, row.gh_updated_at, false, senderOf(payload)) : [], + })); } /** The PR snapshot upsert as a statement (shared by the webhook path and the sweep). */ export function prUpsertStmt(row: PrRow): Stmt { @@ -625,7 +943,12 @@ export function prUpsertStmt(row: PrRow): Stmt { /** Upsert the PR mirror row from a `pull_request` webhook payload. */ export async function mirrorPrEvent(env: SinkEnv, payload: Obj, repo: string): Promise { const row = buildPrRow(payload, repo, await bodyHashOf((payload.pull_request ?? {}) as Obj)); - await mirrorBatch(env, "pull_request", repo, [prUpsertStmt(row)]); + // Q7 history, as in mirrorIssueEvent; a PR's count version is its + // own comments_gh_updated_at, and PRs carry no parent projection. + await mirrorEvent(env, "pull_request", repo, true, row.number, (stored) => ({ + stmts: [prUpsertStmt(row)], + history: stored ? snapshotHistory(stored, row, row.comments_gh_updated_at, true, senderOf(payload)) : [], + })); } /** * Apply an `issue_comment` payload: refresh the comments count and, when @@ -744,5 +1067,105 @@ export function commentTouchStmts(touch: CommentTouch): Stmt[] { export async function mirrorCommentEvent(env: SinkEnv, payload: Obj, repo: string): Promise { const touch = buildCommentTouch(payload, repo); - await mirrorBatch(env, "issue_comment", repo, commentTouchStmts(touch)); + // Q7 history, as in mirrorIssueEvent: the count delta is diffed + // against the stored row before the touch lands. A row the mirror + // has never seen is seeded by the touch — a first sight, no row. + await mirrorEvent(env, "issue_comment", repo, touch.isPr, touch.number, (stored) => ({ + stmts: commentTouchStmts(touch), + history: stored ? commentHistory(stored, touch, str(payload, "action"), senderOf(payload)) : [], + })); +} + +/** + * Apply a `sub_issues` webhook delivery (#14170 Q7): the payload + * names both ends of the link — sub_issue is the child, parent_issue + * the parent — so the child's parent_number projection moves + * directly, without waiting for a snapshot or the sweep. (Ordinary + * issues snapshots also refresh the projection, via parent_issue_url + * in the issue object.) Actions parent_issue_added / sub_issue_added + * set the parent; parent_issue_removed / sub_issue_removed clear it; + * anything else (a reprioritization changes order, not parentage) is + * ignored beyond the meta stamp. The projection write is a normal + * mirror write (fatal on failure, like every mirror write); the + * parent_changed history row is fail-open like all history. A child + * the mirror has never seen is seeded minimal with its parent — a + * first sight, so no history row. + */ +export async function mirrorSubIssueEvent(env: SinkEnv, payload: Obj, repo: string): Promise { + const action = str(payload, "action"); + const child = (payload.sub_issue ?? {}) as Obj; + const parent = (payload.parent_issue ?? {}) as Obj; + const childNumber = num(child, "number"); + const added = action === "parent_issue_added" || action === "sub_issue_added"; + const removed = action === "parent_issue_removed" || action === "sub_issue_removed"; + if (childNumber === null || (!added && !removed)) { + await mirrorBatch(env, "sub_issues", repo, []); + return; + } + const newParent = added ? num(parent, "number") : null; + const childVersion = str(child, "updated_at"); + const at = queueNow(); + await mirrorEvent(env, "sub_issues", repo, false, childNumber, (stored) => { + if (stored === null) { + // First sight: seed the row minimal with its parent (the + // sweep fills the rest); the tombstone guard absorbs seeds + // for deleted issues. No history row — a first sight is a + // defined start, not a change. + return { + stmts: [ + { + sql: `INSERT INTO github_mirror_issues (repo, number, parent_number, mirrored_at) + SELECT ?, ?, ?, ? + WHERE ${TOMBSTONE_GUARD_SQL} + ON CONFLICT(repo, number) DO NOTHING`, + args: [ + tArg(repo), + iArg(childNumber), + iArg(newParent), + tArg(at), + tArg(repo), + iArg(childNumber), + tArg(childVersion), + tArg(childVersion), + ], + }, + ], + history: [], + }; + } + return { + stmts: [ + { + sql: `UPDATE github_mirror_issues SET parent_number = ?, mirrored_at = ? + WHERE repo = ? AND number = ? AND parent_number IS NOT ? + AND ${TOMBSTONE_GUARD_SQL}`, + args: [ + iArg(newParent), + tArg(at), + tArg(repo), + iArg(childNumber), + iArg(newParent), + tArg(repo), + iArg(childNumber), + tArg(childVersion), + tArg(childVersion), + ], + }, + ], + history: + stored.parentNumber !== newParent && !deletionBlocks(stored.tombstoneVersion, childVersion) + ? [ + { + repo, + number: childNumber, + isPr: false, + kind: "parent_changed" as const, + detail: { from: stored.parentNumber, to: newParent }, + actor: senderOf(payload), + ghUpdatedAt: childVersion, + }, + ] + : [], + }; + }); } diff --git a/pkgs/github-ci/worker/test/backfill.test.ts b/pkgs/github-ci/worker/test/backfill.test.ts index 90e8e6f834..16dcc3fce3 100644 --- a/pkgs/github-ci/worker/test/backfill.test.ts +++ b/pkgs/github-ci/worker/test/backfill.test.ts @@ -46,12 +46,33 @@ describe("sweep statement builders (#8580 backfill)", () => { expect(stmt.sql).toContain("INSERT INTO github_mirror_issues"); expect(stmt.sql).toContain("NOT EXISTS"); expect(stmt.sql).toContain("github_mirror_tombstones"); - // 14 row fields + mirrored_at is among them; 4 guard binds follow. - expect(stmt.args).toHaveLength(18); + // 15 insert values (14 row fields + parent_number; mirrored_at + // is among them), then 4 guard binds, then the 2 parent CASE + // binds (#14170 Q7). + expect(stmt.args).toHaveLength(21); expect(stmt.args?.[0]).toEqual({ type: "text", value: REPO }); expect(stmt.args?.[1]).toEqual({ type: "integer", value: "8580" }); }); + it("issue upsert binds the sub-issue parent only when the object states one (#14170 Q7)", () => { + // No parent_issue_url: parent_known bind is 0 and the CASE in + // the upsert keeps the stored projection untouched. + const silent = issueUpsertStmt(buildIssueRow({ issue: issueObj }, REPO, "deadbeef")); + expect(silent.sql).toContain("parent_number = CASE WHEN ? = 1 THEN ?"); + expect(silent.args?.[19]).toEqual({ type: "integer", value: "0" }); + // A stated parent (the sweep's API objects carry + // parent_issue_url) binds known=1 and the parent number, in + // both the insert values (13) and the CASE (20). + const withParent = { + ...issueObj, + parent_issue_url: "https://api.github.com/repos/developing-today/code/issues/20", + }; + const stmt = issueUpsertStmt(buildIssueRow({ issue: withParent }, REPO, "deadbeef")); + expect(stmt.args?.[13]).toEqual({ type: "integer", value: "20" }); + expect(stmt.args?.[19]).toEqual({ type: "integer", value: "1" }); + expect(stmt.args?.[20]).toEqual({ type: "integer", value: "20" }); + }); + it("PR upsert binds merged/head/base and the guard", () => { const stmt = prUpsertStmt(buildPrRow({ pull_request: prObj }, REPO, "cafe")); expect(stmt.sql).toContain("INSERT INTO github_mirror_pull_requests"); diff --git a/pkgs/github-ci/worker/test/mirror.test.ts b/pkgs/github-ci/worker/test/mirror.test.ts index f2b3dcc3a4..79bc438864 100644 --- a/pkgs/github-ci/worker/test/mirror.test.ts +++ b/pkgs/github-ci/worker/test/mirror.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { + bodyHashOf, buildCommentTouch, buildIssueRow, deletionBlocks, @@ -9,6 +10,8 @@ import { mirrorCommentEvent, mirrorIssueEvent, mirrorPrEvent, + mirrorSubIssueEvent, + parentOf, } from "../src/mirror"; import type { SinkEnv } from "../src/sink"; @@ -514,3 +517,391 @@ describe("mirror writers (#8580)", () => { expect(updateValues).toContain("777"); }); }); + +interface StoredFixture { + bodyHash: string | null; + comments: number; + commentsGhUpdatedAt: string | null; + ghUpdatedAt: string | null; + parentNumber: number | null; +} + +/** + * Stub fetch as the Turso pipeline endpoint with a scripted stored + * row: the Q7 pre-read SELECT is answered from `stored` (null = no + * row), the pragma probe reports the migrated steady state ("3"), + * the tombstone SELECT finds no marker, and every statement is + * captured. With failHistory, INSERTs into github_issue_history + * return an error result — the killed history write of the oracle. + */ +function capturePipelineWithStored(stored: StoredFixture | null, opts?: { failHistory?: boolean }): CapturedStmt[] { + const stmts: CapturedStmt[] = []; + const arg = (v: string | null): { type: string; value?: string } => + v === null ? { type: "null" } : { type: "text", value: v }; + const int = (v: number | null): { type: string; value?: string } => + v === null ? { type: "null" } : { type: "integer", value: String(v) }; + vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => { + const body = JSON.parse(String(init.body)) as { + requests: { type: string; stmt?: CapturedStmt }[]; + }; + const results = body.requests.map((r) => { + if (r.type !== "execute" || !r.stmt) return { type: "success" }; + stmts.push(r.stmt); + const sql = r.stmt.sql; + if (opts?.failHistory && sql.includes("INSERT INTO github_issue_history")) { + return { type: "error", error: { message: "history table is gone" } }; + } + let rows: { type: string; value?: string }[][] = []; + if (sql.includes("pragma_table_info")) rows = [[{ type: "text", value: "3" }]]; + else if (sql.includes("SELECT body_hash") && stored) { + rows = [ + [ + arg(stored.bodyHash), + int(stored.comments), + arg(stored.commentsGhUpdatedAt), + arg(stored.ghUpdatedAt), + int(stored.parentNumber), + ], + ]; + } + return { type: "success", response: { type: "execute", result: { rows } } }; + }); + return new Response(JSON.stringify({ results }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + }); + return stmts; +} + +const historyInserts = (stmts: CapturedStmt[]): CapturedStmt[] => + stmts.filter((s) => s.sql.includes("INSERT INTO github_issue_history")); +const kindOf = (s: CapturedStmt): string | undefined => s.args?.[3]?.value; +const detailOf = (s: CapturedStmt): Record => + JSON.parse(String(s.args?.[4]?.value ?? "{}")) as Record; + +const T0 = "2026-11-11T02:00:00Z"; +const T1 = "2026-11-11T03:00:00Z"; + +describe("mirror history (#14170 Q7)", () => { + it("parentOf: absence is unknown, null is no-parent, a URL names the parent", () => { + expect(parentOf({})).toEqual({ known: false, parent: null, parentRepo: null }); + expect(parentOf({ parent_issue_url: null })).toEqual({ known: true, parent: null, parentRepo: null }); + expect(parentOf({ parent_issue_url: "https://api.github.com/repos/developing-today/code/issues/20" })).toEqual({ + known: true, + parent: 20, + parentRepo: "developing-today/code", + }); + // An unparseable value must not be guessed into a projection. + expect(parentOf({ parent_issue_url: "not a url" }).known).toBe(false); + }); + + it("oracle: a body edit writes exactly one body_edited row, hashes only", async () => { + const oldHash = await bodyHashOf({ body: "the original spec" }); + const newHash = await bodyHashOf(issuePayload.issue); + const stored: StoredFixture = { + bodyHash: oldHash, + comments: 3, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: null, + }; + const payload = { ...issuePayload, sender: { login: "dezren39" } }; + let stmts = capturePipelineWithStored(stored); + await mirrorIssueEvent(env, payload, REPO); + const rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("body_edited"); + expect(detailOf(rows[0])).toEqual({ old_hash: oldHash, new_hash: newHash }); + // Hashes only: neither body text appears anywhere in the row. + expect(String(rows[0].args?.[4]?.value)).not.toContain("original spec"); + expect(String(rows[0].args?.[4]?.value)).not.toContain("mirror everything"); + expect(rows[0].args?.[5]).toEqual({ type: "text", value: "dezren39" }); // actor + + // Redelivery of the same edit (stored hash now the new one) + // writes no second row — exactly one per change. + stored.bodyHash = newHash; + stmts = capturePipelineWithStored(stored); + await mirrorIssueEvent(env, payload, REPO); + expect(historyInserts(stmts)).toHaveLength(0); + }); + + it("a first sight writes no history rows", async () => { + const stmts = capturePipelineWithStored(null); + await mirrorIssueEvent(env, { ...issuePayload, action: "opened" }, REPO); + expect(stmts.some((s) => s.sql.includes("INSERT INTO github_mirror_issues"))).toBe(true); + expect(historyInserts(stmts)).toHaveLength(0); + }); + + it("a stale snapshot writes no history (its upsert is refused too)", async () => { + const stored: StoredFixture = { + bodyHash: "some-other-hash", + comments: 9, + commentsGhUpdatedAt: "2026-11-11T05:00:00Z", + ghUpdatedAt: "2026-11-11T05:00:00Z", + parentNumber: null, + }; + const stmts = capturePipelineWithStored(stored); + await mirrorIssueEvent(env, issuePayload, REPO); // payload is older (T0) + expect(historyInserts(stmts)).toHaveLength(0); + }); + + it("oracle: a snapshot count move writes one comment_count_changed row", async () => { + const stored: StoredFixture = { + bodyHash: await bodyHashOf(issuePayload.issue), + comments: 3, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: null, + }; + const payload = { + ...issuePayload, + issue: { ...issuePayload.issue, comments: 5, updated_at: T1 }, + }; + const stmts = capturePipelineWithStored(stored); + await mirrorIssueEvent(env, payload, REPO); + const rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("comment_count_changed"); + expect(detailOf(rows[0])).toEqual({ from: 3, to: 5 }); + }); + + it("oracle: commenting writes comment_added / comment_removed with the delta", async () => { + const stored: StoredFixture = { + bodyHash: "hash", + comments: 3, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: null, + }; + let stmts = capturePipelineWithStored(stored); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { number: 8580, comments: 4, updated_at: T1 }, + comment: { id: 99, html_url: "u", body: "thanks!" }, + repository: { full_name: REPO }, + }, + REPO, + ); + let rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("comment_added"); + expect(detailOf(rows[0])).toEqual({ from: 3, to: 4 }); + + stmts = capturePipelineWithStored(stored); + await mirrorCommentEvent( + env, + { + action: "deleted", + issue: { number: 8580, comments: 2, updated_at: T1 }, + comment: { id: 98, html_url: "u", body: "gone" }, + repository: { full_name: REPO }, + }, + REPO, + ); + rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("comment_removed"); + expect(detailOf(rows[0])).toEqual({ from: 3, to: 2 }); + }); + + it("an agent note's pointer change rides its count row's detail", async () => { + const stored: StoredFixture = { + bodyHash: "hash", + comments: 3, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: null, + }; + const stmts = capturePipelineWithStored(stored); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { number: 8580, comments: 4, updated_at: T1 }, + comment: { + id: 777, + html_url: "https://example.invalid/issues/8580#c777", + body: "🤖 **Agent note** · checkpoint\n", + }, + repository: { full_name: REPO }, + }, + REPO, + ); + const rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("comment_added"); + expect(detailOf(rows[0])).toEqual({ from: 3, to: 4, agent_note_id: 777 }); + }); + + it("a comment on an unseen row seeds it and writes no history", async () => { + const stmts = capturePipelineWithStored(null); + await mirrorCommentEvent( + env, + { + action: "created", + issue: { number: 8580, comments: 1, updated_at: T1 }, + comment: { id: 99, html_url: "u", body: "first!" }, + repository: { full_name: REPO }, + }, + REPO, + ); + expect(historyInserts(stmts)).toHaveLength(0); + }); + + it("oracle: re-parenting via snapshot writes parent_changed and moves the projection", async () => { + const stored: StoredFixture = { + bodyHash: await bodyHashOf(issuePayload.issue), + comments: 3, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: 10, + }; + const payload = { + ...issuePayload, + issue: { + ...issuePayload.issue, + updated_at: T1, + parent_issue_url: "https://api.github.com/repos/developing-today/code/issues/20", + }, + }; + const stmts = capturePipelineWithStored(stored); + await mirrorIssueEvent(env, payload, REPO); + const rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("parent_changed"); + expect(detailOf(rows[0])).toEqual({ from: 10, to: 20, parent_repo: "developing-today/code" }); + // The projection itself moves in the upsert, guarded by the + // parent_known CASE (binds 19/20: known flag, parent number). + const upsert = stmts.find((s) => s.sql.includes("INSERT INTO github_mirror_issues")); + expect(upsert?.sql).toContain("parent_number = CASE WHEN ? = 1 THEN ?"); + expect(upsert?.args?.[13]).toEqual({ type: "integer", value: "20" }); + expect(upsert?.args?.[19]).toEqual({ type: "integer", value: "1" }); + expect(upsert?.args?.[20]).toEqual({ type: "integer", value: "20" }); + }); + + it("a snapshot that does not state a parent leaves the projection standing", async () => { + const stored: StoredFixture = { + bodyHash: await bodyHashOf(issuePayload.issue), + comments: 3, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: 10, + }; + const stmts = capturePipelineWithStored(stored); + await mirrorIssueEvent(env, issuePayload, REPO); // no parent_issue_url key + expect(historyInserts(stmts)).toHaveLength(0); + const upsert = stmts.find((s) => s.sql.includes("INSERT INTO github_mirror_issues")); + expect(upsert?.args?.[19]).toEqual({ type: "integer", value: "0" }); // parent_known = 0 + }); + + it("oracle: a sub_issues delivery moves the projection and writes parent_changed", async () => { + const stored: StoredFixture = { + bodyHash: "hash", + comments: 0, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: null, + }; + let stmts = capturePipelineWithStored(stored); + await mirrorSubIssueEvent( + env, + { + action: "parent_issue_added", + sub_issue: { number: 8580, updated_at: T1 }, + parent_issue: { number: 20 }, + sender: { login: "dezren39" }, + repository: { full_name: REPO }, + }, + REPO, + ); + const update = stmts.find((s) => s.sql.startsWith("UPDATE github_mirror_issues SET parent_number")); + expect(update).toBeDefined(); + expect(update?.args?.[0]).toEqual({ type: "integer", value: "20" }); + let rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("parent_changed"); + expect(detailOf(rows[0])).toEqual({ from: null, to: 20 }); + + stored.parentNumber = 20; + stmts = capturePipelineWithStored(stored); + await mirrorSubIssueEvent( + env, + { + action: "parent_issue_removed", + sub_issue: { number: 8580, updated_at: T1 }, + parent_issue: { number: 20 }, + repository: { full_name: REPO }, + }, + REPO, + ); + rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(detailOf(rows[0])).toEqual({ from: 20, to: null }); + }); + + it("a sub_issues delivery for an unseen child seeds the row, no history", async () => { + const stmts = capturePipelineWithStored(null); + await mirrorSubIssueEvent( + env, + { + action: "sub_issue_added", + sub_issue: { number: 8580, updated_at: T1 }, + parent_issue: { number: 20 }, + repository: { full_name: REPO }, + }, + REPO, + ); + expect(stmts.some((s) => s.sql.includes("INSERT INTO github_mirror_issues (repo, number, parent_number"))).toBe( + true, + ); + expect(historyInserts(stmts)).toHaveLength(0); + }); + + it("a PR body edit writes a body_edited row with is_pr set", async () => { + const stored: StoredFixture = { + bodyHash: await bodyHashOf({ body: "the old PR body" }), + comments: 1, + commentsGhUpdatedAt: T1, + ghUpdatedAt: T1, + parentNumber: null, + }; + const stmts = capturePipelineWithStored(stored); + await mirrorPrEvent(env, prPayload, REPO); + const rows = historyInserts(stmts); + expect(rows).toHaveLength(1); + expect(kindOf(rows[0])).toBe("body_edited"); + expect(rows[0].args?.[2]).toEqual({ type: "integer", value: "1" }); // is_pr + }); + + it("oracle: a killed history write still lands the mirror upsert (fail-open)", async () => { + const stored: StoredFixture = { + bodyHash: await bodyHashOf({ body: "the original spec" }), + comments: 3, + commentsGhUpdatedAt: T0, + ghUpdatedAt: T0, + parentNumber: null, + }; + const stmts = capturePipelineWithStored(stored, { failHistory: true }); + const log = vi.spyOn(console, "error").mockImplementation(() => {}); + // The event resolves: the history failure is swallowed, and the + // mirror upsert + meta stamp were captured before it. + await expect(mirrorIssueEvent(env, issuePayload, REPO)).resolves.toBeUndefined(); + expect(stmts.some((s) => s.sql.includes("INSERT INTO github_mirror_issues"))).toBe(true); + expect(stmts.some((s) => s.sql.includes("INSERT INTO github_mirror_meta"))).toBe(true); + expect(historyInserts(stmts)).toHaveLength(1); // attempted, then dropped + expect(log).toHaveBeenCalledWith(expect.stringContaining("history write failed open")); + log.mockRestore(); + }); + + it("the history schema ships in the DDL batch", async () => { + const stmts = capturePipelineWithStored(null); + await mirrorIssueEvent(env, issuePayload, REPO); + const sql = stmts.map((s) => s.sql).join("\n"); + expect(sql).toContain("CREATE TABLE IF NOT EXISTS github_issue_history"); + expect(sql).toContain("CREATE INDEX IF NOT EXISTS github_issue_history_issue"); + expect(sql).toContain("parent_number INTEGER"); + }); +}); diff --git a/pkgs/github-ci/worker/test/worker.test.ts b/pkgs/github-ci/worker/test/worker.test.ts index f3beb83583..6ed0a76cea 100644 --- a/pkgs/github-ci/worker/test/worker.test.ts +++ b/pkgs/github-ci/worker/test/worker.test.ts @@ -237,8 +237,9 @@ describe("github-ci worker", () => { const seen: string[] = []; const queueMock = fetchMock.get(QUEUE); // 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++) { + // + mirror column probe (1) + stored-row read for the Q7 + // history diff (1) + mirror writes batch (1) + for (let i = 0; i < 6; i++) { queueMock.intercept({ path: "/v2/pipeline", method: "POST" }).reply(200, (opts) => { seen.push(String(opts.body)); return tursoOk(); @@ -273,8 +274,9 @@ describe("github-ci worker", () => { const seen: string[] = []; const queueMock = fetchMock.get(QUEUE); // 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++) { + // + mirror column probe (1) + stored-row read for the Q7 + // history diff (1) + mirror writes batch (1) + for (let i = 0; i < 6; i++) { queueMock.intercept({ path: "/v2/pipeline", method: "POST" }).reply(200, (opts) => { seen.push(String(opts.body)); return tursoOk(); @@ -296,4 +298,31 @@ describe("github-ci worker", () => { expect(all).toContain("UPDATE github_mirror_issues SET"); expect(all).toContain("31337"); }); + + it("sub_issues on a fleet repo moves the mirror parent projection (#14170 Q7)", async () => { + const seen: string[] = []; + const queueMock = fetchMock.get(QUEUE); + // sink event insert (1) + watermark (1) + mirror DDL batch (1) + // + mirror column probe (1) + stored-row read (1) + mirror + // writes batch (1) + for (let i = 0; i < 6; i++) { + queueMock.intercept({ path: "/v2/pipeline", method: "POST" }).reply(200, (opts) => { + seen.push(String(opts.body)); + return tursoOk(); + }); + } + const p = JSON.stringify({ + action: "parent_issue_added", + sub_issue: { number: 8581, updated_at: "2026-11-11T03:00:00Z" }, + parent_issue: { number: 8580 }, + repository: { full_name: "developing-today/code" }, + }); + const res = await post(p, "sub_issues", await sign(p)); + expect(res.status).toBe(200); + const all = seen.join("\n"); + // The mock answers every read with no rows, so the child is a + // first sight: seeded minimal with its parent projection. + expect(all).toContain("parent_number"); + expect(all).toContain("INSERT INTO github_mirror_meta"); + }); });