From bf2e999458a5f47f878e82e62ef95e464530dc1e Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:23:56 +0000 Subject: [PATCH] Record each GitHub write before the call and finish the row after; unknown outcome for rows left started --- src/dash/api/github-activity.ts | 1 + src/fixissue/index.ts | 4 +- src/github/write.ts | 61 +++++++++++++++++++----------- test/github-activity.test.ts | 21 ++++++++++ test/labels.test.ts | 2 +- web/src/api/mock/githubFixtures.ts | 2 +- web/src/api/types.ts | 2 + web/src/modules/github/index.tsx | 3 +- 8 files changed, 68 insertions(+), 28 deletions(-) diff --git a/src/dash/api/github-activity.ts b/src/dash/api/github-activity.ts index 660a33391..67d2b001e 100644 --- a/src/dash/api/github-activity.ts +++ b/src/dash/api/github-activity.ts @@ -106,6 +106,7 @@ export async function githubActivity(db: DatabaseSync, req: Req): Promise ({ action: a, label: GITHUB_ACTIONS[a]! })) }; diff --git a/src/fixissue/index.ts b/src/fixissue/index.ts index e0230ffd4..ee047b798 100644 --- a/src/fixissue/index.ts +++ b/src/fixissue/index.ts @@ -493,8 +493,8 @@ async function closedLive(x: Ctx, r: AttemptRow): Promise { return true; } -/** Comments on the issue at most once: the activity row is written for every attempt, so a failed post is not retried. */ -async function comment(x: Ctx, r: AttemptRow, url: string): Promise { +/** Comments on the issue at most once: the activity row is written before the post, so a failed post or a crash is not retried. */ +export async function comment(x: Ctx, r: AttemptRow, url: string): Promise { const { db, d, log } = x; const ref = refOf(r); if (db.prepare("SELECT 1 FROM audit WHERE action = 'fixissue-comment' AND target = ?").get(ref)) return; diff --git a/src/github/write.ts b/src/github/write.ts index 4faf16d7f..4bf2a72dd 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -6,7 +6,6 @@ // injected so tests fake them and assert the rows. import type { DatabaseSync } from "node:sqlite"; import { ORG } from "../act/templates.ts"; -import { audit } from "../dash/audit.ts"; import { connect } from "../db.ts"; import type { Exec, ExecResult, Git } from "../fixup/git.ts"; import type { Querier } from "../mirror.ts"; @@ -22,22 +21,31 @@ const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim().slice(0, 30 const direct: Retry = (f) => f(); const refOf = (repo: string, number: number): string => `${repo}#${number}`; -function row(w: Writer, action: string, target: string, details: Details, error?: string): void { - audit(w.db, w.login, action, target, error === undefined ? details : { ...details, error }); +/** Adds the row before the write, so a crash during the call leaves a "started" row: an unknown outcome. */ +function begin(w: Writer, action: string, target: string, details: Details): number { + const r = w.db.prepare("INSERT INTO audit (at, login, action, target, details) VALUES (?, ?, ?, ?, ?)") + .run(new Date().toISOString(), w.login, action, target, JSON.stringify({ ...details, state: "started" })); + return Number(r.lastInsertRowid); } -/** Runs the write, records one row with `view`'s extra details on success or the error on failure, and returns the result. */ +function finish(w: Writer, id: number, details: Details, error?: string): void { + const d = error === undefined ? { ...details, state: "done" } : { ...details, state: "failed", error }; + w.db.prepare("UPDATE audit SET details = ? WHERE rowid = ?").run(JSON.stringify(d), id); +} + +/** Records the row first, runs the write, then marks the row done with `view`'s extra details or failed with the error. */ async function recorded(w: Writer, action: string, target: string, details: Details, f: () => Promise, view?: (r: T) => Details, failure?: (r: T) => string | null): Promise { + const id = begin(w, action, target, details); let r: T; try { r = await f(); } catch (e) { - row(w, action, target, details, oneLine(String((e as Error).message ?? e))); + finish(w, id, details, oneLine(String((e as Error).message ?? e))); throw e; } const bad = failure?.(r) ?? null; - if (bad !== null) row(w, action, target, details, bad); - else row(w, action, target, { ...details, ...view?.(r) }); + if (bad !== null) finish(w, id, details, bad); + else finish(w, id, { ...details, ...view?.(r) }); return r; } @@ -115,20 +123,22 @@ export type LabelWrite = { number: number; id: string; labelIds: string[]; names export async function addLabels(w: Writer, q: Querier, repo: string, items: LabelWrite[], retry: Retry = direct, details: Details = {}): Promise { const vars: Record = {}; items.forEach((it, k) => { vars[`i${k}`] = it.id; vars[`l${k}`] = it.labelIds; }); + const det = (it: LabelWrite): Details => ({ ...details, labels: it.names }); + const ids = items.map((it) => begin(w, "labels-apply", refOf(repo, it.number), det(it))); let d: Record | null; try { d = await retry(() => q.query(addLabelsMutation(items.length), vars)); } catch (e) { const msg = oneLine(String((e as Error).message ?? e)); - for (const it of items) row(w, "labels-apply", refOf(repo, it.number), { ...details, labels: it.names }, msg); + items.forEach((it, k) => finish(w, ids[k]!, det(it), msg)); throw e; } const done: number[] = []; items.forEach((it, k) => { if (d && d[`m${k}`] !== null && d[`m${k}`] !== undefined) { done.push(it.number); - row(w, "labels-apply", refOf(repo, it.number), { ...details, labels: it.names }); - } else row(w, "labels-apply", refOf(repo, it.number), { ...details, labels: it.names }, "GitHub did not apply the labels"); + finish(w, ids[k]!, det(it)); + } else finish(w, ids[k]!, det(it), "GitHub did not apply the labels"); }); return done; } @@ -198,27 +208,32 @@ export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string } /** - * The merge itself: `gh pr merge` pinned to `head`. `record` receives the outcome for the built-in command - * line; it is absent when a parent process already records the merge. + * The merge itself: `gh pr merge` pinned to `head`. `record` starts the activity row and returns the function that + * finishes it; it is absent when a parent process already records the merge. */ -export async function ghMergePr(gh: (args: string[]) => Promise, repo: string, pr: string, method: "--squash" | "--merge", head: string, record?: (error?: string) => void): Promise { +export async function ghMergePr(gh: (args: string[]) => Promise, repo: string, pr: string, method: "--squash" | "--merge", head: string, record?: () => (error?: string) => void): Promise { + const end = record?.(); try { await gh(["pr", "merge", pr, "-R", repo, method, "--match-head-commit", head]); } catch (e) { - record?.(oneLine(String((e as Error).message ?? e))); + end?.(oneLine(String((e as Error).message ?? e))); throw e; } - record?.(); + end?.(); } /** Records a merge made from the command line, in the database `connect()` opens, under the login `cli`. */ -export function cliMergeRecorder(repoSlug: string, pr: string, method: string, head: string): (error?: string) => void { - return (error) => { - const db = connect(); - try { - row({ db, login: "cli" }, "merge", refOf(repoSlug.split("/").pop() ?? repoSlug, Number(pr)), { method: method.slice(2), head }, error); - } finally { - db.close(); - } +export function cliMergeRecorder(repoSlug: string, pr: string, method: string, head: string): () => (error?: string) => void { + return () => { + const w: Writer = { db: connect(), login: "cli" }; + const details = { method: method.slice(2), head }; + const id = begin(w, "merge", refOf(repoSlug.split("/").pop() ?? repoSlug, Number(pr)), details); + return (error) => { + try { + finish(w, id, details, error); + } finally { + w.db.close(); + } + }; }; } diff --git a/test/github-activity.test.ts b/test/github-activity.test.ts index cc1543044..630c398cc 100644 --- a/test/github-activity.test.ts +++ b/test/github-activity.test.ts @@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync } from "node:fs"; import { join } from "node:path"; import { test } from "node:test"; import { connect } from "../src/db.ts"; +import { comment } from "../src/fixissue/index.ts"; import { githubActivity } from "../src/dash/api/github-activity.ts"; import { addLabels, closeItem, commentOn, ghComment, mergeViaCommand, pushBranch, type Writer } from "../src/github/write.ts"; import { readSeqs } from "../src/live.ts"; @@ -117,3 +118,23 @@ test("filters, paging and visibility", async () => { assert.equal((await githubActivity(db, req(`to=${new Date().toISOString().slice(0, 10)}`))).total, 7); await assert.rejects(githubActivity(db, req("action=nope")), /unknown action/); }); + +test("the row exists before the call; a crash leaves an unknown outcome and the issue comment is not posted again", async () => { + const db = setup(); + const w: Writer = { db, login: "act" }; + const state = () => (db.prepare("SELECT details FROM audit WHERE action = 'act-comment'").all() as { details: string }[]).map((r) => (JSON.parse(r.details) as { state: string }).state); + let during: string[] = []; + await commentOn(w, { ...fakeQuerier(), async query() { during = state(); return {}; } }, "act-comment", { repo: "app", number: 7, id: "N7" }, "x"); + assert.deepEqual(during, ["started"], "recorded before the GitHub call"); + assert.deepEqual(state(), ["done"]); + + // A process that died inside the call leaves the started row. + db.prepare("INSERT INTO audit (at, login, action, target, details) VALUES (?, 'fixissue', 'fixissue-comment', 'app#7', ?)").run(new Date().toISOString(), JSON.stringify({ run: "r", state: "started" })); + const p = await githubActivity(db, req("action=fixissue-comment")); + assert.equal(p.rows[0]!.outcome, "unknown"); + + const calls: string[][] = []; + const x = { db, d: { exec: async (_c: string, a: string[]) => { calls.push(a); return { code: 0, stdout: "OPEN", stderr: "" }; } }, git: {}, log: () => {}, runId: "r2", usage: {} } as unknown as Parameters[0]; + await comment(x, { repo: "app", number: 7 } as Parameters[1], "https://github.com/storytold/app/pull/9"); + assert.deepEqual(calls, [], "no second comment after a started row"); +}); diff --git a/test/labels.test.ts b/test/labels.test.ts index 54b0af398..33bb5c815 100644 --- a/test/labels.test.ts +++ b/test/labels.test.ts @@ -114,7 +114,7 @@ describe("labels apply", () => { const rows = db.prepare("SELECT target, details FROM audit WHERE action = 'labels-apply' ORDER BY rowid").all() as { target: string; details: string }[]; const ok = rows.filter((x) => !x.details.includes('"error"')); assert.equal(ok.length, n - 1, "one row per labelled item"); - assert.deepEqual(JSON.parse(ok[0]!.details), { run: RUN, labels: ["bugfix", "security"] }); + assert.deepEqual(JSON.parse(ok[0]!.details), { run: RUN, labels: ["bugfix", "security"], state: "done" }); assert.equal(ok[0]!.target, "app#1"); assert.ok(rows.some((x) => x.target === "app#2" && x.details.includes('"error"')), "the item GitHub did not label has a failure row"); diff --git a/web/src/api/mock/githubFixtures.ts b/web/src/api/mock/githubFixtures.ts index e5b2f9333..60d1a04b2 100644 --- a/web/src/api/mock/githubFixtures.ts +++ b/web/src/api/mock/githubFixtures.ts @@ -14,7 +14,7 @@ const ROWS: GithubActivityRow[] = Array.from({ length: 120 }, (_, i) => { id: String(1000 - i), at: new Date(NOW - i * 37 * 60_000).toISOString(), action: a.action, label: a.label, repo, number, branch: null, title: `Fix the thing in module ${number}`, detail: a.action === "labels-apply" ? "bugfix, size-S" : a.action === "act-comment" ? "Closing as a duplicate of an earlier report." : a.action === "merge" ? "squash 3f9a2c1" : "", - url: `https://github.com/storytold/${repo}/pull/${number}`, source: a.action === "labels-apply" ? "kiri-n" : `act act-${repo}-20261102`, error: i === 5 ? "gh failed: HTTP 502" : null, + url: `https://github.com/storytold/${repo}/pull/${number}`, source: a.action === "labels-apply" ? "kiri-n" : `act act-${repo}-20261102`, error: i === 5 ? "gh failed: HTTP 502" : null, outcome: i === 5 ? "failed" : i === 7 ? "unknown" : "done", }; }); diff --git a/web/src/api/types.ts b/web/src/api/types.ts index fb9545718..3443742c5 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -1340,6 +1340,8 @@ export interface GithubActivityRow { source: string; /** why the write failed; null when it went through */ error: string | null; + /** "unknown": the write was started and the app never recorded how it ended */ + outcome: "done" | "failed" | "unknown"; } export interface GithubActivityPage { diff --git a/web/src/modules/github/index.tsx b/web/src/modules/github/index.tsx index 2ea20d618..d5ae0c63f 100644 --- a/web/src/modules/github/index.tsx +++ b/web/src/modules/github/index.tsx @@ -37,6 +37,7 @@ function Detail({ r }: { r: GithubActivityRow }) { return ( <> {r.error && Failed} + {r.outcome === "unknown" && Unknown outcome.} {r.detail && {r.detail}} {r.error && {r.error}} @@ -104,7 +105,7 @@ function Cards({ rows }: { rows: GithubActivityRow[] }) { {r.label} - {(r.detail || r.error) && ( + {(r.detail || r.error || r.outcome === "unknown") && (