Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions pkgs/github-ci/worker/mirror.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down Expand Up @@ -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);
135 changes: 110 additions & 25 deletions pkgs/github-ci/worker/scripts/backfill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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<Map<number, StoredRow>> => {
const storedRows = async (
q: Turso,
table: string,
repo: string,
withParent = false,
): Promise<Map<number, StoredRow>> => {
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 }],
),
Expand All @@ -199,6 +218,7 @@ const storedRows = async (q: Turso, table: string, repo: string): Promise<Map<nu
comments: Number(cell(3) ?? 0) || 0,
commentsGhUpdatedAt: cell(4),
agentNoteId: cell(5) === null ? null : Number(cell(5)),
parentNumber: cell(6) === null ? null : Number(cell(6)),
});
}
return map;
Expand All @@ -216,6 +236,8 @@ interface RepoSummary {
pointers_failed: number;
counts_forced: number;
counts_repair_failed: number;
history_rows: number;
history_failed: number;
incomplete?: boolean;
vanished_skipped_live: number;
unchanged: number;
Expand All @@ -236,6 +258,8 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
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);
Expand All @@ -248,7 +272,7 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
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;
Expand All @@ -258,6 +282,8 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
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;
Expand All @@ -271,18 +297,25 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
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;
Expand All @@ -294,6 +327,8 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
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
Expand All @@ -306,20 +341,31 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
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);
Expand Down Expand Up @@ -401,16 +447,36 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
}
}

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
Expand All @@ -437,6 +503,25 @@ const sweepRepo = async (repo: string): Promise<RepoSummary> => {
),
]);
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++;
Expand Down
22 changes: 21 additions & 1 deletion pkgs/github-ci/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<string, unknown>;
const parent = (payload.parent_issue ?? {}) as Record<string, unknown>;
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 });
}
Expand Down
Loading