diff --git a/src/data/views/prStatus.ts b/src/data/views/prStatus.ts new file mode 100644 index 000000000..1ad1702ab --- /dev/null +++ b/src/data/views/prStatus.ts @@ -0,0 +1,57 @@ +// Read model of the PR status comment step (src/prstatus/index.ts): the stored comments, the PRs in the pipeline's scope and the +// started items of one repo in one wave, then the batch, answer and quiet facts of the PRs the step looks at. +// reads: workflow.pr_status_comments, workflow.item_workflows, workflow.workflow_events, mirror.items, planner.item_stage, merge.merge_batches, merge.merge_batch_prs, security (quiet) +import type { Db } from "../../db/index.ts"; +import { queryDb } from "../../db/query-db.ts"; +import * as kx from "../../db/kx.ts"; +import { loadAnswers, loadLatestWorkflows, loadStatusComments } from "../workflow/index.ts"; +import { inScopeExpr } from "../workflow/fragments.ts"; +import { loadQuiet } from "../security/index.ts"; +import { ACTIVE_BATCH } from "../merge/types.ts"; +import type { StatusExtras, StatusInputs } from "./types.ts"; + +/** + * The repo's stored comments that are not final, the open PRs in scope past triage (a stage row) that are not integration + * PRs, and each started item's latest workflow with whether the item is open. One `together` wave. + */ +export async function loadStatusInputs(db: Db, repo: string): Promise { + const q = queryDb(db); + const k = q.k as any; + const scopeQ = k.selectFrom("main.items as i").select("i.number") + .where("i.repo", "=", repo).where("i.kind", "=", "pr").where("i.state", "=", "OPEN") + .where((eb: any) => eb.exists(eb.selectFrom("main.item_stage as s").select(eb.lit(1).as("one")).whereRef("s.repo", "=", "i.repo").whereRef("s.number", "=", "i.number"))) + .where((eb: any) => eb.not(eb.exists(eb.selectFrom("main.merge_batches as b").select(eb.lit(1).as("one")).whereRef("b.repo", "=", "i.repo").whereRef("b.pr_number", "=", "i.number")))) + .where((eb: any) => inScopeExpr(db, eb, "i.repo", "i.number")); + const [stored, scope, started] = await db.together(() => Promise.all([ + loadStatusComments(db, repo), + q.all(scopeQ) as Promise<{ number: number }[]>, + loadLatestWorkflows(db, repo), + ])); + return { stored, inScope: new Set(scope.map((r) => Number(r.number))), started }; +} + +/** + * For the PRs `numbers` of the repo: each one's open merge batch at its current head (`open:N`) and the batch it merged with + * (`merged:N`), with the batch's PR number (null before it opens); the latest answer of each workflow in `workflowIds`; and the + * quiet PRs. One `together` wave. + */ +export async function loadStatusExtras(db: Db, repo: string, numbers: number[], workflowIds: number[]): Promise { + const q = queryDb(db); + const k = q.k as any; + const batchQ = k.selectFrom("main.merge_batch_prs as bp").innerJoin("main.merge_batches as b", "b.id", "bp.batch_id") + .innerJoin("main.items as i", (j: any) => j.onRef("i.repo", "=", "b.repo").onRef("i.number", "=", "bp.number")) + .select(["bp.number", "b.state", "b.pr_number", "bp.head_oid", "i.head_oid as head"]) + .where("b.repo", "=", repo).where(kx.inList(db, "bp.number", numbers, "bigint")).where("b.state", "in", [...ACTIVE_BATCH, "merged"]).orderBy("b.id"); + const [rows, answered, quiet] = await db.together(() => Promise.all([ + numbers.length ? q.all(batchQ) as Promise<{ number: number; state: string; pr_number: number | null; head_oid: string; head: string | null }[]> : Promise.resolve([]), + loadAnswers(db, workflowIds), + loadQuiet(db, numbers.map((n) => `${repo}#${n}`)), + ])); + const batches = new Map(); + for (const r of rows) { + const pr = r.pr_number === null ? null : Number(r.pr_number); + if (r.state === "merged") batches.set(`merged:${Number(r.number)}`, { pr }); + else if (r.head_oid === r.head) batches.set(`open:${Number(r.number)}`, { pr }); + } + return { batches, answered, quiet: new Set(numbers.filter((n) => quiet.has(`${repo}#${n}`))) }; +} diff --git a/src/data/views/types.ts b/src/data/views/types.ts index 648eb70cd..76895243b 100644 --- a/src/data/views/types.ts +++ b/src/data/views/types.ts @@ -143,5 +143,12 @@ export type PublicStatsFacts = { open: { repo: string; kind: "pr" | "issue"; n: number }[]; merged: { repo: string; number: number; ours: boolean; mergedAt: string; openedAt: string }[]; reviews: { repo: string; n: number }[]; queues: { repo: string; n: number }[]; }; -export type StatusInputs = { workflows: ItemWorkflow[]; stages: Map; batches: BatchView[]; items: unknown[] }; export type HeldFixupFacts = { repo: string; number: number; title: string; head: string; reason: string | null; fixes: unknown; latestFixup: { state: string; reason: string | null } | null }; + +/** src/data/views/prStatus.ts */ +export type StatusInputs = { + stored: import("../workflow/types.ts").StatusRow[]; + inScope: Set; + started: Map; +}; +export type StatusExtras = { batches: Map; answered: Map; quiet: Set }; diff --git a/src/operator-actions.ts b/src/operator-actions.ts index 8d5a581ea..e9dbbd570 100644 --- a/src/operator-actions.ts +++ b/src/operator-actions.ts @@ -2,9 +2,10 @@ // plan Verify again after it failed or errored, try a skipped or failed issue fix again, try the integration batch // again after a single-PR batch failed. Each changes // only local tables (the pipeline then picks the item up as usual) and is audited; none writes to GitHub. -import { FIX_RETIRED_REASON } from "./db/fix-retire.ts"; -import { audit } from "./dash/audit.ts"; -import { batchStates, updateBatch } from "./merge/batch-store.ts"; +import { loadPrMirror } from "./data/mirror/index.ts"; +import { loadReviewsAt, dropHoldReviews } from "./data/review/index.ts"; +import { loadFailedBatchOf, markVerificationsStale, supersedeFailedBatch, verificationOf } from "./data/merge/index.ts"; +import { addAudit } from "./data/control/index.ts"; import { headOf } from "./review/candidates.ts"; import type { Db } from "./db/index.ts"; import { openDb } from "./db/open.ts"; @@ -19,56 +20,52 @@ export class ActionError extends Error { export type ItemActions = { reviewAgain: boolean; verifyAgain: boolean; batchAgain: boolean }; -type ItemRow = { kind: string; state: string; head_oid: string | null; updated_at: string | null; c_head: string | null; c_at: string | null }; +type Item = { kind: string; state: string; head: string | null }; -async function openItem(db: Db, repo: string, n: number): Promise { - const r = await db.get(db.k.selectFrom("items as i") - .leftJoin("pr_checks as c", (j) => j.onRef("c.repo", "=", "i.repo").onRef("c.number", "=", "i.number")) - .select(["i.kind", "i.state", "i.head_oid", "i.updated_at", "c.head_oid as c_head", "c.fetched_at as c_at"]) - .where("i.repo", "=", repo).where("i.number", "=", n)); - if (!r) throw new ActionError(404, `no item ${repo}#${n} in the mirror`); - if (r.state !== "OPEN") throw new ActionError(409, `${repo}#${n} is not open`); - return { ...r, head: headOf(r) }; +/** The item's kind, state and current head (the newer of the item's and its checks' heads), or null when the mirror lacks it. */ +async function itemOf(db: Db, repo: string, n: number): Promise { + const m = (await loadPrMirror(db, [{ repo, number: n }])).get(`${repo}#${n}`); + if (!m) return null; + const c = m.checks; + return { kind: m.item.kind, state: m.item.state, head: headOf({ head_oid: m.item.head_oid, updated_at: m.item.updated_at, c_head: c?.head_oid ?? null, c_at: c?.fetched_at ?? null }) }; } -const heldReview = async (db: Db, repo: string, n: number, head: string | null) => - head ? await db.get(db.k.selectFrom("final_reviews").select("reason").where("repo", "=", repo).where("number", "=", n).where("head_oid", "=", head).where("verdict", "=", "hold")) : undefined; -const failedVerify = async (db: Db, repo: string, n: number, head: string | null) => - head ? await db.get(db.k.selectFrom("verifications").select(["state", "summary"]).where("repo", "=", repo).where("number", "=", n).where("head_sha", "=", head).where("state", "in", ["failed", "error"])) : undefined; -export const stoppedFix = async (db: Db, repo: string, n: number) => - await db.get(db.k.selectFrom("fix_attempts").select(["state", "round", "retries", "push_tries", "reason", "summary"]) - .where("repo", "=", repo).where("number", "=", n).where("state", "in", ["skipped", "failed"]).where("pr_url", "is", null) - // An attempt the Implement migration ended is not the fix step's to retry. - .where((eb) => eb.or([eb("reason", "is", null), eb("reason", "<>", FIX_RETIRED_REASON)]))); +async function openItem(db: Db, repo: string, n: number): Promise { + const r = await itemOf(db, repo, n); + if (!r) throw new ActionError(404, `no item ${repo}#${n} in the mirror`); + if (r.state !== "OPEN") throw new ActionError(409, `${repo}#${n} is not open`); + return r; +} + +const heldReview = async (db: Db, repo: string, n: number, head: string | null) => { + if (!head) return undefined; + const r = (await loadReviewsAt(db, [{ repo, number: n, head }])).get(`${repo}#${n}@${head}`); + return r?.verdict === "hold" ? { reason: r.reason } : undefined; +}; +const failedVerify = async (db: Db, repo: string, n: number, head: string | null) => { + const v = head ? await verificationOf(db, repo, n, head) : undefined; + return v && (v.state === "failed" || v.state === "error") ? { state: v.state, summary: v.summary } : undefined; +}; +/** The legacy fix step's stopped attempt; the fix step is retired, so there is none. */ +export const stoppedFix = async (_db: Db, _repo: string, _n: number): Promise<{ state: string; round: number; retries: number; push_tries: number; reason: string | null; summary: string | null } | null> => null; const failedBatch = async (db: Db, repo: string, n: number, head: string | null) => - head && (await batchStates(db, repo)).get(`${repo}#${n}@${head}`) === "batch-failed" - ? await db.get(db.k.selectFrom("main.merge_batches as b").innerJoin("main.merge_batch_prs as p", "p.batch_id", "b.id") - .select(["b.id", "b.summary"]).where("b.repo", "=", repo).where("b.state", "=", "failed").where("p.number", "=", n).where("p.head_oid", "=", head) - .orderBy("b.id", "desc").limit(1)) - : undefined; + head ? (await loadFailedBatchOf(db, [{ repo, number: n, head }])).get(`${repo}#${n}@${head}`) : undefined; /** Which releases apply to the item now; the Item page shows only these. */ export async function actionsOf(db: Db, repo: string, n: number): Promise { - const r = await db.get(db.k.selectFrom("items as i") - .leftJoin("pr_checks as c", (j) => j.onRef("c.repo", "=", "i.repo").onRef("c.number", "=", "i.number")) - .select(["i.kind", "i.state", "i.head_oid", "i.updated_at", "c.head_oid as c_head", "c.fetched_at as c_at"]) - .where("i.repo", "=", repo).where("i.number", "=", n)); - if (!r || r.state !== "OPEN") return { reviewAgain: false, verifyAgain: false, batchAgain: false }; - const head = headOf(r); - return r.kind === "pr" - ? { reviewAgain: !!await heldReview(db, repo, n, head), verifyAgain: !!await failedVerify(db, repo, n, head), batchAgain: !!await failedBatch(db, repo, n, head) } - : { reviewAgain: false, verifyAgain: false, batchAgain: false }; + const r = await itemOf(db, repo, n); + if (!r || r.state !== "OPEN" || r.kind !== "pr") return { reviewAgain: false, verifyAgain: false, batchAgain: false }; + const [review, verify, batch] = await db.together(() => Promise.all([heldReview(db, repo, n, r.head), failedVerify(db, repo, n, r.head), failedBatch(db, repo, n, r.head)])); + return { reviewAgain: !!review, verifyAgain: !!verify, batchAgain: !!batch }; } /** Removes the hold review at the PR's current head so the Review stage reviews that head again. */ export async function reviewAgain(db: Db, by: string, repo: string, n: number): Promise { const it = await openItem(db, repo, n); if (it.kind !== "pr") throw new ActionError(409, `${repo}#${n} is not a pull request`); - const held = await heldReview(db, repo, n, it.head); - if (!held) throw new ActionError(409, `${repo}#${n} has no review hold at its current head`); - await db.run(db.k.deleteFrom("opus_reviews").where("repo", "=", repo).where("number", "=", n).where("head_oid", "=", it.head!)); - await audit(db, by, "review-again", `${repo}#${n}`, { head: it.head, reason: held.reason }); + const gone = it.head ? await dropHoldReviews(db, [{ repo, number: n, head: it.head }], by) : []; + if (!gone.length) throw new ActionError(409, `${repo}#${n} has no review hold at its current head`); } /** Marks the failed or errored verification of the current head stale so Verify plans it again. */ @@ -77,18 +74,22 @@ export async function verifyAgain(db: Db, by: string, repo: string, n: number): if (it.kind !== "pr") throw new ActionError(409, `${repo}#${n} is not a pull request`); const v = await failedVerify(db, repo, n, it.head); if (!v) throw new ActionError(409, `${repo}#${n} has no failed or errored verification at its current head`); - await db.run(db.k.updateTable("verifications").set({ state: "stale" }).where("repo", "=", repo).where("number", "=", n).where("head_sha", "=", it.head!)); - await audit(db, by, "verify-again", `${repo}#${n}`, { head: it.head, was: v.state, summary: v.summary }); + await db.write(async () => { + await markVerificationsStale(db, [`${repo}#${n}@${it.head!}`], by); + await addAudit(db, [{ login: by, action: "verify-again", target: `${repo}#${n}`, details: { head: it.head, was: v.state, summary: v.summary } }]); + }); } /** Marks the failed batch that holds the PR's current head superseded, keeping its summary, so the merge queue considers the PR again. */ export async function batchAgain(db: Db, by: string, repo: string, n: number): Promise { const it = await openItem(db, repo, n); if (it.kind !== "pr") throw new ActionError(409, `${repo}#${n} is not a pull request`); - const b = await failedBatch(db, repo, n, it.head); - if (!b) throw new ActionError(409, `${repo}#${n} is not held by a failed batch at its current head`); - await updateBatch(db, b.id, new Date().toISOString(), { state: "superseded" }); - await audit(db, by, "batch-again", `${repo}#${n}`, { head: it.head, batch: b.id, summary: b.summary }); + if (!it.head) throw new ActionError(409, `${repo}#${n} is not held by a failed batch at its current head`); + try { + await supersedeFailedBatch(db, by, { repo, number: n, head: it.head }); + } catch (e) { + throw new ActionError(409, (e as Error).message); + } } export const commands = { diff --git a/src/preapproval/index.ts b/src/preapproval/index.ts index 00b7333aa..897cafdf5 100644 --- a/src/preapproval/index.ts +++ b/src/preapproval/index.ts @@ -1,46 +1,48 @@ // Pipeline steps of a resolution card (review again, fix-up, fix-up then merge) and the pre-approved merge they can start. // -// A pre-approved merge is an operator's Merge answer given ahead of a fix-up. States (see Preapproval in web/src/api/types.ts): +// A pre-approved merge is the merge leg of a person's workflow: the merge they approved, worked through a fix-up, its review, CI +// and the pre-merge review. States (see Preapproval in web/src/api/types.ts): // fixup -> the fix-up step works the operator's instructions (source 'operator' in its fixups rows) // review -> the fix-up pushed; waiting for the Opus review of the pushed head. A row with no fix-up (a Merge answer carried across a // base merge, or "Queue items") starts here at its head. // ci -> that review says take (sure or unsure, not stale); waiting for CI of the pushed head, then for a clean pre-merge review of it. // A take-fix review keeps the row in review while the pipeline's fix-up of its fixes runs; that push is reviewed again. -// queued -> CI is green and the pre-merge review is clean: the PR's Merge? decision at the head is answered Merge by the operator, -// exactly as a dashboard answer would be, in the same transaction that moves the row from ci to queued; the merge queue -// then merges it with every check it always makes (safe-merge included) -// merged / asked / cancelled / failed end it. +// queued -> CI is green and the pre-merge review is clean: the merge queue merges it as the person who approved the workflow +// (src/core/may.ts mayMerge), with every check it always makes (safe-merge included) +// merged / cancelled / failed end it. A stop ends the leg failed; the workflow then stops at a blocker with its recommendation. // Every transition is a pure reaction to rows other steps write (fixups, opus_reviews, pr_checks, items, merges), evaluated by // advancePreapprovals on each runner tick: no timer and no wait of its own; the one time comparison (the start of the mirror's last sync against the push) is made when the tick runs anyway. Merging itself is never called from here. import { settleMemo, settlesNow } from "../settlers.ts"; import type { Preapproval } from "../../web/src/api/types.ts"; import type { Step } from "../conversations/cards.ts"; -import { conversationOf, insertTurn, systemBlock } from "../conversations/store.ts"; +import { systemBlock } from "../conversations/store.ts"; import { cifixBucket, decidePr, fixupOf, ownImplementation, reviseOf } from "../core/decide.ts"; import { loadPrFact, loadPrFacts } from "../core/facts.ts"; -import { withSettingsSnapshot } from "../settings-read.ts"; -import { HEAD_FACT, MERGE_OPTIONS, PREMERGE_MAX_TRIES, mergeDecisionId } from "../core/rules.ts"; -import { audit } from "../dash/audit.ts"; -import { ask, getDecision, replaceProposedCards } from "../decisions.ts"; +import { PREMERGE_MAX_TRIES } from "../core/rules.ts"; +import { mayMerge, mayPush, type WorkflowGate } from "../core/may.ts"; import { ensureAuthorWrites } from "../fixup/author-permission.ts"; import { longLivedOf, pushable } from "../fixup/pushable.ts"; -import { pushApprovalOf } from "../fixup/approval.ts"; -import { mergeApprovalOf } from "../merge/approval.ts"; import { repoHasNoCi } from "../merge/no-ci.ts"; -import { setAsideSupersededQuestions, withdrawMergeQuestion, withdrawOtherHeadQuestions } from "../merge/withdraw.ts"; import { findingsOf, premergeAt } from "../premerge/store.ts"; import { releaseMerge, removeFromBatch } from "../merge/controls.ts"; import type { Exec } from "../fixup/git.ts"; import { markReviewsStale, staleReviews } from "../review/discussion.ts"; import { reviewHold } from "../review/gate.ts"; import type { PrFacts } from "../core/plan.ts"; -import { openOperatorFixups, operatorTriesLeft, queuedOperatorFix } from "./state.ts"; -import { legContext } from "../workflow/store.ts"; +import { operatorTriesLeft, queuedOperatorFix } from "./state.ts"; import { refreshSettlers, type RefreshDeps } from "./permissions.ts"; -import { lockLiveExpr } from "../answers/hold.ts"; +import { addAudit, listAudit, listPushOutcomes, loadAuditActions, loadStepApprovals, withConfig, type StepApproval } from "../data/control/index.ts"; +import { loadChecks, loadItems, loadRepos, type PrChecksView } from "../data/mirror/index.ts"; +import { getBatch, loadBatchByBranch, loadBatchMembership, loadMergeFacts, type MergeFacts } from "../data/merge/index.ts"; +import { loadOperatorFixResults, loadPushEdges, ownPushKind, type PushEdge } from "../data/changes/index.ts"; +import { loadReviewsAt } from "../data/review/index.ts"; +import { isRunning } from "../data/jobs/index.ts"; +import { addTurns } from "../data/conversations/index.ts"; +import { + addFixupRequests, addLegs, adoptLegs, endFixupRequests, loadFixupRequests, loadHolds, loadLegPass, loadLegs, loadRepins, loadWorkflowFacts, moveLegs, + type LegContext, type LegMove, type LegRow, type LegState, type WorkflowFact, +} from "../data/workflow/index.ts"; import type { Db } from "../db/index.ts"; -import type { NotNull } from "kysely"; -import * as kx from "../db/kx.ts"; import { readSeqs } from "../live.ts"; import { INPUT_TOPICS } from "../runner/autopilot.ts"; @@ -48,20 +50,19 @@ export type PipelineStep = Extract; const ACTOR = "pipeline"; export const INSTRUCTIONS_MAX = 1500; -const ACTIVE = ["fixup", "review", "ci", "queued"] as const; +const ACTIVE: readonly LegState[] = ["fixup", "review", "ci", "queued"]; /** Plan states in which the PR gets no review, so a pre-approved merge cannot go on. A label never stops one: a live pre-approval lifts the label gate (src/core/decide.ts). */ const NOT_REVIEWABLE = ["out-of-scope", "integration", "backlog", "duplicate", "draft", "scope"]; const iso = () => new Date().toISOString(); const short = (sha: string | null) => (sha ?? "").slice(0, 7); const oneLine = (s: string, n = 200) => s.replace(/\s+/g, " ").trim().slice(0, n); +const refOf = (repo: string, n: number) => `${repo}#${n}`; -type Row = { id: number; repo: string; number: number; by: string; at: string; instructions: string; state: Preapproval["state"]; from_head: string; head: string | null; reason: string | null; updated_at: string; fix_id: number | null }; +type Row = LegRow; type PrRow = { state: string; head_oid: string | null; kind: string; head_repo: string | null; head_ref: string | null }; const prRow = async (db: Db, repo: string, n: number): Promise => - await db.get(db.k.selectFrom("items").select(["state", "head_oid", "kind", "head_repo", "head_ref"]).where("repo", "=", repo).where("number", "=", n)); - -const preapprovalRows = (db: Db) => db.k.selectFrom("preapprovals").select(kx.cols("preapprovals")).$narrowType<{ state: Row["state"] }>(); + (await loadItems(db, [{ repo, number: n }], "pr")).get(refOf(repo, n)); /** The PR's plan state as it would be with a live pre-approved merge, which lifts the label gate: what a new pre-approval can count on. */ function preapprovedState(f: PrFacts | null): string | null { @@ -72,73 +73,76 @@ const toView = (r: Row): Preapproval => ({ id: r.id, by: r.by, at: r.at, instruc /** The newest pre-approved merge of the PR, or null. */ export async function preapprovalOf(db: Db, repo: string, n: number): Promise { - const r = await db.get(preapprovalRows(db).where("repo", "=", repo).where("number", "=", n).orderBy("id", "desc").limit(1)); + const r = (await loadLegs(db, [{ repo, number: n }], { latestOnly: true })).get(refOf(repo, n))?.at(-1); return r ? toView(r) : null; } /** Every pre-approved merge of the PR, oldest first. */ export async function preapprovalsOf(db: Db, repo: string, n: number): Promise { - return (await db.all(preapprovalRows(db).where("repo", "=", repo).where("number", "=", n).orderBy("id"))).map(toView); + return ((await loadLegs(db, [{ repo, number: n }])).get(refOf(repo, n)) ?? []).map(toView); } -/** The system line of the item's thread (when it has a conversation). Not inside a transaction: the thread writes its own. */ -async function say(db: Db, repo: string, n: number, text: string): Promise { - if (await conversationOf(db, repo, n)) await insertTurn(db, repo, n, { kind: "system", login: "system", body: text, block: systemBlock(text) }); +/** The system lines of the items' threads (items with no conversation are skipped). Not inside a transaction: the thread writes its own. */ +async function sayAll(db: Db, lines: { repo: string; number: number; text: string }[]): Promise { + if (!lines.length) return; + await addTurns(db, lines.map((l) => ({ ref: refOf(l.repo, l.number), kind: "system", login: "system", body: l.text, block: systemBlock(l.text), onlyIfThread: true }))); } +const say = async (db: Db, repo: string, n: number, text: string): Promise => await sayAll(db, [{ repo, number: n, text }]); -/** Moves the row to `to` when it is still in its state; audits the transition (the trace shows it). Callable inside a transaction. */ -async function moveRaw(db: Db, p: Row, to: Row["state"], o: { head?: string | null; reason?: string | null; by?: string; via?: string }): Promise { - // A head the call does not give leaves the row's head as it is. - const r = await db.run(db.k.updateTable("preapprovals").set({ state: to, reason: o.reason ?? null, updated_at: iso(), ...(o.head != null ? { head: o.head } : {}) }) - .where("id", "=", p.id).where("state", "=", p.state)); - if (r.changes !== 1) return false; - // A fix-up request that has no try yet must not start after the pre-approval ended; a push that is already running is recorded by the fix-up step as usual. - if (["asked", "cancelled", "failed", "merged"].includes(to) && p.fix_id !== null) await db.run(db.k.updateTable("operator_fixups").set({ state: "ended" }).where("id", "=", p.fix_id)); - const head = o.head ?? p.head; - await audit(db, o.by ?? ACTOR, "preapproval", `${p.repo}#${p.number}`, { id: p.id, from: p.state, state: to, ...(head ? { head } : {}), ...(o.reason ? { reason: o.reason } : {}), ...(o.via ? { via: o.via } : {}) }); - return true; +/** Moves the row to `to` when it is still in its state; the module audits the transition (the trace shows it). Joins a caller's transaction. */ +async function moveRaw(db: Db, p: Row, to: LegState, o: { head?: string | null; reason?: string | null; by?: string; via?: string }): Promise { + const m: LegMove = { id: p.id, from: p.state, to, ...(o.head != null ? { head: o.head } : {}), reason: o.reason ?? null, ...(o.by ? { by: o.by } : {}), ...(o.via ? { via: o.via } : {}) }; + return (await moveLegs(db, [m])).length === 1; } /** `moveRaw`, then says it in the thread. Not inside a transaction: the thread writes its own. */ -async function move(db: Db, p: Row, to: Row["state"], o: { head?: string | null; reason?: string | null; by?: string; line: string }): Promise { +async function move(db: Db, p: Row, to: LegState, o: { head?: string | null; reason?: string | null; by?: string; line: string }): Promise { if (!await moveRaw(db, p, to, o)) return false; await say(db, p.repo, p.number, o.line); return true; } /** - * An operator, or a maintainer who still settles on the repo (src/settlers.ts): their Merge answer and approval count. `held` is the pass's + * An operator, or a maintainer who still settles on the repo (src/settlers.ts): their approval counts. `held` is the pass's * `refreshSettlers` result: a maintainer's write permission the pipeline is reading again still counts until GitHub answers. */ const isOperator = async (db: Db, login: string | null, repo: string, held?: ReadonlySet): Promise => await settlesNow(db, login, [repo], { ...settleMemo(), held }); -/** Takes back the Merge answer the hand-over wrote at the row's head (an answer anyone else wrote, or one already applied, stays). Inside the caller's transaction. */ -export async function revertAnswer(db: Db, p: Row, by: string): Promise { - if (!p.head) return false; - const id = mergeDecisionId(p.repo, p.number, p.head); - if (!await db.get(db.k.selectFrom("audit").select((eb) => eb.lit(1).as("one")).where("action", "=", "answer").where("target", "=", id).where((w) => kx.like(db, "details", w.val('%"source":"preapproval"%'))))) return false; - const r = await db.run(db.k.updateTable("main.decisions").set({ answer: null, answer_note: null, exceptions: null, answered_by: null, answered_at: null, applied_at: null, adopted_opinion: null, exec_state: null, exec_reason: null, dispute_by: null, dispute_reason: null, dispute_at: null }) - .where("id", "=", id).where("answer", "=", "merge").where("applied_at", "is", null).where("answered_by", "=", p.by)); - if (r.changes !== 1) return false; - await audit(db, by, "undo", id, { answer: "merge", source: "preapproval" }); - return true; +/** The PR's newest merge attempt at `head` merged it. */ +const mergedAt = (m: MergeFacts, repo: string, n: number, head: string | null): boolean => !!head && m.attempts.get(`${refOf(repo, n)}@${head}`)?.outcome === "merged"; + +/** + * Whether the merge leg may merge at `head`: the workflow's approval (mayMerge, src/core/may.ts), else the repo's merge approval. + * The leg's own head rules decide which heads it may merge (a push that is not ours cancels it), so the gate takes `head` as the base. + */ +function mergeGate(approval: StepApproval | null, wf: WorkflowFact | null, head: string): { ok: true } | { ok: false; why: string } { + const workflow: WorkflowGate | null = wf ? { + live: true, entry: wf.entry as WorkflowGate["entry"], state: wf.state, startedBy: wf.startedBy, approvedBy: wf.approvedBy, approvedAt: null, + blocker: wf.state === "blocked" ? "the workflow is blocked" : null, baseHead: head, fixupAsked: false, + } : null; + const r = mayMerge({ repoApproval: approval, workflow, head, ownHeads: new Set([head]) }); + return r.ok ? { ok: true } : { ok: false, why: r.why }; } -/** Cancels the row and takes the hand-over answer back in one transaction, whatever state the caller read. False when the row had ended meanwhile. */ -async function cancelRow(db: Db, id: number, by: string, reason: string, line: string, guard = false, via?: string): Promise { +/** The live workflow of the PR, or of the issue it implements, and the repo's merge approval. */ +async function gateFacts(db: Db, repo: string, n: number): Promise<{ wf: WorkflowFact | null; approval: StepApproval | null }> { + const [facts, approvals] = await db.together(() => Promise.all([loadWorkflowFacts(db, [{ repo, number: n }]), loadStepApprovals(db, [repo], ["merge"])])); + return { wf: facts.live.get(refOf(repo, n)) ?? facts.ofPr.get(refOf(repo, n)) ?? null, approval: approvals.get(repo)?.merge ?? null }; +} + +/** Cancels the row in one transaction, whatever state the caller read. False when the row had ended meanwhile. */ +async function cancelRow(db: Db, leg: { id: number; repo: string; number: number }, by: string, reason: string, line: string, guard = false, via?: string): Promise { // Nothing is written before an early return, so committing leaves the database as a rollback would. const p = await db.write(async () => { - const p = await db.get(preapprovalRows(db).where("id", "=", id)); - if (!p || !(ACTIVE as readonly string[]).includes(p.state)) return null; + const p = (await loadLegs(db, [{ repo: leg.repo, number: leg.number }], { activeOnly: true })).get(refOf(leg.repo, leg.number))?.find((r) => r.id === leg.id); + if (!p || !ACTIVE.includes(p.state)) return null; // Past the guard of the merge queue, a cancel cannot stop the merge: a batch holds the PR, or it is merged. if (guard && p.state === "queued") { if (await inActiveBatch(db, p.repo, p.number)) throw new Error("the PR is still in an integration batch"); if (await mergeRunning(db, p.repo)) throw new Error("a merge of the repo is running: it may be merging this PR"); - if (p.head && await db.get(db.k.selectFrom("merges").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("head_oid", "=", p.head).where("outcome", "=", "merged"))) throw new Error("the PR is already merged"); + if (mergedAt(await loadMergeFacts(db, [{ repo: p.repo, number: p.number }]), p.repo, p.number, p.head)) throw new Error("the PR is already merged"); } - if (!await moveRaw(db, p, "cancelled", { by, reason, via })) return null; - await revertAnswer(db, p, by); - return p; + return await moveRaw(db, p, "cancelled", { by, reason, via }) ? p : null; }); if (!p) return false; await say(db, p.repo, p.number, line); @@ -169,9 +173,11 @@ export async function runPipelineStep(db: Db, o: { repo: string; number: number; if (instructions.length > INSTRUCTIONS_MAX) throw new Error(`the instructions are over ${INSTRUCTIONS_MAX} characters`); const head = it.head_oid; if (!head) throw new Error(`${ref} has no head commit in the mirror yet`); - const checks = await db.get(db.k.selectFrom("pr_checks").select(["head_oid", "mergeable", "maintainer_can_modify"]).where("repo", "=", repo).where("number", "=", number)); + const checks = (await loadChecks(db, [{ repo, number }])).get(refOf(repo, number)) as PrChecksView | undefined; if (checks?.mergeable === "CONFLICTING") throw new Error(`${ref} conflicts with its base branch: the conflict merge comes first`); - if (!await pushApprovalOf(db, repo)) throw new Error(`pushing is not approved for ${repo}`); + // A person's fix-up runs as that person (mayPush, src/core/may.ts); the repo's push approval is for pushes nobody asked for. + const may = mayPush({ kind: "fixup", repoApproval: null, workflow: null, operatorFix: true, by }); + if (!may.ok) throw new Error(may.why); const writes = await ensureAuthorWrites(db, repo, number, it.head_repo); if (writes === "unknown") throw new Error("the author's permission on the repository could not be read yet; try again"); if (!pushable(it.head_repo, repo, checks?.head_oid === head ? checks.maintainer_can_modify : null, it.head_ref, await longLivedOf(db, repo), false, writes === "yes")) throw new Error("can't push to the contributor's branch"); @@ -179,28 +185,23 @@ export async function runPipelineStep(db: Db, o: { repo: string; number: number; if (await queuedOperatorFix(db, repo, number, head)) throw new Error(`a fix-up of ${ref} is already queued`); const merge = step.merge === true; const activeCheck = async () => { - if (await db.get(db.k.selectFrom("preapprovals").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", number).where("state", "in", ACTIVE))) throw new Error(`${ref} already has a pre-approved merge in progress`); + if ((await loadLegs(db, [{ repo, number }], { activeOnly: true })).has(ref)) throw new Error(`${ref} already has a pre-approved merge in progress`); }; + let workflowId: number | undefined; if (merge) { - if (!await mergeApprovalOf(db, repo)) throw new Error(`merging is not approved for ${repo}`); + const g = await gateFacts(db, repo, number); + const ok = mergeGate(g.approval, g.wf, head); + if (!ok.ok) throw new Error(g.wf ? ok.why : `merging is not approved for ${repo}`); + workflowId = g.wf?.id; await activeCheck(); } - const at = iso(); - let id: number | null = null; - await db.write(async () => { - // Checked again under the write lock: another writer may have started one since the first check. - if (merge) await activeCheck(); - const fix = (await db.get(db.k.insertInto("operator_fixups").values({ repo, number, from_head: head, instructions, by, at }).returning("id")))!.id; - if (merge) { - id = (await db.get(db.k.insertInto("preapprovals").values({ repo, number, by, at, instructions, state: "fixup", from_head: head, updated_at: at, fix_id: fix }).returning("id")))!.id; - await db.run(db.k.updateTable("operator_fixups").set({ preapproval_id: id }).where("id", "=", fix)); - } - await audit(db, by, merge ? "preapproval" : "operator-fixup", ref, merge ? { id, state: "fixup", head } : { head, queued: true }); - }); + // The insert of a merge request refuses a second active leg itself (the partial unique index): it throws and writes nothing. + const made = (await addFixupRequests(db, [{ repo, number, fromHead: head, instructions, by, merge, ...(workflowId !== undefined ? { workflowId } : {}) }])).get(ref); + const id = made?.legId ?? null; await say(db, repo, number, merge ? `${by} approved a merge after a fix-up: a fix-up of ${short(head)} is queued; if its review says take and CI is green, the PR goes to the merge queue.` : `${by} queued a fix-up of ${short(head)}.`); - return { label: merge ? "Queued the fix-up; the PR merges if its review says take and CI is green" : "Queued the fix-up", ...(id !== null && { preapproval: id }) }; + return { label: merge ? "Queued the fix-up; the PR merges if its review says take and CI is green" : "Queued the fix-up", ...(id !== null ? { preapproval: id } : {}) }; } /** Why a PR in a NOT_REVIEWABLE plan state gets no code review, in words a commenter can act on. */ @@ -246,17 +247,15 @@ export async function preapproveMerge(db: Db, o: { repo: string; number: number; const head = it.head_oid; if (!head) throw new Error(`${ref} has no head commit in the mirror yet`); if (o.head !== undefined && head !== o.head) throw new Error(HEAD_CHANGED); - if (!await mergeApprovalOf(db, repo)) throw new PreapprovalRefused(`merging is not approved for ${repo}`); - const active = async () => await db.get(db.k.selectFrom("preapprovals").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", number).where("state", "in", ACTIVE)); - if (await active()) throw new PreapprovalRefused(`${ref} already has a pre-approved merge in progress`, true); - const at = iso(); - await db.write(async () => { - // Checked again under the write lock: another writer may have started one since the first check. - if (await active()) throw new PreapprovalRefused(`${ref} already has a pre-approved merge in progress`, true); - // `workflowId`: the maintainer workflow whose merge leg this is, written with the row so no pass sees it unowned. - const id = (await db.get(db.k.insertInto("preapprovals").values({ repo, number, by, at, instructions: "", state: "review", from_head: head, head, updated_at: at, fix_id: null, workflow_id: o.workflowId ?? null }).returning("id")))!.id; - await audit(db, by, "preapproval", ref, { id, state: "review", head, queued: "merge-queue", ...(via ? { via } : {}) }); - }); + const g = await gateFacts(db, repo, number); + const wf = o.workflowId !== undefined && g.wf?.id !== o.workflowId ? null : g.wf; + const ok = mergeGate(g.approval, wf, head); + if (!ok.ok) throw new PreapprovalRefused(wf ? ok.why : `merging is not approved for ${repo}`); + const busy = () => new PreapprovalRefused(`${ref} already has a pre-approved merge in progress`, true); + if ((await loadLegs(db, [{ repo, number }], { activeOnly: true })).has(ref)) throw busy(); + // `workflowId`: the workflow whose merge leg this is, written with the row so no pass sees it unowned. The insert refuses a second active leg. + const made = (await addLegs(db, [{ repo, number, by, workflowId: (o.workflowId ?? wf?.id ?? null) as number, head, state: "review", ...(via ? { via } : {}) }])).get(ref); + if (made === "active") throw busy(); await say(db, repo, number, `${by} added the PR to the merge queue at ${short(head)}: it merges once the review there says take, the pre-merge review is clean and CI is green.`); return { label: "Added to the merge queue; it merges once the review says take and CI is green" }; } @@ -271,70 +270,63 @@ function headName(p: Row): string { return p.fix_id !== null ? "the pushed head" : p.head !== p.from_head ? "the new head" : "the PR's head"; } -/** The fact line naming the review a stop or hand-over rests on. */ -const reviewFact = (p: Row, what: string) => `review of ${p.fix_id !== null ? "the fix-up" : headName(p)}: ${what}`; +/** What one advance pass reads of the legs' PRs, loaded in one wave for every active leg. */ +type PassFacts = { + items: Map; + checks: Map; + syncedAt: Map; + merge: MergeFacts; + fixResults: Map; + edges: Map; + /** `ref` -> from -> to of the implementation session's revisions. */ + implPushes: Map>; + /** `ref` -> autorepins that are waiting, locking or pushed. */ + repins: Map; + approvals: Map; + workflows: Map; + reviews: Map; +}; -/** Asks a Merge? question at `head` the normal way (Prepare writes its options and recommendation); an answered one is left as it is. */ -async function askMerge(db: Db, p: Row, head: string, why: string, facts: string[]): Promise { - const id = mergeDecisionId(p.repo, p.number, head); - if ((await getDecision(db, id))?.answer) return; - const at = iso(); - await ask(db, [{ - id, kind: "merge", repo: p.repo, number: p.number, question: "Merge this PR?", - context: p.fix_id !== null ? `${p.by} approved a merge after a fix-up, but it stopped: ${why}.` : `${p.by} approved the merge ahead of its review and CI, but it stopped: ${why}.`, - facts: [...facts.slice(0, 4), `${HEAD_FACT}${head}`], options: Object.values(MERGE_OPTIONS).map((x) => ({ ...x })), asked_by: ACTOR, asked_at: at, - }]); - await withdrawOtherHeadQuestions(db, p.repo, p.number, head, at); - await setAsideSupersededQuestions(db, at, p.repo); +async function loadPassFacts(db: Db, rows: Row[]): Promise { + const refs = [...new Map(rows.map((r) => [refOf(r.repo, r.number), { repo: r.repo, number: r.number }])).values()]; + const repos = [...new Set(rows.map((r) => r.repo))]; + const heads = rows.flatMap((r) => (r.head ? [{ repo: r.repo, number: r.number, head: r.head }] : [])); + const fixIds = rows.flatMap((r) => (r.fix_id !== null ? [r.fix_id] : [])); + const [items, checks, repoRows, merge, fixResults, edges, outcomes, repins, approvals, wfFacts, reviews] = await db.together(() => Promise.all([ + loadItems(db, refs, "pr"), loadChecks(db, refs), loadRepos(db, { names: repos }), loadMergeFacts(db, refs), loadOperatorFixResults(db, fixIds), + loadPushEdges(db, refs), listPushOutcomes(db, { refs: refs.map((r) => refOf(r.repo, r.number)) }), loadRepins(db, refs, { states: ["waiting", "locking", "pushed"] }), + loadStepApprovals(db, repos, ["merge"]), loadWorkflowFacts(db, refs), loadReviewsAt(db, heads), + ])); + const implPushes = new Map>(); + for (const o of outcomes) { + if (o.action !== "implement-push" || o.number === null || !o.from_oid) continue; + const k = refOf(o.repo, o.number); + (implPushes.get(k) ?? implPushes.set(k, new Map()).get(k)!).set(o.from_oid, o.to_oid); + } + const workflows = new Map(); + for (const f of [...wfFacts.live.values(), ...wfFacts.ofPr.values()]) workflows.set(f.id, f); + return { + items, checks, merge, fixResults, edges, implPushes, workflows, + syncedAt: new Map(repos.map((r) => [r, repoRows.get(r)?.synced_at ?? null])), + repins: new Map([...repins].map(([k, v]) => [k, v.map((x) => ({ head: x.head, to_head: x.to_head }))])), + approvals: new Map(repos.map((r) => [r, approvals.get(r)?.merge ?? null])), + reviews: new Map([...reviews].map(([k, v]) => [k, { verdict: v.verdict, sure: v.sure, reason: v.reason, at: v.at }])), + }; } type Hand = { done: true } | { gone: true } | { wait: true } | { stop: string }; -/** - * Moves the row from ci to queued and answers the PR's Merge? decision at `head` with Merge for the operator, as the dashboard would, - * in one transaction: a cancel that ran first leaves the row cancelled and nothing answered. Idempotent. - */ -async function handOver(db: Db, p: Row, head: string, held: ReadonlySet, unsure = false): Promise { - const id = mergeDecisionId(p.repo, p.number, head); - const at = iso(); - const premergeWord = unsure ? "found no defect but could not verify every claim of the description" : "is clean"; - // Nothing is written before an early return, so committing leaves the database as a rollback would. - const stopped = await db.write(async (): Promise => { - if (!await isOperator(db, p.by, p.repo, held)) return { stop: `${p.by} no longer settles decisions on ${p.repo}` }; - // A hand-over waits for a running verification and never answers Merge over a failed one: the operator is asked. - if (await db.get(db.k.selectFrom("verifications").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("head_sha", "=", head).where("state", "in", ["planned", "running"]))) return { wait: true }; - if (await db.get(db.k.selectFrom("verifications").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("head_sha", "=", head).where("state", "in", ["failed", "error"]))) return { stop: `verification failed at ${headName(p)}` }; - const d0 = await getDecision(db, id); - if (d0 && d0.answer !== null && d0.answer !== "merge") return { stop: `the Merge? question at this head was answered ${d0.answer}` }; - // A conversation card is settling the question right now: the hand-over waits for it instead of answering over it. - if (d0 && d0.answer === null && await db.get(db.k.selectFrom("main.decisions").select((eb) => eb.lit(1).as("one")).where("id", "=", id).where((eb) => lockLiveExpr(db, eb, "decisions")))) return { wait: true }; - if (!await moveRaw(db, p, "queued", { head })) return { gone: true }; - if (!await getDecision(db, id)) { - await ask(db, [{ - id, kind: "merge", repo: p.repo, number: p.number, question: "Merge this PR?", - context: p.fix_id !== null - ? `${p.by} approved this merge ahead of a fix-up; the fix-up was pushed, its review says take, CI is green and its pre-merge review ${premergeWord}.` - : `${p.by} approved this merge ahead of its review and CI; the review says take, CI is green and the pre-merge review ${premergeWord}.`, - facts: [ - ...(p.fix_id !== null ? [`fix-up pushed by the pipeline from ${short(p.from_head)} to ${short(head)}`] : head !== p.from_head ? [`base merge pushed by the pipeline from ${short(p.from_head)} to ${short(head)}`] : []), - `${HEAD_FACT}${head}`, - ], - options: Object.values(MERGE_OPTIONS).map((x) => ({ ...x })), asked_by: ACTOR, asked_at: at, - }], true); - } - if ((await getDecision(db, id))!.answer === null) { - await db.run(db.k.updateTable("main.decisions").set({ answer: "merge", answer_note: null, exceptions: null, answered_by: p.by, answered_at: at, adopted_opinion: null, snoozed_by: null, snoozed_at: null }) - .where("id", "=", id).where("answer", "is", null).where((eb) => eb.not(lockLiveExpr(db, eb, "decisions")))); - await db.run(db.k.deleteFrom("main.decision_claims").where("decision_id", "=", id)); - await replaceProposedCards(db, p.repo, p.number, id); - await audit(db, p.by, "answer", id, { answer: "merge", source: "preapproval" }); - } - return null; - }); - if (stopped) return stopped; +/** Moves the row from ci to queued: the merge queue merges it as the workflow's approver from here. Idempotent. */ +async function handOver(db: Db, p: Row, head: string, held: ReadonlySet, pf: PassFacts, unsure = false): Promise { + if (!await isOperator(db, p.by, p.repo, held)) return { stop: `${p.by} no longer settles decisions on ${p.repo}` }; + // A hand-over waits for a running verification and never goes on over a failed one. + const v = pf.merge.verifications.get(`${refOf(p.repo, p.number)}@${head}`); + if (v && (v.state === "planned" || v.state === "running")) return { wait: true }; + if (v && (v.state === "failed" || v.state === "error")) return { stop: `verification failed at ${headName(p)}` }; + if (!await moveRaw(db, p, "queued", { head })) return { gone: true }; await say(db, p.repo, p.number, unsure - ? "CI is green and the pre-merge review found no defect, though it could not verify every claim of the description: the merge was approved, so the PR is in the merge queue, which checks it as for any Merge answer." - : "CI is green and the pre-merge review is clean: the PR is in the merge queue, which checks it as for any Merge answer."); + ? "CI is green and the pre-merge review found no defect, though it could not verify every claim of the description: the merge was approved, so the PR is in the merge queue, which checks it as for any approved merge." + : "CI is green and the pre-merge review is clean: the PR is in the merge queue, which checks it as for any approved merge."); return { done: true }; } @@ -344,13 +336,12 @@ type ReviewRead = { kind: "none" | "stale" | "take" | "takefix" | "bad"; why: st * The Opus review at `head`. A take or take-fix that is not stale goes on, sure or unsure: the merge approval says the change is wanted, * so a take-fix is the pipeline's own fix-up to make and the pre-approval goes on with its push. Any other verdict stops it. */ -async function reviewAt(db: Db, p: Row, head: string, wake?: Wake): Promise { - const r = await db.get(db.k.selectFrom("opus_reviews").select(["verdict", "sure", "reason", "at"]).$narrowType<{ verdict: NotNull }>() - .where("repo", "=", p.repo).where("number", "=", p.number).where("head_oid", "=", head).where("verdict", "is not", null)); +async function reviewAt(db: Db, p: Row, head: string, pf: PassFacts, wake?: Wake): Promise { + const r = pf.reviews.get(`${refOf(p.repo, p.number)}@${head}`); if (!r) return { kind: "none", why: "", unsure: false }; - const ref = `${p.repo}#${p.number}`; + const ref = refOf(p.repo, p.number); if ((await staleReviews(db, p.repo, false, { refresh: (r, at) => (r === ref ? wake?.(at) : undefined) })).has(`${ref}@${head}`)) return { kind: "stale", why: "", unsure: false }; - const unsure = r.sure !== 1; + const unsure = !r.sure; if (r.verdict === "take") return { kind: "take", why: "", unsure, at: r.at }; if (r.verdict === "take-fix") return { kind: "takefix", why: r.reason ? oneLine(r.reason, 160) : "", unsure, at: r.at }; return { kind: "bad", why: `the review says ${r.verdict}${unsure ? " (unsure)" : ""}${r.reason ? `: ${oneLine(r.reason, 160)}` : ""}`, unsure, at: r.at }; @@ -361,10 +352,11 @@ const approvedAhead = (p: Row) => (p.fix_id !== null ? "the merge was approved w /** Says `line` in the thread once per row, head and note (the audit entry is the memory): for a wait that moves the row nowhere. */ async function noteOnce(db: Db, p: Row, head: string, note: string, line: string): Promise { - const ref = `${p.repo}#${p.number}`; - if (await db.get(db.k.selectFrom("audit").select((eb) => eb.lit(1).as("one")).where("action", "=", "preapproval").where("target", "=", ref) - .where(kx.jsonNum(db, "details", "$.id"), "=", p.id).where(kx.jsonText(db, "details", "$.note"), "=", note).where(kx.jsonText(db, "details", "$.head"), "=", head).limit(1))) return; - await audit(db, ACTOR, "preapproval", ref, { id: p.id, head, note }); + const ref = refOf(p.repo, p.number); + const seen = ((await loadAuditActions(db, [ref], ["preapproval"])).get(ref) ?? []) + .some((a) => a.details?.id === p.id && a.details?.note === note && a.details?.head === head); + if (seen) return; + await addAudit(db, [{ login: ACTOR, action: "preapproval", target: ref, details: { id: p.id, head, note } }]); await say(db, p.repo, p.number, line); } @@ -372,15 +364,15 @@ async function noteOnce(db: Db, p: Row, head: string, note: string, line: string * "base merge", "autorepin", "fix-up for the review's fixes" or the implementation session's revision when the pipeline itself pushed `cur` on top of the row's head, else null. * The review's fix-up counts for every row: the merge approval says the change is wanted, and the fix-up's push gets a fresh review. */ -async function ownPush(db: Db, p: Row, cur: string): Promise { - if (await db.get(db.k.selectFrom("fixups").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("from_head", "=", p.head).where("to_head", "=", cur) - .where((eb) => eb(eb.fn.coalesce("source", eb.val("review")), "=", "review")).where("state", "in", ["pushing", "pushed"]))) return "fix-up for the review's fixes"; - // Only a base merge that left the PR's own diff unchanged continues an answer; a CI fix or a resolved conflict is model-written code nobody saw. - if (await db.get(db.k.selectFrom("conflict_merges").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("from_head", "=", p.head).where("to_head", "=", cur).where("state", "=", "merged").where("own_diff", "=", "same"))) return "base merge"; +function ownPush(p: Row, cur: string, pf: PassFacts): string | null { + const ref = refOf(p.repo, p.number); + // Only a base merge that left the PR's own diff unchanged continues an approval; a CI fix or a resolved conflict is model-written code nobody saw. + const kind = p.head ? ownPushKind(pf.edges.get(ref) ?? [], p.head, cur) : null; + if (kind) return kind; // A revision of our implementation PR by the session that wrote it: the PR is the queuer's implementation, and the push gets a fresh review. - if (await db.get(db.k.selectFrom("push_outcomes").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("action", "=", "implement-push").where("from_oid", "=", p.head).where("to_oid", "=", cur))) return "implementation session's revision"; + if (p.head && pf.implPushes.get(ref)?.get(p.head) === cur) return "implementation session's revision"; // An autorepin (src/repin) is no model's code either: the revs of a dependency moved to a merge commit on its default branch, as someone who may queue the PR asked. - if (await db.get(db.k.selectFrom("main.autorepins").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("head", "=", p.head).where("to_head", "=", cur).where("state", "in", ["waiting", "locking", "pushed"]))) return "autorepin"; + if ((pf.repins.get(ref) ?? []).some((a) => a.head === p.head && a.to_head === cur)) return "autorepin"; return null; } @@ -410,53 +402,47 @@ function stepRuns(f: PrFacts, step: "cifix" | "conflict"): boolean { const FAILED_FIXUP = ["failed", "refused", "rejected", "cannot-push", "too-large", "push-denied", "asked", "comment-failed", "superseded"]; /** - * One pre-approved merge: reads what the other steps recorded and makes at most one transition. - * - * The merge leg of a maintainer workflow (`legContext`) differs in three ways: a stop asks no Merge? question (the workflow stops at a - * blocker and gives its recommendation, src/workflow/advance.ts); a merge-queue entry has no Opus review to wait for; and a review the + * One merge leg: reads what the other steps recorded and makes at most one transition. A stop ends the leg failed: the workflow stops at a + * blocker and gives its recommendation (src/workflow/advance.ts). A merge-queue entry has no Opus review to wait for, and a review the * person answered after (a yes past a major finding) counts as a take. */ -async function advance(db: Db, p: Row, held: ReadonlySet, factOf: () => Promise, wake: Wake): Promise { - const it = await prRow(db, p.repo, p.number); - const ctx = await legContext(db, p.id); - const cancel = async (reason: string) => void await cancelRow(db, p.id, ACTOR, reason, `The pre-approved merge was cancelled: ${reason}.`); - // In a repo on the maintainer workflow a row never acts as a legacy pre-approval: the leg of an ended workflow ends with it, and a - // row no workflow owns waits for the start that is writing its workflow (stop, backlog and close cancel it by its PR). - if (ctx === "ended") return cancel("its workflow ended"); - if (ctx === "unlinked") return; - const leg = ctx; - const stop = async (to: "asked" | "failed", why: string, head: string, facts: string[] = [why]) => { - if (leg) return void await move(db, p, to, { reason: why, line: `The pre-approved merge stopped: ${why}.` }); - if (await move(db, p, to, { reason: why, line: `The pre-approved merge stopped: ${why}. A Merge? question was asked.` })) await askMerge(db, p, head, why, facts); - }; +async function advance(db: Db, p: Row, ctx: LegContext | "ended", held: ReadonlySet, pf: PassFacts, factOf: () => Promise, wake: Wake): Promise { + const ref = refOf(p.repo, p.number); + const it = pf.items.get(ref); + const cancel = async (reason: string) => void await cancelRow(db, p, ACTOR, reason, `The pre-approved merge was cancelled: ${reason}.`); + const cur = it?.head_oid ?? null; + const mergedByQueue = mergedAt(pf.merge, p.repo, p.number, p.head); + if (p.state === "queued" && (it?.state === "MERGED" || mergedByQueue)) return void await move(db, p, "merged", { line: "The pre-approved merge went through: the PR is merged." }); + if (ctx === "ended") { + // The workflow of a merged PR ends before this pass sees the merge: a queued leg whose merge is under way is left for merge detection, + // so its history shows the merge and not a cancel. + if (p.state === "queued" && it?.state === "OPEN" && await mergeRunning(db, p.repo)) return; + if (it?.state !== "MERGED") return cancel("its workflow ended"); + } + const leg = ctx === "ended" ? null : ctx; + const stop = async (why: string) => void await move(db, p, "failed", { reason: why, line: `The pre-approved merge stopped: ${why}.` }); // A review the person had seen when they last answered: they chose to go on. const accepted = (r: ReviewRead): ReviewRead => (leg && r.kind === "bad" && r.at !== undefined && r.at <= leg.since ? { ...r, kind: "take" } : r); if (!it) return cancel("the PR is gone"); - const cur = it.head_oid; - const mergedByQueue = !!p.head && !!await db.get(db.k.selectFrom("merges").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("head_oid", "=", p.head).where("outcome", "=", "merged")); - if (p.state === "queued" && (it.state === "MERGED" || mergedByQueue)) return void await move(db, p, "merged", { line: "The pre-approved merge went through: the PR is merged." }); if (it.state === "MERGED") return cancel(p.fix_id !== null ? "the PR was merged before the fix-up finished" : "the PR was merged before the pre-approved merge reached the merge queue"); if (it.state !== "OPEN") return cancel("the PR was closed"); - // The fix-up and the review that follows run on the maker's authority; the queued state re-checks the Merge answer below. + // The fix-up and the review that follows run on the maker's authority; the queued state re-checks the approval below. if (p.state !== "queued" && !await isOperator(db, p.by, p.repo, held)) return cancel(`${p.by} no longer settles decisions on ${p.repo}`); if (p.state === "fixup") { - const fx = await db.get(db.k.selectFrom("fixups").select(["state", "to_head", "reason"]).where("operator_fix", "=", p.fix_id).where("source", "=", "operator").orderBy(kx.rowid("fixups"), "desc").limit(1)); - if (fx?.state === "pushed" && fx.to_head) return void await move(db, p, "review", { head: fx.to_head, line: `The fix-up pushed ${short(fx.to_head)}; Opus reviews it next.` }); - if (fx && FAILED_FIXUP.includes(fx.state)) { - const why = `the fix-up ${fx.state}${fx.reason ? `: ${oneLine(fx.reason, 120)}` : ""}`; - return await stop("failed", why, cur ?? p.from_head); - } + const fx = p.fix_id !== null ? pf.fixResults.get(p.fix_id) : undefined; + if (fx?.state === "pushed" && fx.toHead) return void await move(db, p, "review", { head: fx.toHead, line: `The fix-up pushed ${short(fx.toHead)}; Opus reviews it next.` }); + if (fx && FAILED_FIXUP.includes(fx.state)) return await stop(`the fix-up ${fx.state}${fx.reason ? `: ${oneLine(fx.reason, 120)}` : ""}`); // A push written before it ran: when the head is its commit, it landed. - if (fx?.state === "pushing" && fx.to_head && cur === fx.to_head) return void await move(db, p, "review", { head: fx.to_head, line: `The fix-up pushed ${short(fx.to_head)}; Opus reviews it next.` }); + if (fx?.state === "pushing" && fx.toHead && cur === fx.toHead) return void await move(db, p, "review", { head: fx.toHead, line: `The fix-up pushed ${short(fx.toHead)}; Opus reviews it next.` }); // Whatever the fix-up row says (none yet, linting, pushing), a head that is neither its start nor its push is someone else's. - if (cur !== null && cur !== p.from_head && cur !== fx?.to_head) return cancel(`another push moved the head to ${short(cur)}`); + if (cur !== null && cur !== p.from_head && cur !== fx?.toHead) return cancel(`another push moved the head to ${short(cur)}`); // No try yet and the planner would not work the request (not pushable, conflicting, a draft, ...): it would wait for ever. if (!fx) { const f = await factOf(); const why = f ? await whyNotPlanned(db, f) : null; - if (why) await stop("asked", `the fix-up cannot run: ${why}`, cur ?? p.from_head); + if (why) await stop(`the fix-up cannot run: ${why}`); } return; } @@ -465,12 +451,11 @@ async function advance(db: Db, p: Row, held: ReadonlySet, factOf: () => const head = p.head!; if (cur !== null && cur !== head) { // The mirror row shows the old head until a sync that started after the push has finished (synced_at is the sync's start; the row's state entry follows the push); a review at the pushed head also shows the mirror saw it. - const synced = (await db.get(db.k.selectFrom("repos").select("synced_at").where("name", "=", p.repo)))?.synced_at ?? null; - const lag = p.state === "review" && cur === p.from_head && (synced === null || synced <= p.updated_at) - && !await db.get(db.k.selectFrom("opus_reviews").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("head_oid", "=", head)); + const synced = pf.syncedAt.get(p.repo) ?? null; + const lag = p.state === "review" && cur === p.from_head && (synced === null || synced <= p.updated_at) && !pf.reviews.has(`${ref}@${head}`); if (!lag && p.state !== "queued") { // The pipeline's own CI fix or conflict merge on the pushed head carries the pre-approval on: the new head needs the whole chain again. - const own = await ownPush(db, p, cur); + const own = ownPush(p, cur, pf); if (own) return void await move(db, p, "review", { head: cur, line: `The ${own} pushed ${short(cur)}; it needs a fresh review, a clean pre-merge review and green CI before the PR goes to the merge queue.` }); } if (!lag) return cancel(cur === p.from_head ? `the head went back to ${short(cur)}` : `another push moved the head to ${short(cur)}`); @@ -480,16 +465,16 @@ async function advance(db: Db, p: Row, held: ReadonlySet, factOf: () => return void await move(db, p, "ci", { line: `In the merge queue at ${short(head)} with no review; waiting for CI and a clean pre-merge review.` }); } if (p.state === "review") { - const r = accepted(await reviewAt(db, p, head, wake)); + const r = accepted(await reviewAt(db, p, head, pf, wake)); if (r.kind === "stale") return; if (r.kind === "none") { // No review is coming for a PR the planner does not review (an open scope question, a draft, a hold). const f = cur === head ? await factOf() : null; const state = f ? decidePr(f).state : null; - if (state && NOT_REVIEWABLE.includes(state)) return await stop("asked", `${headName(p)} cannot be reviewed (${state})`, head); + if (state && NOT_REVIEWABLE.includes(state)) return await stop(`${headName(p)} cannot be reviewed (${state})`); // The gate lifts every hold for a pre-approved head except a review that failed for good, which only a new request or push ends. const hold = cur === head ? await reviewHold(db, p.repo, p.number, head) : null; - if (hold?.kind === "failed" && hold.until === undefined) return await stop("asked", `the review of ${headName(p)} waits on ${hold.wait}`, head); + if (hold?.kind === "failed" && hold.until === undefined) return await stop(`the review of ${headName(p)} waits on ${hold.wait}`); return; } const name = p.fix_id !== null ? "the fix-up" : headName(p); @@ -505,149 +490,88 @@ async function advance(db: Db, p: Row, held: ReadonlySet, factOf: () => if (fx && ((fx.bucket === "fix" && !fx.done) || fx.bucket === "hold")) { return await noteOnce(db, p, head, "review-fixup", `The review of ${name} ${r.unsure ? "is unsure and asks" : "asks"} for fixes; ${approvedAhead(p)}, so the fix-up runs.`); } - return await stop("asked", `the review of ${name} asks for fixes and its fix-up cannot run${fx ? ` (${fx.bucket})` : ""}`, head, - [reviewFact(p, `take-fix${r.unsure ? " (unsure)" : ""}${r.why ? `: ${r.why}` : ""}`), "Recommended: Fix up first, then merge"]); + return await stop(`the review of ${name} asks for fixes and its fix-up cannot run${fx ? ` (${fx.bucket})` : ""}`); } - return await stop("asked", r.why, head, [reviewFact(p, r.why)]); + return await stop(r.why); } - if (!await mergeApprovalOf(db, p.repo)) return p.state === "queued" ? cancel("merging is no longer approved for the repo") : await stop("asked", "merging is no longer approved for the repo", head); + const gate = mergeGate(pf.approvals.get(p.repo) ?? null, leg ? pf.workflows.get(leg.workflowId) ?? null : null, head); + if (!gate.ok) return p.state === "queued" ? cancel("merging is no longer approved") : await stop("merging is no longer approved"); if (p.state === "ci") { // A re-review since the move to ci counts: the hand-over needs a take at this head now. A merge-queue entry has no review. - const r: ReviewRead = leg?.entry === "merge" ? { kind: "take", why: "", unsure: false } : accepted(await reviewAt(db, p, head, wake)); + const r: ReviewRead = leg?.entry === "merge" ? { kind: "take", why: "", unsure: false } : accepted(await reviewAt(db, p, head, pf, wake)); if (r.kind === "none" || r.kind === "stale") return void await move(db, p, "review", { line: `The review of ${headName(p)} is out of date; Opus reviews it again.` }); if (r.kind === "takefix") return void await move(db, p, "review", { line: `The review of ${headName(p)} now asks for fixes; the pipeline's fix-up comes first.` }); - if (r.kind === "bad") return await stop("asked", r.why, head, [reviewFact(p, r.why)]); - const c = await db.get(db.k.selectFrom("pr_checks").select(["overall", "mergeable"]).where("repo", "=", p.repo).where("number", "=", p.number).where("head_oid", "=", head)); - if (!c || c.overall === "pending") return; + if (r.kind === "bad") return await stop(r.why); + const c = pf.checks.get(ref); + if (!c || c.head_oid !== head || c.overall === "pending") return; if (c.overall === "failure") { - // The CI fix step works the red head as it would for any PR; its push is a head the operator did not see, so the row ends and the Merge? question is asked there. The operator decides when the step has given up. + // The CI fix step works the red head as it would for any PR; its push is a head nobody saw, so the leg ends. A person decides when the step has given up. const f = await factOf(); if (f && revisesNow(f)) return; const bucket = f ? cifixBucket(f) : null; if (bucket !== null && ["work", "formatting", "linting", "collect", "rerun", "rerun-wait"].includes(bucket) && stepRuns(f!, "cifix")) return; - return await stop("asked", `CI failed at ${headName(p)} and the CI fix did not repair it`, head, [reviewFact(p, "take"), `CI failed at ${headName(p)}`]); + return await stop(`CI failed at ${headName(p)} and the CI fix did not repair it`); } if (c.overall === "none" && !await repoHasNoCi(db, p.repo)) return; if (c.mergeable === "CONFLICTING") { // The conflict step merges the base into the PR when it can; its push is a new head that continues this pre-approval. const f = await factOf(); if (f?.conflict?.baseOk && ["merge", "linting"].includes(f.conflict.bucket) && stepRuns(f, "conflict")) return; - return await stop("asked", "the PR conflicts with its base branch", head); + return await stop("the PR conflicts with its base branch"); } // The pre-merge review of this head must be clean; the planner runs it (src/core/decide.ts) and retries a failed one. const pm = await premergeAt(db, p.repo, p.number, head); if (!pm || (pm.findings === null && pm.tries < PREMERGE_MAX_TRIES)) return; - if (pm.findings === null) return await stop("asked", `the pre-merge review of ${headName(p)} failed`, head); + if (pm.findings === null) return await stop(`the pre-merge review of ${headName(p)} failed`); const defects = findingsOf(pm).filter((x) => x.severity === "defect").length; - if (defects) return await stop("asked", `the pre-merge review found ${defects} defect${defects === 1 ? "" : "s"}`, head); - // A workflow's merge approval says the change is wanted: an unsure pre-merge review (a claim of the description it could not - // verify) with no defect goes on to the merge queue; only a defect, or another blocker, brings the item back. - if (pm.unsure === 1 && !leg) return await stop("asked", "the pre-merge review is unsure", head); - const h = await handOver(db, p, head, held, pm.unsure === 1); - if ("stop" in h) { - if (await move(db, p, "asked", { reason: h.stop, line: `The pre-approved merge stopped: ${h.stop}.` }) && !leg && !h.stop.includes("was answered")) await askMerge(db, p, head, h.stop, [h.stop]); - } + if (defects) return await stop(`the pre-merge review found ${defects} defect${defects === 1 ? "" : "s"}`); + // The merge approval says the change is wanted: an unsure pre-merge review (a claim of the description it could not verify) with + // no defect goes on to the merge queue; only a defect, or another blocker, brings the item back. + const h = await handOver(db, p, head, held, pf, pm.unsure === 1); + if ("stop" in h) await stop(h.stop); return; } - // queued: the merge queue owns it now; only an answer that stops counting ends it here. - const d = await getDecision(db, mergeDecisionId(p.repo, p.number, head)); - if (!d || d.answer !== "merge") return cancel("its Merge answer was withdrawn"); - if (!await isOperator(db, d.answered_by ?? p.by, p.repo, held)) await cancel(`${d.answered_by ?? p.by} no longer settles decisions on ${p.repo}, so the Merge answer no longer counts`); + // queued: the merge queue owns it now; only an approver who may no longer act ends it here. + const by = leg?.approvedBy ?? p.by; + if (!await isOperator(db, by, p.repo, held)) await cancel(`${by} no longer settles decisions on ${p.repo}, so the approval no longer counts`); } /** Ends fix-up requests the planner can no longer work (the PR's head moved, it closed, the push is not possible), with the reason in the thread. Requests of a pre-approved merge end with it. */ -async function endStaleRequests(db: Db, held: ReadonlySet, wake: Wake): Promise { - // A request whose maker stopped settling (a maintainer after the setting went off, the repo left the app identity, a demotion) is dropped before the planner can push it. - for (const o of await db.all(db.k.selectFrom("operator_fixups").select(["id", "repo", "number", "from_head", "by", "preapproval_id"]).where("state", "=", "queued").orderBy("id"))) { - if (o.preapproval_id !== null || await isOperator(db, o.by, o.repo, held)) continue; - if ((await db.run(db.k.updateTable("operator_fixups").set({ state: "ended" }).where("id", "=", o.id).where("state", "=", "queued"))).changes !== 1) continue; - await audit(db, ACTOR, "operator-fixup", `${o.repo}#${o.number}`, { id: o.id, ended: true, reason: "the requester no longer settles here" }); - await say(db, o.repo, o.number, `The queued fix-up of ${short(o.from_head)} was dropped: ${o.by} no longer settles decisions on ${o.repo}.`); - } - for (const o of await openOperatorFixups(db)) { - if (o.preapprovalId !== null) continue; +async function endStaleRequests(db: Db, wake: Wake): Promise { + const now = Date.now(); + // A request whose maker may no longer act on the repo (a demotion, a write permission gone) is dropped before the planner can push it. + const [all, live] = await db.together(() => Promise.all([loadFixupRequests(db, { anyMaker: true, nowMs: now }), loadFixupRequests(db, { nowMs: now })])); + const liveIds = new Set(live.map((o) => o.id)); + const gone = all.filter((o) => o.preapproval_id === null && !liveIds.has(o.id)); + const ended = new Set(await endFixupRequests(db, gone.map((o) => ({ id: o.id, reason: "the requester no longer settles here" })))); + await sayAll(db, gone.filter((o) => ended.has(o.id)).map((o) => ({ repo: o.repo, number: o.number, text: `The queued fix-up of ${short(o.from_head)} was dropped: ${o.by} no longer settles decisions on ${o.repo}.` }))); + const ends: { id: number; reason: string; repo: string; number: number; head: string }[] = []; + const results = await loadOperatorFixResults(db, live.map((o) => o.id)); + for (const o of live) { + if (o.preapproval_id !== null) continue; const f = await loadPrFact(db, o.repo, o.number); if (f?.refreshAt !== undefined) wake(f.refreshAt); - const why = !f ? "the PR is no longer open" : f.head !== o.head ? `the head moved to ${short(f.head)}` : o.started ? null : await whyNotPlanned(db, f); - if (!why) continue; - if ((await db.run(db.k.updateTable("operator_fixups").set({ state: "ended" }).where("id", "=", o.id).where("state", "=", "queued"))).changes !== 1) continue; - await audit(db, ACTOR, "operator-fixup", `${o.repo}#${o.number}`, { id: o.id, ended: true, reason: why }); - await say(db, o.repo, o.number, `The queued fix-up of ${short(o.head)} was dropped: ${why}.`); + const why = !f ? "the PR is no longer open" : f.head !== o.from_head ? `the head moved to ${short(f.head)}` : results.has(o.id) ? null : await whyNotPlanned(db, f); + if (why) ends.push({ id: o.id, reason: why, repo: o.repo, number: o.number, head: o.from_head }); } + const done = new Set(await endFixupRequests(db, ends.map((e) => ({ id: e.id, reason: e.reason })))); + await sayAll(db, ends.filter((e) => done.has(e.id)).map((e) => ({ repo: e.repo, number: e.number, text: `The queued fix-up of ${short(e.head)} was dropped: ${e.reason}.` }))); } /** A cancel that came too late for a merge already past its guard: the merge row that appears at the head turns the row into merged. */ async function settleCancelled(db: Db): Promise { const since = new Date(Date.now() - 86_400_000).toISOString(); - const rows = await db.all(preapprovalRows(db).$narrowType<{ head: NotNull }>().where("state", "=", "cancelled").where("head", "is not", null).where("updated_at", ">", since).orderBy("id")); - for (const p of rows) { - if (await db.get(db.k.selectFrom("merges").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("head_oid", "=", p.head).where("outcome", "=", "merged").where("at", ">=", p.at))) await move(db, p, "merged", { line: "The merge went through before the cancel took effect: the PR is merged." }); - } -} - -/** - * An operator's Merge answer at head H carries across the pipeline's own base merge to H2 that left the PR's diff unchanged: when the answer - * still stands and the PR has no pre-approved merge, a row starts in `review` at H2 with no fix-up, and the chain of review, pre-merge - * review and CI runs again before the hand-over answers the Merge? question at H2. One row per (PR, H2); the row's existence is the memory. - */ -async function carryAnswers(db: Db, held: ReadonlySet): Promise { - const pushes = await db.all(db.k.selectFrom("conflict_merges as m").select(["m.repo", "m.number", "m.from_head", "m.to_head", (eb) => eb.val("base merge").as("what")]).$narrowType<{ to_head: NotNull }>() - .where("m.state", "=", "merged").where("m.own_diff", "=", "same").where("m.to_head", "is not", null) - .where((eb) => eb("m.repo", "in", eb.selectFrom("main.tracked_repos").select("name")))); - for (const x of pushes) { - const it = await prRow(db, x.repo, x.number); - if (!it || it.kind !== "pr" || it.state !== "OPEN" || it.head_oid !== x.to_head) continue; - const d = await getDecision(db, mergeDecisionId(x.repo, x.number, x.from_head)); - if (!d || d.answer !== "merge" || !d.answered_by || !await isOperator(db, d.answered_by, x.repo, held)) continue; - if (await db.get(db.k.selectFrom("preapprovals").select((eb) => eb.lit(1).as("one")).where("repo", "=", x.repo).where("number", "=", x.number).where((eb) => eb.or([eb("head", "=", x.to_head), eb("state", "in", ACTIVE)])))) continue; - // An answer the hand-over of a row wrote is that row's own; its ownPush handling carries it while the row is active. - if (await db.get(db.k.selectFrom("audit").select((eb) => eb.lit(1).as("one")).where("action", "=", "answer").where("target", "=", d.id).where((w) => kx.like(db, "details", w.val('%"source":"preapproval"%')))) - && await db.get(db.k.selectFrom("preapprovals").select((eb) => eb.lit(1).as("one")).where("repo", "=", x.repo).where("number", "=", x.number).where("head", "=", x.from_head).where("state", "in", ACTIVE))) continue; - if (!await mergeApprovalOf(db, x.repo)) continue; - const at = iso(); - const carried = await db.write(async () => { - // Re-check under the write lock: another tick may have created it. - if (await db.get(db.k.selectFrom("preapprovals").select((eb) => eb.lit(1).as("one")).where("repo", "=", x.repo).where("number", "=", x.number).where("head", "=", x.to_head))) return false; - const id = (await db.get(db.k.insertInto("preapprovals").values({ repo: x.repo, number: x.number, by: d.answered_by!, at, instructions: "", state: "review", from_head: x.from_head, head: x.to_head, updated_at: at, fix_id: null }).returning("id")))!.id; - await audit(db, ACTOR, "preapproval", `${x.repo}#${x.number}`, { id, state: "review", head: x.to_head, carried: x.from_head }); - return true; - }); - if (!carried) continue; - await say(db, x.repo, x.number, `${d.answered_by}'s Merge answer at ${short(x.from_head)} carries to the pipeline's ${x.what} ${short(x.to_head)} once the review, the pre-merge review and CI there are clean.`); - } -} - -/** The reasons of rows that stopped only on their review under the earlier rule: an unsure take or take-fix, or a take-fix of a row without a fix-up. */ -const REVIEW_ONLY_STOP = /^the review says take(-fix)? \(unsure\)|^the review of (the PR's head|the merged head) asks for fixes$/; - -/** - * A row that stopped in asked only because of a review the rule now goes on with, at the head that is still the PR's, goes back to review - * while its Merge? question there is still open, and that question is withdrawn: the next evaluation takes it on from the review. - */ -async function resumeReviewStops(db: Db, held: ReadonlySet, wake: Wake): Promise { - const rows = await db.all(preapprovalRows(db).$narrowType<{ head: NotNull; reason: NotNull }>().where("state", "=", "asked").where("head", "is not", null).where("reason", "is not", null) - .where((eb) => eb("repo", "in", eb.selectFrom("main.tracked_repos").select("name"))).orderBy("id")); - for (const p of rows) { - if (!REVIEW_ONLY_STOP.test(p.reason)) continue; - // A later row of the PR took over from this one. - if (await db.get(db.k.selectFrom("preapprovals").select((eb) => eb.lit(1).as("one")).where("repo", "=", p.repo).where("number", "=", p.number).where("id", ">", p.id))) continue; - const it = await prRow(db, p.repo, p.number); - if (!it || it.state !== "OPEN" || it.head_oid !== p.head) continue; - const r = await reviewAt(db, p, p.head, wake); - if (r.kind !== "take" && r.kind !== "takefix") continue; - const d = await getDecision(db, mergeDecisionId(p.repo, p.number, p.head)); - if (!d || d.answer !== null) continue; - if (!await isOperator(db, p.by, p.repo, held) || !await mergeApprovalOf(db, p.repo)) continue; - const at = iso(); - const moved = await db.write(async () => { - if (!await moveRaw(db, p, "review", { reason: null })) return false; - await withdrawMergeQuestion(db, p.repo, p.number, p.head, at, `${approvedAhead(p)}, so the pre-approved merge goes on`); - return true; - }); - if (moved) await say(db, p.repo, p.number, `The review of ${p.fix_id !== null ? "the fix-up" : headName(p)} ${r.kind === "take" ? "is unsure" : r.unsure ? "is unsure and asks for fixes" : "asks for fixes"}; ${approvedAhead(p)}, so the pre-approved merge goes on and its Merge? question is withdrawn.`); + const targets = [...new Set((await listAudit(db, { actions: ["preapproval"], since, where: { state: "cancelled" } })).flatMap((a) => (a.target ? [a.target] : [])))]; + const refs = targets.flatMap((t) => { const m = /^(.+)#(\d+)$/.exec(t); return m ? [{ repo: m[1]!, number: Number(m[2]) }] : []; }); + if (!refs.length) return; + const [legs, merges] = await db.together(() => Promise.all([loadLegs(db, refs, { latestOnly: true }), loadMergeFacts(db, refs)])); + for (const p of [...legs.values()].flat()) { + if (p.state !== "cancelled" || !p.head || p.updated_at <= since) continue; + const a = merges.attempts.get(`${refOf(p.repo, p.number)}@${p.head}`); + if (a?.outcome === "merged" && a.at >= p.at) await move(db, p, "merged", { line: "The merge went through before the cancel took effect: the PR is merged." }); } } @@ -656,9 +580,8 @@ export type Wake = (at: number) => void; /** * What advancePreapprovals reads, as change markers: the planner's input topics (the PR facts and most rows the pass reads) and `access` - * (roles, and the audit table: the entries an answer's source is read from, and the GitHub writes that follow a base merge's own-diff - * mark, which no other topic watches). A pass whose markers are the ones it read before and whose wake time (`Wake`) has not come would - * move nothing. + * (roles, and the audit table: the GitHub writes that follow a base merge's own-diff mark, which no other topic watches). A pass whose + * markers are the ones it read before and whose wake time (`Wake`) has not come would move nothing. */ export async function preapprovalInputs(db: Db): Promise { const seqs = await readSeqs(db); @@ -666,7 +589,7 @@ export async function preapprovalInputs(db: Db): Promise { } /** - * Moves each pre-approved merge that other steps' rows have carried to a new state; the runner tick runs it when its inputs changed + * Moves each merge leg that other steps' rows have carried to a new state; the runner tick runs it when its inputs changed * (preapprovalInputs) or a time `wake` was told has come. Writes nothing when nothing moved, except the maintainers' write permissions it * reads again first (refreshSettlers). A failure tells `wake` the pass's own time, so the next tick runs it again. */ @@ -683,75 +606,73 @@ export async function advancePreapprovals(db: Db, log: (line: string) => void = return 0; } try { - await endStaleRequests(db, held, wake); + await endStaleRequests(db, wake); await settleCancelled(db); - await carryAnswers(db, held); - await resumeReviewStops(db, held, wake); } catch (e) { log(`preapproval requests: ${(e as Error).message}`); wake(t); } - const rows = await db.all(preapprovalRows(db).where("state", "in", ACTIVE).where((eb) => eb("repo", "in", eb.selectFrom("main.tracked_repos").select("name"))).orderBy("id")); - // The facts of the PRs of this row and the rows after it, loaded together when a row first needs its PR's, with the settings - // read once for the load as in a planner pass. A row that moved or failed may have written what they read, so the next row - // that needs them loads them again. + const pass = await loadLegPass(db); + // A leg written before its workflow's row is linked to the live workflow of its PR. + const adopt = pass.rows.flatMap((r) => { const c = pass.context.get(r.id); return r.workflow_id === null && c && c !== "ended" ? [{ id: r.id, workflowId: c.workflowId }] : []; }); + if (adopt.length) await adoptLegs(db, adopt); + if (!pass.rows.length) return 0; + const pf = await loadPassFacts(db, pass.rows); + // The facts of the legs' PRs, loaded together when a leg first needs its PR's, with the settings read once for the load as in a planner pass. let facts: Map | null = null; - for (const [i, p] of rows.entries()) { + const refs = pass.rows.map((r) => refOf(r.repo, r.number)); + for (const p of pass.rows) { const factOf = async (): Promise => { if (!facts) { - const loaded = await withSettingsSnapshot(db, () => loadPrFacts(db, { refs: rows.slice(i).map((r) => `${r.repo}#${r.number}`) })); + const loaded = await withConfig(db, () => loadPrFacts(db, { refs })); for (const f of loaded) if (f.refreshAt !== undefined) wake(f.refreshAt); - facts = new Map(loaded.map((f) => [`${f.repo}#${f.number}`, f])); + facts = new Map(loaded.map((f) => [refOf(f.repo, f.number), f])); } - return facts.get(`${p.repo}#${p.number}`) ?? null; + return facts.get(refOf(p.repo, p.number)) ?? null; }; try { - await advance(db, p, held, factOf, wake); - if ((await db.get(db.k.selectFrom("preapprovals").select("state").where("id", "=", p.id)))!.state !== p.state) { - n++; - facts = null; - } + const before = p.state; + await advance(db, p, pass.context.get(p.id) ?? "ended", held, pf, factOf, wake); + const now = (await loadLegs(db, [{ repo: p.repo, number: p.number }], { ids: [p.id] })).get(refOf(p.repo, p.number))?.[0]?.state; + if (now !== before) n++; } catch (e) { - facts = null; wake(t); const msg = oneLine(String((e as Error).message ?? e), 300); - log(`preapproval ${p.repo}#${p.number}: ${msg}`); + const ref = refOf(p.repo, p.number); + log(`preapproval ${ref}: ${msg}`); // Runs every tick: the item's trace gets the error once, not once per tick. try { - const last = await db.get(db.k.selectFrom("audit").select("details").where("action", "=", "preapproval-error").where("target", "=", `${p.repo}#${p.number}`).orderBy(kx.rowid("audit"), "desc").limit(1)); - if (!last || (JSON.parse(last.details ?? "{}") as { error?: string }).error !== msg) await audit(db, ACTOR, "preapproval-error", `${p.repo}#${p.number}`, { id: p.id, state: p.state, error: msg }); + const last = ((await loadAuditActions(db, [ref], ["preapproval-error"])).get(ref) ?? []).reduce<{ rowid: number; details: Record | null } | null>((a, b) => (!a || b.rowid > a.rowid ? b : a), null); + if (!last || last.details?.error !== msg) await addAudit(db, [{ login: ACTOR, action: "preapproval-error", target: ref, details: { id: p.id, state: p.state, error: msg } }]); } catch { /* the log line above stands */ } } } return n; } -export const mergeRunning = async (db: Db, repo: string): Promise => !!await db.get(db.k.selectFrom("jobs").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("step", "=", "merge").where("state", "=", "running")); -export const inActiveBatch = async (db: Db, repo: string, n: number): Promise => - !!await db.get(db.k.selectFrom("main.merge_batch_prs as x").innerJoin("main.merge_batches as b", "b.id", "x.batch_id").select((eb) => eb.lit(1).as("one")).where("b.repo", "=", repo).where("x.number", "=", n).where("b.state", "in", ["checking", "open"])); +export const mergeRunning = async (db: Db, repo: string): Promise => (await isRunning(db, [{ step: "merge", repo }])).size > 0; +export const inActiveBatch = async (db: Db, repo: string, n: number): Promise => (await loadBatchMembership(db, [{ repo, number: n }])).has(refOf(repo, n)); /** - * An operator cancels the PR's pre-approved merge before the merge queue has merged it. A queued PR in an integration batch is first + * A person cancels the PR's pre-approved merge before the merge queue has merged it. A queued PR in an integration batch is first * removed from the batch (the operator control: the batch PR is closed; the hold it sets is released) unless the merge is running. * Throws when there is none or the queue is past stopping it. */ export async function cancelPreapproval(db: Db, by: string, repo: string, n: number, run?: Exec, via?: string): Promise { - const p = await db.get(db.k.selectFrom("preapprovals").select("id").where("repo", "=", repo).where("number", "=", n).where("state", "in", ACTIVE).orderBy("id", "desc").limit(1)); + const p = (await loadLegs(db, [{ repo, number: n }], { activeOnly: true })).get(refOf(repo, n))?.at(-1); if (!p) throw new Error(`${repo}#${n} has no pre-approved merge in progress`); - const state = (await db.get(db.k.selectFrom("preapprovals").select("state").where("id", "=", p.id)))!.state; - // The state change and the take-back of the hand-over answer are one transaction, so the merge queue never sees a cancelled row with a live answer. const finish = async () => { - if (!await cancelRow(db, p.id, by, `cancelled by ${by}`, `${by} cancelled the pre-approved merge.`, true, via)) throw new Error("the pre-approved merge changed a moment ago"); + if (!await cancelRow(db, p, by, `cancelled by ${by}`, `${by} cancelled the pre-approved merge.`, true, via)) throw new Error("the pre-approved merge changed a moment ago"); }; - if (state === "queued" && await inActiveBatch(db, repo, n)) { + if (p.state === "queued" && await inActiveBatch(db, repo, n)) { if (await mergeRunning(db, repo)) throw new Error("a merge of the repo is running: it may be merging this PR"); // The removal holds the PR's merge; a hold that was there before stays, the one the removal set is released again after the row - // is cancelled (so the queue never sees an unheld PR with a live Merge answer), also when the removal or the cancel fails. - const heldBefore = !!await db.get(db.k.selectFrom("main.merge_holds").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n)); + // is cancelled (so the queue never sees an unheld PR with a live approval), also when the removal or the cancel fails. + const heldBefore = (await loadHolds(db, { refs: [{ repo, number: n }] })).has(refOf(repo, n)); try { const r = await removeFromBatch(db, by, repo, n, run); - const b = await db.get(db.k.selectFrom("main.merge_batches").select("state").where("repo", "=", repo).where("branch", "=", r.batch).orderBy("id", "desc").limit(1)); - if (b?.state === "merged") throw new Error("the PR is already merged: its batch merged"); + const id = await loadBatchByBranch(db, repo, r.batch); + if (id !== undefined && (await getBatch(db, id))?.state === "merged") throw new Error("the PR is already merged: its batch merged"); await finish(); } finally { if (!heldBefore) await releaseMerge(db, by, repo, n); @@ -761,13 +682,12 @@ export async function cancelPreapproval(db: Db, by: string, repo: string, n: num } /** - * Operator: queues the PR's failed pre-approved merge again with the same instructions at the PR's current head, as a new - * pre-approval (the same path as the first press: the audit entry and the thread line are the ones of any pre-approval). - * An open Merge? question at the head is answered by the new row's hand-over as it would have been the first time. - * Throws when the latest pre-approval did not fail. + * Queues the PR's failed pre-approved merge again with the same instructions at the PR's current head, as a new pre-approval (the + * same path as the first press: the audit entry and the thread line are the ones of any pre-approval). Throws when the latest + * pre-approval did not fail. */ export async function retryPreapproval(db: Db, by: string, repo: string, n: number): Promise { - const p = await db.get(preapprovalRows(db).where("repo", "=", repo).where("number", "=", n).orderBy("id", "desc").limit(1)); + const p = (await loadLegs(db, [{ repo, number: n }], { latestOnly: true })).get(refOf(repo, n))?.at(-1); if (!p || p.state !== "failed") throw new Error(`${repo}#${n} has no failed pre-approved merge`); if (!await isOperator(db, by, repo)) throw new Error(`${by} does not settle decisions on ${repo}`); await runPipelineStep(db, { repo, number: n, step: { kind: "fixup", instructions: p.instructions, merge: true }, by }); diff --git a/src/preapproval/permissions.ts b/src/preapproval/permissions.ts index a5cea8ca4..8a9f51d11 100644 --- a/src/preapproval/permissions.ts +++ b/src/preapproval/permissions.ts @@ -1,14 +1,15 @@ -// The pipeline's own reading of a maintainer's write permission. A maintainer's pre-approved merge, the Merge answer it rests on and a +// The pipeline's own reading of a maintainer's write permission. A maintainer's pre-approved merge, the approval it rests on and a // queued fix-up request count only while the maintainer's cached write permission is fresh (src/settlers.ts), and a dashboard session // refreshes that row only while the person uses the dashboard. The pipeline reads it again through the GitHub App installation // (src/remote/permission.ts, which writes repo_permissions) shortly before it expires, so these long-lived rows do not end with the session. -import { mergeDecisionId } from "../core/rules.ts"; import { PERM_READ_TTL } from "../dash/server/sessions.ts"; import { WRITE_PERMISSIONS } from "../dash/server/provider.ts"; import { appPermission, type AppPermission } from "../remote/permission.ts"; -import { maintainersSettle, maintainersSettleOn, settleKey, settlesNow } from "../settlers.ts"; +import { settleKey, settlesNow } from "../settlers.ts"; +import { loadAccess, loadPermissions, loginsWithRole, permKey, type PermEntry } from "../data/access/index.ts"; +import { loadTrackedRepos } from "../data/control/index.ts"; +import { loadActingPairs } from "../data/workflow/index.ts"; import type { Db } from "../db/index.ts"; -import { rowid } from "../db/kx.ts"; /** A write permission older than this is read again, so it stays younger than PERM_READ_TTL while GitHub answers. About one read per login and repo per TTL. */ export const REFRESH_AFTER = PERM_READ_TTL - 2 * 60_000; @@ -22,34 +23,15 @@ export type RefreshDeps = { permission?: (db: Db, login: string, repo: string) => Promise; }; -const answeredMerge = async (db: Db, repo: string, number: number, head: string): Promise => - (await db.get(db.k.selectFrom("main.decisions").select("answered_by").where("id", "=", mergeDecisionId(repo, number, head)).where("answer", "=", "merge")))?.answered_by ?? null; - -/** The maintainer logins the pipeline acts for, with the repo: makers of active pre-approvals and queued fix-up requests, and who answered the Merge a queued pre-approval rests on or that has yet to carry across a base merge. */ -async function pipelineMaintainers(db: Db): Promise<{ login: string; repo: string }[]> { - const maintainers = new Set((await db.all(db.k.selectFrom("main.access").select("login").where("role", "=", "maintainer"))).map((r) => r.login)); - if (!maintainers.size) return []; - const pairs = new Map(); - const add = (login: string | null, repo: string) => { - if (login && maintainers.has(login)) pairs.set(settleKey(login, repo), { login, repo }); - }; - const active = await db.all(db.k.selectFrom("preapprovals").select(["repo", "number", "state", "head", "by"]).where("state", "in", ["fixup", "review", "ci", "queued"]) - .where("repo", "in", (eb) => eb.selectFrom("main.tracked_repos").select("name")).orderBy("repo").orderBy("number").orderBy("id")); - for (const p of active) { - add(p.by, p.repo); - if (p.state === "queued" && p.head) add(await answeredMerge(db, p.repo, p.number, p.head), p.repo); - } - for (const o of await db.all(db.k.selectFrom("operator_fixups").select(["by", "repo"]).where("state", "=", "queued").orderBy("id"))) add(o.by, o.repo); - // A Merge answer that carries across the pipeline's own base merge (carryAnswers) and has not carried yet. - const carries = await db.all(db.k.selectFrom("conflict_merges as m") - .innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "m.repo").onRef("i.number", "=", "m.number")) - .select(["m.repo", "m.number", "m.from_head"]) - .where("m.state", "=", "merged").where("m.own_diff", "=", "same").where("i.state", "=", "OPEN").whereRef("i.head_oid", "=", "m.to_head") - .where("m.repo", "in", (eb) => eb.selectFrom("main.tracked_repos").select("name")) - .where((eb) => eb.not(eb.exists(eb.selectFrom("preapprovals as p").select(eb.lit(1).as("one")).whereRef("p.repo", "=", "m.repo").whereRef("p.number", "=", "m.number").whereRef("p.head", "=", "m.to_head")))) - .orderBy("m.repo").orderBy("m.number").orderBy("m.created_at").orderBy(rowid("conflict_merges", "m"))); - for (const x of carries) add(await answeredMerge(db, x.repo, x.number, x.from_head), x.repo); - return [...pairs.values()]; +/** The maintainer logins the pipeline acts for, with the repo (of tracked repos), and each one's cached permission row. */ +async function pipelineMaintainers(db: Db): Promise<{ login: string; repo: string; row: PermEntry | undefined }[]> { + const [pairs, maintainers, tracked] = await db.together(() => Promise.all([loadActingPairs(db), loginsWithRole(db, ["maintainer"]), loadTrackedRepos(db)])); + const isMaintainer = new Set(maintainers.map((l) => l.toLowerCase())); + const seen = new Map(); + for (const p of pairs) if (isMaintainer.has(p.login.toLowerCase()) && tracked.has(p.repo)) seen.set(settleKey(p.login, p.repo), p); + const list = [...seen.values()]; + const rows = await loadPermissions(db, list); + return list.map((p) => ({ ...p, row: rows.get(permKey(p.login, p.repo)) })); } /** @@ -62,17 +44,10 @@ async function pipelineMaintainers(db: Db): Promise<{ login: string; repo: strin */ export async function refreshSettlers(db: Db, log: (line: string) => void = () => {}, deps: RefreshDeps = {}, wake: (at: number) => void = () => {}): Promise> { const held = new Set(); - const all = await maintainersSettle(db); const read = deps.permission ?? ((d, login, repo) => appPermission(d, login, repo)); const now = Date.now(); - const settlesOn = new Map(); - for (const { login, repo } of await pipelineMaintainers(db)) { - if (!all) { - // A repo on the maintainer workflow lets its maintainers settle without `maintainer_writes`. - if (!settlesOn.has(repo)) settlesOn.set(repo, await maintainersSettleOn(db, repo)); - if (!settlesOn.get(repo)) continue; - } - const row = await db.get(db.k.selectFrom("main.repo_permissions").select(["permission", "checked_at"]).where("login", "=", login).where("repo", "=", repo)); + for (const { login, repo, row: entry } of await pipelineMaintainers(db)) { + const row = entry ? { permission: entry.permission, checked_at: entry.checkedAt } : undefined; const age = row ? now - Date.parse(row.checked_at) : NaN; if (row && WRITE_PERMISSIONS.has(row.permission) && age < REFRESH_AFTER) wake(Date.parse(row.checked_at) + REFRESH_AFTER); // Past HOLD_MAX (or an unreadable time) the row is not held and the pre-approval ends: a read started now would come too late for this pass. @@ -100,11 +75,11 @@ export async function refreshSettlers(db: Db, log: (line: string) => void = () = * younger than HOLD_MAX: the caller waits. Past that, or on a fresh non-write answer, "no". */ export async function settlesLive(db: Db, login: string, repo: string, read: RefreshDeps["permission"] = (d, l, r) => appPermission(d, l, r)): Promise<"yes" | "no" | "unknown"> { - const role = (await db.get(db.k.selectFrom("main.access").select("role").where("login", "=", login)))?.role; - if (role !== "maintainer" || !await maintainersSettleOn(db, repo)) return await settlesNow(db, login, [repo]) ? "yes" : "no"; + const role = (await loadAccess(db, [login])).get(login.toLowerCase())?.role; + if (role !== "maintainer") return await settlesNow(db, login, [repo]) ? "yes" : "no"; const age = async (): Promise => { - const row = await db.get(db.k.selectFrom("main.repo_permissions").select(["permission", "checked_at"]).where("login", "=", login).where("repo", "=", repo)); - return row && WRITE_PERMISSIONS.has(row.permission) ? Date.now() - Date.parse(row.checked_at) : NaN; + const row = (await loadPermissions(db, [{ login, repo }])).get(permKey(login, repo)); + return row && WRITE_PERMISSIONS.has(row.permission) ? Date.now() - Date.parse(row.checkedAt) : NaN; }; const before = await age(); if (!(before < PERM_READ_TTL)) { diff --git a/src/preapproval/state.ts b/src/preapproval/state.ts index 097a2a302..4be6b4c6d 100644 --- a/src/preapproval/state.ts +++ b/src/preapproval/state.ts @@ -1,43 +1,34 @@ -// What the planner and the fix-up step read of operator fix-ups and pre-approved merges. No writes here. -import { PERM_READ_TTL } from "../dash/server/sessions.ts"; -import { settlesCheckedAtExpr, settlesLoginExpr } from "../settlers.ts"; +// What the planner and the fix-up step read of operator fix-ups and pre-approved merges, over the workflow and changes modules. No writes here. import { FIXUP_MAX_ATTEMPTS } from "../core/rules.ts"; -import * as kx from "../db/kx.ts"; +import { loadFixupRequests, loadLegPass } from "../data/workflow/index.ts"; +import { loadOperatorFixResults, loadPatchFacts, operatorTriesIn } from "../data/changes/index.ts"; +import { loadPermissions, permKey, PERM_READ_TTL } from "../data/access/index.ts"; import type { Db } from "../db/index.ts"; -/** Fix-up states that count as a try; a row left in `pushing` by a crash counts too. */ -const TRY_STATES = ["pushing", "pushed", "failed", "refused", "rejected"]; -/** Fix-up states that end the work of an operator fix-up (`linting` is a stored patch waiting for its lint task; `superseded` is one the plan dropped). */ -const ENDED_STATES = ["pushing", "pushed", "failed", "refused", "rejected", "cannot-push", "too-large", "push-denied", "asked", "comment-failed", "superseded"]; -/** A request counts only while the person who made it still settles on the repo (an operator, or a maintainer under src/settlers.ts): its push is made as them. */ -const bySettles = (eb: kx.AnyEb, nowMs: number) => settlesLoginExpr(eb, "o.by", "o.repo", nowMs); -const ended = (eb: kx.AnyEb) => eb.exists(kx.schemaEb(eb).selectFrom("fixups as f").select(eb.lit(1).as("one")).where("f.operator_fix", "=", eb.ref("o.id")).where("f.source", "=", "operator").where("f.state", "in", ENDED_STATES)); - /** Tries the operator's fix-ups used on the PR; the fix-up limit of the PR applies to them as to the review's. */ export async function operatorTries(db: Db, repo: string, number: number): Promise { - return (await db.get(db.k.selectFrom("fixups").select((eb) => eb.fn.countAll().as("n")) - .where("repo", "=", repo).where("number", "=", number).where("source", "=", "operator").where("state", "in", TRY_STATES)))!.n; + return operatorTriesIn((await loadPatchFacts(db, [{ repo, number }])).get(`${repo}#${number}`)?.fixups ?? []); } export const operatorTriesLeft = async (db: Db, repo: string, number: number): Promise => await operatorTries(db, repo, number) < FIXUP_MAX_ATTEMPTS; export type OperatorFix = { id: number; head: string; instructions: string; by: string; preapprovalId: number | null }; -/** The operator fix-up of the PR still to work at `head`: queued and without a final fixups row of its own (matched by the request's id). */ +/** + * The operator fix-up of the PR still to work at `head`: queued, without a final fixups row of its own, and made by someone who + * may still act on the repo (its push is made as them). + */ export async function queuedOperatorFix(db: Db, repo: string, number: number, head: string, nowMs: number = Date.now()): Promise { - const r = await db.get(db.k.selectFrom("operator_fixups as o").select(["o.id", "o.from_head", "o.instructions", "o.by", "o.preapproval_id"]) - .where("o.repo", "=", repo).where("o.number", "=", number).where("o.from_head", "=", head).where("o.state", "=", "queued") - .where((eb) => bySettles(eb, nowMs)).where((eb) => eb.not(ended(eb))) - .orderBy("o.id", "desc").limit(1)); + const r = (await loadFixupRequests(db, { refs: [{ repo, number }], nowMs })).filter((o) => o.from_head === head).at(-1); return r ? { id: r.id, head: r.from_head, instructions: r.instructions, by: r.by, preapprovalId: r.preapproval_id } : null; } export type OperatorWork = { fixHeads: Set; hold: boolean; /** The pushed head of a pre-approved merge waiting for its pre-merge review (state `ci`). */ premergeHeads: Set; /** A pre-approved merge is live (fixup, review, ci or queued). */ preapproved: boolean; - /** When the first of `fixHeads`' requests stops counting with the clock alone: its maintainer's cached write permission ages out (ms). */ + /** When the first of `fixHeads`' requests stops counting with the clock alone: its maker's cached write permission ages out (ms). */ settleUntil?: number; }; -/** Per PR ("repo#n") at `nowMs`: the heads with an operator fix-up still to work, whether a pre-approved merge is before its merge answer or live at all, and the heads due a pre-merge review. Small tables, read once per pass. */ +/** Per PR ("repo#n") at `nowMs`: the heads with an operator fix-up still to work, whether a pre-approved merge is before its merge answer or live at all, and the heads due a pre-merge review. */ export async function operatorWork(db: Db, repo?: string, nowMs: number = Date.now()): Promise> { const out = new Map(); const get = (r: string, n: number): OperatorWork => { @@ -46,16 +37,16 @@ export async function operatorWork(db: Db, repo?: string, nowMs: number = Date.n if (!w) out.set(k, (w = { fixHeads: new Set(), hold: false, premergeHeads: new Set(), preapproved: false })); return w; }; - for (const o of await db.all(db.k.selectFrom("operator_fixups as o") - .select((eb) => ["o.repo", "o.number", "o.from_head", settlesCheckedAtExpr(eb, "o.by", "o.repo").as("checked_at")]) - .where("o.state", "=", "queued").where((eb) => bySettles(eb, nowMs)).where((eb) => eb.not(ended(eb))) - .$if(!!repo, (q) => q.where("o.repo", "=", repo!)))) { + const [requests, pass] = await db.together(() => Promise.all([loadFixupRequests(db, { nowMs }), loadLegPass(db, repo ? { repos: [repo] } : {})])); + const mine = requests.filter((o) => !repo || o.repo === repo); + const perms = await loadPermissions(db, mine.map((o) => ({ login: o.by, repo: o.repo }))); + for (const o of mine) { const w = get(o.repo, o.number); w.fixHeads.add(o.from_head); - if (o.checked_at) { const until = Date.parse(o.checked_at) + PERM_READ_TTL; if (!(w.settleUntil! <= until)) w.settleUntil = until; } + const checked = perms.get(permKey(o.by, o.repo))?.checkedAt; + if (checked) { const until = Date.parse(checked) + PERM_READ_TTL; if (!(w.settleUntil! <= until)) w.settleUntil = until; } } - for (const p of await db.all(db.k.selectFrom("preapprovals").select(["repo", "number", "state", "head"]).where("state", "in", ["fixup", "review", "ci", "queued"]) - .$if(!!repo, (q) => q.where("repo", "=", repo!)))) { + for (const p of pass.rows) { const w = get(p.repo, p.number); w.preapproved = true; if (p.state === "queued") continue; @@ -69,11 +60,7 @@ export type OpenRequest = { id: number; repo: string; number: number; head: stri /** Every operator fix-up request still queued (no final fixups row of its own); `started` when a fixups row of it exists (a stored patch or a push under way). */ export async function openOperatorFixups(db: Db, nowMs: number = Date.now()): Promise { - const rows = await db.all(db.k.selectFrom("operator_fixups as o") - .select((eb) => ["o.id", "o.repo", "o.number", "o.from_head", "o.preapproval_id", - eb.exists(eb.selectFrom("fixups as f").select(eb.lit(1).as("one")).whereRef("f.operator_fix", "=", "o.id")).as("started")]) - .where("o.state", "=", "queued").where((eb) => bySettles(eb, nowMs)).where((eb) => eb.not(ended(eb))) - .where("o.repo", "in", (eb) => eb.selectFrom("main.tracked_repos").select("name")) - .orderBy("o.repo").orderBy("o.number").orderBy("o.from_head").orderBy("o.id")); - return rows.map((r) => ({ id: r.id, repo: r.repo, number: r.number, head: r.from_head, preapprovalId: r.preapproval_id, started: !!r.started })); + const rows = await loadFixupRequests(db, { nowMs }); + const results = await loadOperatorFixResults(db, rows.map((r) => r.id)); + return rows.map((r) => ({ id: r.id, repo: r.repo, number: r.number, head: r.from_head, preapprovalId: r.preapproval_id, started: results.has(r.id) })); } diff --git a/src/prstatus/approval.ts b/src/prstatus/approval.ts index 245e1e9e7..c9310ee03 100644 --- a/src/prstatus/approval.ts +++ b/src/prstatus/approval.ts @@ -1,28 +1,15 @@ // Per-repo switch for the PR status comment (src/prstatus/index.ts), off by default. Set from the dashboard by an operator -// or a maintainer with write access to the repo (src/dash/api/admin.ts). -import { audit } from "../dash/audit.ts"; -import { setting } from "../settings-read.ts"; +// or a maintainer with write access to the repo (src/dash/api/admin.ts). The row is the repo's `prstatus` step approval. +import { repoStepApproval, setStepApproval, type StepApproval } from "../data/control/index.ts"; import type { Db } from "../db/index.ts"; -export type StatusApproval = { by: string; at: string }; -const key = (repo: string) => `prstatus_approved:${repo}`; +export type StatusApproval = StepApproval; export async function statusApprovalOf(db: Db, repo: string): Promise { - const value = await setting(db, key(repo)); - if (value === undefined) return null; - try { - return JSON.parse(value) as StatusApproval; - } catch { - return null; - } + return await repoStepApproval(db, repo, "prstatus"); } -// Returns false when nothing changed. +/** Returns false when nothing changed; throws for a repo that is not tracked. */ export async function setStatusApproval(db: Db, by: string, repo: string, approved: boolean): Promise { - if (!await db.get(db.k.selectFrom("main.tracked_repos").select("name").where("name", "=", repo))) throw new Error(`${repo} is not tracked`); - if ((await statusApprovalOf(db, repo) !== null) === approved) return false; - if (approved) await db.run(db.k.insertInto("main.settings").values({ key: key(repo), value: JSON.stringify({ by, at: new Date().toISOString() }) })); - else await db.run(db.k.deleteFrom("main.settings").where("key", "=", key(repo))); - await audit(db, by, approved ? "prstatus-approve" : "prstatus-revoke", repo); - return true; + return await setStepApproval(db, [{ repo, step: "prstatus", on: approved }], by) > 0; } diff --git a/src/prstatus/index.ts b/src/prstatus/index.ts index 77270634a..07140d033 100644 --- a/src/prstatus/index.ts +++ b/src/prstatus/index.ts @@ -6,8 +6,7 @@ // budget), under the repo's PR status switch (src/prstatus/approval.ts) and the step's daily limit. No timer: the planner // queues the step when a PR's line differs from the one posted; a PR whose writes keep failing waits out a backoff. // -// In a repo on the maintainer workflow (tracked_repos.workflow = 'new'), every item a person started, issue or PR, gets the -// comment as soon as it starts, built from the workflow's lines (src/workflow/status.ts): where it stands, who started, +// Every item a person started, issue or PR, gets the comment as soon as it starts, built from the workflow's lines (src/workflow/status.ts): where it stands, who started, // approved, answered or stopped it, its steps, its place in the merge queue, its numbered parts and the open recommendation. // A quiet PR's comment carries no parts, recommendation or blocker reason. Items nobody started keep the line above. import { commentStatuses, type PublicStatus, type PublicStep } from "../public/status.ts"; @@ -16,20 +15,18 @@ import type { By } from "../core/gates.ts"; import { ghComment, ghEditComment, WritePacedError, type Writer } from "../github/write.ts"; import { mentionName, shownMention } from "../github/slugs.ts"; import { appSlug, githubIdentity, ownLoginTest, plainLogin } from "../github/identity.ts"; -import { setting } from "../settings-read.ts"; import { leaseItem } from "../runner/leases.ts"; import { exec as realExec, type Exec } from "../fixup/git.ts"; import { Client, type Querier } from "../mirror.ts"; -import { ACTIVE_BATCH } from "../merge/batch-store.ts"; -import { pilotExpr } from "../pilot.ts"; import { ownerOf } from "../owners.ts"; import { envVar } from "../env.ts"; import { itemPath, shortRepo } from "../../web/src/lib/links.ts"; import { jobItem } from "../runner/job-items.ts"; import type { Db } from "../db/index.ts"; import { t } from "../i18n/index.ts"; -import { isQuiet } from "../security/quiet.ts"; -import { repoWorkflow, workflowOf } from "../workflow/store.ts"; +import { freshConfig } from "../data/control/index.ts"; +import { countStatusRetriesDue, loadStatusRetryAt, saveStatusComments, type StatusRow } from "../data/workflow/index.ts"; +import { loadStatusExtras, loadStatusInputs } from "../data/views/prStatus.ts"; import { attributionLines, currentStep, queueLine, recommendationLine, stateLine, stepLines, workflowSteps, type Progress } from "../workflow/status.ts"; import type { ItemWorkflow } from "../workflow/types.ts"; import { legWait } from "../workflow/waits.ts"; @@ -116,19 +113,6 @@ export function workflowBody(repo: string, number: number, paragraphs: string[], return `${parts.join("\n\n")}\n\n${MARKER}`; } -/** Each started item's latest workflow in a repo on the maintainer workflow, with whether the item is open. */ -async function latestWorkflows(db: Db, repo: string): Promise> { - const rows = await db.all(db.k.selectFrom("main.item_workflows as w").innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "w.repo").onRef("i.number", "=", "w.number")) - .selectAll("w").select("i.state as item_state").where("w.repo", "=", repo).orderBy("w.id")); - return new Map(rows.map((r) => [r.number, { wf: workflowOf(r), open: r.item_state === "OPEN" }])); -} - -async function workflowFacts(db: Db, repo: string, number: number, wf: ItemWorkflow): Promise { - const a = await db.get(db.k.selectFrom("main.workflow_events").select(["login", "at"]) - .where("workflow_id", "=", wf.id).where("kind", "=", "answered").orderBy("id", "desc").limit(1)); - return { wf, answered: a ? { by: a.login, at: a.at } : null, quiet: await isQuiet(db, repo, number), wait: await legWait(db, wf) }; -} - export type HistoryStep = { step: string; at: string }; /** The history with `step` added when it differs from the last one, keeping the newest HISTORY_MAX. */ @@ -152,7 +136,7 @@ export function commentBody(repo: string, number: number, line: string, history: } -type Stored = { number: number; comment_id: string | null; author: string | null; line: string | null; steps: string; failures: number }; +type Stored = StatusRow; export type Due = { number: number; facts: StatusFacts; line: string; prev: Stored | null }; const parseSteps = (s: string): HistoryStep[] => { @@ -173,31 +157,19 @@ const retryAt = (failures: number, now: number): string => /** * The PRs of a repo whose comment is due: an open PR in the pipeline's scope past triage with no comment yet, or a PR - * whose posted line differs from its line now. Out of scope (the repo's Pipeline off, a pilot) a posted comment still - * gets its Merged or Closed edit. Batch PRs get none; a PR waiting out a failure backoff is left out; a member of a batch - * whose PR has not opened yet keeps its line. + * whose posted line differs from its line now. Out of scope (the repo's Pipeline off, a person ended the item) a posted + * comment still gets its Merged or Closed edit. Batch PRs get none; a PR waiting out a failure backoff is left out; a member + * of a batch whose PR has not opened yet keeps its line. */ export async function statusDue(db: Db, repo: string, now: number = Date.now()): Promise { - const stored = await db.all(db.k.selectFrom("main.pr_status_comments").select(["number", "comment_id", "author", "line", "steps", "failures", "retry_at"]) - .where("repo", "=", repo).where("final", "=", 0) - // A Closed line is final until the item is open again: its state then leaves CLOSED and the row is read again. - .where((eb) => eb.not(eb.and([eb("line", "=", WORDS.Closed), eb.exists(eb.selectFrom("main.items as c").select(eb.lit(1).as("one")) - .whereRef("c.repo", "=", "main.pr_status_comments.repo").whereRef("c.number", "=", "main.pr_status_comments.number").where("c.state", "=", "CLOSED"))])))); + const { stored, inScope, started } = await loadStatusInputs(db, repo); const byNumber = new Map(stored.map((r) => [r.number, r])); - const inScope = new Set((await db.all(db.k.selectFrom("main.items as i").select("i.number") - .where("i.repo", "=", repo).where("i.kind", "=", "pr").where("i.state", "=", "OPEN") - .where((eb) => eb.or([ - eb.exists(eb.selectFrom("main.item_stage as s").select(eb.lit(1).as("one")).whereRef("s.repo", "=", "i.repo").whereRef("s.number", "=", "i.number")), - eb.exists(eb.selectFrom("main.decisions as d").select(eb.lit(1).as("one")).whereRef("d.repo", "=", "i.repo").whereRef("d.number", "=", "i.number").where("d.answer", "is", null)), - ])) - .where((eb) => eb.not(eb.exists(eb.selectFrom("main.merge_batches as b").select(eb.lit(1).as("one")).whereRef("b.repo", "=", "i.repo").whereRef("b.pr_number", "=", "i.number")))) - .where((eb) => pilotExpr(db, eb, "i")))).map((r) => r.number)); - const started = await repoWorkflow(db, repo) === "new" ? await latestWorkflows(db, repo) : new Map(); const numbers = [...new Set([...inScope, ...[...started].filter(([, w]) => w.open).map(([n]) => n), ...stored.map((r) => r.number)])] .filter((n) => { const at = byNumber.get(n)?.retry_at; return !at || Date.parse(at) <= now; }); if (!numbers.length) return []; const statuses = await commentStatuses(db, repo, numbers); - const batches = await batchesOf(db, repo, numbers); + const wfIds = numbers.flatMap((n) => { const w = started.get(n); return w ? [w.wf.id] : []; }); + const { batches, answered, quiet } = await loadStatusExtras(db, repo, numbers, wfIds); const out: Due[] = []; for (const n of numbers.sort((a, b) => a - b)) { const status = statuses.get(n), prev = byNumber.get(n) ?? null; @@ -209,7 +181,9 @@ export async function statusDue(db: Db, repo: string, now: number = Date.now()): if (open && open.pr === null) continue; const merged = status.step === "Merged" ? batches.get(`merged:${n}`) : undefined; const pr = (open ?? merged)?.pr; - const facts: StatusFacts = { status, ...(pr ? { batch: { pr } } : {}), ...(w ? { workflow: await workflowFacts(db, repo, n, w.wf) } : {}) }; + const a = w ? answered.get(w.wf.id) : undefined; + const workflow: WorkflowFacts | undefined = w ? { wf: w.wf, answered: a ? { by: a.login, at: a.at } : null, quiet: quiet.has(n), wait: await legWait(db, w.wf) } : undefined; + const facts: StatusFacts = { status, ...(pr ? { batch: { pr } } : {}), ...(workflow ? { workflow } : {}) }; // A started item's line is its whole comment text, so any change edits it; once it ended, the final line is the same as any PR's. const line = facts.workflow && !ended ? workflowLines({ ...facts, workflow: facts.workflow }).join("\n\n") : statusLine(facts); const first = facts.workflow ? !ended : !NO_FIRST_POST.has(status.step); @@ -220,30 +194,12 @@ export async function statusDue(db: Db, repo: string, now: number = Date.now()): /** The earliest end of a failure backoff of the repo's comments after `now`, or null. */ export async function statusRetryAt(db: Db, repo: string, now: number = Date.now()): Promise { - const r = await db.get(db.k.selectFrom("main.pr_status_comments").select((eb) => eb.fn.min("retry_at").as("at")) - .where("repo", "=", repo).where("final", "=", 0).where("retry_at", ">", new Date(now).toISOString())); - return r?.at ? Date.parse(r.at) : null; + return await loadStatusRetryAt(db, repo, now); } /** Backoffs that have ended, for the lane's fingerprint: the planner tries those PRs again once the time has passed. */ export async function statusRetriesDue(db: Db, now: number = Date.now()): Promise { - const r = await db.get(db.k.selectFrom("main.pr_status_comments").select((eb) => eb.fn.countAll().as("n")) - .where("final", "=", 0).where("retry_at", "<=", new Date(now).toISOString())); - return String(r?.n ?? 0); -} - -/** Each PR's open merge batch at its current head (`open:N`) and the batch it merged with (`merged:N`): the batch's PR number, null before it opens. */ -async function batchesOf(db: Db, repo: string, numbers: number[]): Promise> { - const rows = await db.all(db.k.selectFrom("main.merge_batch_prs as bp").innerJoin("main.merge_batches as b", "b.id", "bp.batch_id") - .innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "b.repo").onRef("i.number", "=", "bp.number")) - .select(["bp.number", "b.state", "b.pr_number", "bp.head_oid", "i.head_oid as head"]) - .where("b.repo", "=", repo).where("bp.number", "in", numbers).where("b.state", "in", [...ACTIVE_BATCH, "merged"]).orderBy("b.id")); - const out = new Map(); - for (const r of rows) { - if (r.state === "merged") out.set(`merged:${r.number}`, { pr: r.pr_number }); - else if (r.head_oid === r.head) out.set(`open:${r.number}`, { pr: r.pr_number }); - } - return out; + return String(await countStatusRetriesDue(db, now)); } const FIND_QUERY = `query($owner: String!, $name: String!, $n: Int!, $before: String) { @@ -277,7 +233,7 @@ async function searchComments(q: Querier, repo: string, number: number, pick: (c /** The login our comments are written as now (plainLogin), or null when it is not known. */ async function writerLogin(db: Db): Promise { - const login = await githubIdentity(db) === "box" ? await setting(db, "pipeline_login") : appSlug(); + const login = await githubIdentity(db) === "box" ? (await freshConfig(db, ["pipeline_login"])).pipelineLogin : appSlug(); return login ? plainLogin(login) : null; } @@ -354,7 +310,7 @@ export async function runPrStatus(db: Db, p: PrStatusParams): Promise; async function store(db: Db, repo: string, number: number, row: RowValues): Promise { - await db.run(db.k.insertInto("main.pr_status_comments").values({ repo, number, ...row }).onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet(row))); + await saveStatusComments(db, [{ repo, number, ...row }]); } diff --git a/src/repin/due.ts b/src/repin/due.ts index c9554de59..05c0523fa 100644 --- a/src/repin/due.ts +++ b/src/repin/due.ts @@ -1,8 +1,7 @@ // Which autorepins (src/repin/index.ts) have something to do now. Read from the database alone and without the modules the -// work needs, so the runner can ask on every tick. -import type { AliasableExpression, SqlBool } from "kysely"; +// work needs, so the runner can ask on every tick. The due rule lives with the rows (src/data/workflow/repins.ts). +import { hasRepinDue, loadRepinsDue } from "../data/workflow/index.ts"; import type { Db } from "../db/index.ts"; -import * as kx from "../db/kx.ts"; /** An attempt that did not finish is tried again after this long. */ export const RETRY_MS = 60_000; @@ -18,35 +17,11 @@ export type RepinRow = { sha: string | null; head: string | null; task_id: number | null; tries: number; to_head: string | null; result: string | null; notice: string | null; }; -// waiting: the dependency's pull request is no longer open (merged or closed), or this one is; locking: the lockfile task -// has ended, or has run out of time; ended: the comment that tells the outcome is still to post. -function due(eb: kx.AnyEb, now: Date): AliasableExpression { - const s = kx.schemaEb(eb); - const retryBefore = new Date(now.getTime() - RETRY_MS).toISOString(); - const lockBefore = new Date(now.getTime() - LOCK_MAX_MS).toISOString(); - return eb.or([ - eb.and([ - eb("a.state", "=", "waiting"), - eb.or([eb("a.tried_at", "is", null), eb("a.tried_at", "<=", retryBefore)]), - eb.or([ - eb.exists(s.selectFrom("main.items as i").select(eb.lit(1).as("one")).where("i.repo", "=", eb.ref("a.ref_repo")).where("i.number", "=", eb.ref("a.ref_number")).where("i.state", "!=", "OPEN")), - eb.not(eb.exists(s.selectFrom("main.items as i").select(eb.lit(1).as("one")).where("i.repo", "=", eb.ref("a.repo")).where("i.number", "=", eb.ref("a.number")).where("i.kind", "=", "pr").where("i.state", "=", "OPEN"))), - ]), - ]), - eb.and([ - eb("a.state", "=", "locking"), - eb.not(eb.exists(s.selectFrom("main.build_tasks as t").select(eb.lit(1).as("one")).where("t.id", "=", eb.ref("a.task_id")).where("t.state", "in", ["queued", "claimed", "running"]).where("t.queued_at", ">", lockBefore))), - ]), - eb.and([eb("a.state", "in", ["pushed", "failed", "cancelled"]), eb("a.notice", "is", null)]), - ]); -} - /** The autorepins with a step to take, oldest first. */ export async function repinsDue(db: Db, now: Date = new Date()): Promise { - return await db.all(db.k.selectFrom("main.autorepins as a").select(kx.cols("main.autorepins", "a")).$narrowType<{ state: RepinRow["state"] }>() - .where((eb) => due(eb, now)).orderBy("a.requested_at").orderBy("a.repo").orderBy("a.number")); + return (await loadRepinsDue(db, now)) as RepinRow[]; } export async function anyRepinDue(db: Db, now: Date = new Date()): Promise { - return !!await db.get(db.k.selectFrom("main.autorepins as a").select((eb) => eb.lit(1).as("one")).where((eb) => due(eb, now)).limit(1)); + return await hasRepinDue(db, now); } diff --git a/src/repin/index.ts b/src/repin/index.ts index 1b4cbb74c..33947d823 100644 --- a/src/repin/index.ts +++ b/src/repin/index.ts @@ -23,7 +23,6 @@ import { join } from "node:path"; import { absolute } from "../build/artifacts.ts"; import { cancelTask, createTask, getTask, TERMINAL } from "../build/tasks.ts"; import { guardRepo } from "../core/guard.ts"; -import { audit } from "../dash/audit.ts"; import { WRITE_PERMISSIONS } from "../dash/server/provider.ts"; import { HttpError } from "../dash/server/util.ts"; import { ensureAuthorWrites, type PermissionReader } from "../fixup/author-permission.ts"; @@ -36,17 +35,16 @@ import { ghComment, pushRepin, WritePacedError } from "../github/write.ts"; import type { Querier } from "../mirror.ts"; import { ownerOf, slugOf } from "../owners.ts"; import { appPermission } from "../remote/permission.ts"; -import { isFastTracked } from "../fasttrack.ts"; -import { baseScopeRepos } from "../pilot.ts"; import { isQuiet } from "../security/quiet.ts"; import { settleRefusal } from "../settlers.ts"; import { fetchScript } from "../worker/rust.ts"; import { BRANCH_MAX_MS, BRANCH_POLL_MS, LOCK_MAX_MS, RETRY_MS, repinsDue, type RepinRow } from "./due.ts"; import { lockRefusal, repinManifest, safePath, type PrRef } from "./manifest.ts"; -import type { ExpressionBuilder } from "kysely"; -import * as kx from "../db/kx.ts"; +import { addAudit, loadTrackedRepos } from "../data/control/index.ts"; +import { loadItems } from "../data/mirror/index.ts"; +import { loadArtifactFiles } from "../data/build/index.ts"; +import { loadRepinOffs, loadRepins, loadStartedRefs, requestRepin as writeRepin, saveRepins, type RepinKey, type RepinPatch } from "../data/workflow/index.ts"; import type { Db } from "../db/index.ts"; -import type { DB } from "../db/types.ts"; /** Attempts that may end unfinished (GitHub unreadable, the head moved, the lockfile task failed) before the repin is given up. */ export const MAX_TRIES = 5; @@ -90,17 +88,19 @@ const short = (sha: string): string => sha.slice(0, 12); const refOf = (r: { repo: string; number: number }): string => `${r.repo}#${r.number}`; const depRefOf = (r: { ref_repo: string; ref_number: number }): string => `${slugOf(r.ref_repo)}#${r.ref_number}`; type Item = { kind: string; state: string }; -const itemOf = async (db: Db, repo: string, number: number): Promise => - await db.get(db.k.selectFrom("main.items").select(["kind", "state"]).where("repo", "=", repo).where("number", "=", number)); +/** The mirror's kind and state of each pull request asked for, keyed `repo#number`. */ +const itemsOf = async (db: Db, refs: { repo: string; number: number }[]): Promise> => + await loadItems(db, refs, "ref"); // ---- the command --------------------------------------------------------------- /** - * Why no build worker would take the pull request's lockfile task, or null: workers take pipeline tasks only for repos in - * scope or for fast-tracked items (claim in src/build/tasks.ts). + * Why no build worker would take the pull request's lockfile task, or null: workers take pipeline tasks only for repos whose + * pipeline is on or for started items (claim in src/build/tasks.ts). */ async function outOfBuildScope(db: Db, repo: string, number: number): Promise { - return (await baseScopeRepos(db)).has(repo) || await isFastTracked(db, repo, number) ? null : `AutoCraft's pipeline is off for ${slugOf(repo)}, so no build worker would write its lockfile`; + const [tracked, started] = await db.together(() => Promise.all([loadTrackedRepos(db, [repo]), loadStartedRefs(db, { refs: [{ repo, number }] })])); + return tracked.get(repo)?.pipeline || started.has(`${repo}#${number}`) ? null : `AutoCraft's pipeline is off for ${slugOf(repo)}, so no build worker would write its lockfile`; } /** Cancels a lockfile task that is no longer wanted; one that already ended is left as it is. */ @@ -123,26 +123,30 @@ export async function requestRepin(db: Db, o: { login: string; githubId: number; const refusal = o.authorized ? null : await settleRefusal(db, { login: o.login, role: o.role, canWrite: async (r) => r === o.repo && o.canWrite }, [o.repo], `sets autorepin on ${o.repo}`); if (refusal) throw refused(refusal); const at = (o.at ?? new Date()).toISOString(); - const me = await itemOf(db, o.repo, o.number); + const ref = o.ref; + const [items, tracked, offs] = await db.together(() => Promise.all([ + itemsOf(db, [{ repo: o.repo, number: o.number }]), loadTrackedRepos(db), ref ? loadRepinOffs(db, [{ repo: o.repo, number: o.number }]) : Promise.resolve(new Map()), + ])); + const me = items.get(refOf(o)); if (me?.kind !== "pr" || me.state !== "OPEN") throw refused("this pull request is not open"); - if (!o.ref) { - // Kept even when nothing waits, so an older `autorepin` command still to be carried out (a retry) does not set it again. - await db.run(db.k.insertInto("main.autorepin_offs").values({ repo: o.repo, number: o.number, off_at: at }) - .onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet(kx.excluded(["off_at"])).whereRef("excluded.off_at", ">", "main.autorepin_offs.off_at"))); - const tasks = await db.all(db.k.selectFrom("main.autorepins").select("task_id").where("repo", "=", o.repo).where("number", "=", o.number).where("state", "=", "locking").where("requested_at", "<=", at)); - const n = (await db.run(db.k.updateTable("main.autorepins").set({ state: "cancelled", result: null, done_at: at, requested_at: at, notice: "none" }) - .where("repo", "=", o.repo).where("number", "=", o.number).where("state", "in", ["waiting", "locking"]).where("requested_at", "<=", at))).changes; - for (const t of tasks) await stopTask(db, t.task_id); - await audit(db, o.login, "autorepin-off", refOf(o), { cancelled: Number(n) }); - return n ? "Autorepin is off for this pull request" : "No autorepin was waiting on this pull request; it stays off"; + if (!ref) { + // The off marker is kept even when nothing waits, so an older `autorepin` command still to be carried out (a retry) does not set it again. + const r = await db.write(async () => { + const r = await writeRepin(db, { repo: o.repo, number: o.number, refRepo: "", refNumber: 0, refBranch: null, login: o.login, githubId: o.githubId, off: true, at }); + await addAudit(db, [{ login: o.login, action: "autorepin-off", target: refOf(o), details: { cancelled: r.cancelled } }]); + return r; + }); + for (const t of r.cancelledTasks) await stopTask(db, t); + return r.cancelled ? "Autorepin is off for this pull request" : "No autorepin was waiting on this pull request; it stays off"; } - const off = (await db.get(db.k.selectFrom("main.autorepin_offs").select("off_at").where("repo", "=", o.repo).where("number", "=", o.number)))?.off_at; + const off = offs.get(refOf(o)); if (off !== undefined && off > at) throw refused("a later autorepin off on this pull request stands"); - const dep = (await db.get(db.k.selectFrom("main.tracked_repos").select("name").where((eb) => kx.ciEq(db, "name", eb.val(o.ref!.name)))))?.name; - if (!dep || (o.ref.owner !== null && o.ref.owner.toLowerCase() !== ownerOf(dep).toLowerCase())) throw refused(`${o.ref.owner ? `${o.ref.owner}/` : ""}${o.ref.name} is not a repository AutoCraft tracks`); - const depRef = `${slugOf(dep)}#${o.ref.number}`; + const want = ref.name.toLowerCase(); + const dep = [...tracked.keys()].find((n) => n.toLowerCase() === want); + if (!dep || (ref.owner !== null && ref.owner.toLowerCase() !== ownerOf(dep).toLowerCase())) throw refused(`${ref.owner ? `${ref.owner}/` : ""}${ref.name} is not a repository AutoCraft tracks`); + const depRef = `${slugOf(dep)}#${ref.number}`; if (dep === o.repo) throw refused("the pull request to wait for must be in another repository"); - const other = await itemOf(db, dep, o.ref.number); + const other = (await itemsOf(db, [{ repo: dep, number: ref.number }])).get(`${dep}#${ref.number}`); if (other?.kind !== "pr") throw refused(`${depRef} is not a pull request AutoCraft has read`); if (other.state === "CLOSED") throw refused(`${depRef} was closed without merging`); const g = await guardRepo(db, o.repo, "push", { operator: o.login }, undefined, o.login); @@ -155,15 +159,17 @@ export async function requestRepin(db: Db, o: { login: string; githubId: number; } // Only over a row of an earlier command: a later `off`, or a later command for the same repository, stands. const branch = o.branch ?? null; - const set = (await db.run(db.k.insertInto("main.autorepins") - .values({ repo: o.repo, number: o.number, ref_repo: dep, ref_number: o.ref.number, ref_branch: branch, login: o.login, github_id: o.githubId, requested_at: at, state: "waiting" }) - .onConflict((oc) => oc.columns(["repo", "number", "ref_repo"]).doUpdateSet((eb) => ({ - ref_number: eb.ref("excluded.ref_number"), ref_branch: eb.ref("excluded.ref_branch"), login: eb.ref("excluded.login"), github_id: eb.ref("excluded.github_id"), - requested_at: eb.ref("excluded.requested_at"), state: "waiting", - sha: null, head: null, task_id: null, tries: 0, tried_at: null, to_head: null, result: null, done_at: null, notice: null, - })).whereRef("excluded.requested_at", ">=", "main.autorepins.requested_at")))).changes; - if (!set) throw refused(`a later autorepin command for ${slugOf(dep)} on this pull request stands`); - await audit(db, o.login, "autorepin-set", refOf(o), { on: depRef, ...(branch ? { via: branch } : {}) }); + try { + await db.write(async () => { + await writeRepin(db, { repo: o.repo, number: o.number, refRepo: dep, refNumber: ref.number, refBranch: branch, login: o.login, githubId: o.githubId, at }); + await addAudit(db, [{ login: o.login, action: "autorepin-set", target: refOf(o), details: { on: depRef, ...(branch ? { via: branch } : {}) } }]); + }); + } catch (e) { + const m = (e as Error).message; + if (m.includes("later autorepin off")) throw refused("a later autorepin off on this pull request stands"); + if (m.includes("later autorepin command")) throw refused(`a later autorepin command for ${slugOf(dep)} on this pull request stands`); + throw e; + } if (branch) { const to = `the first \`${branch}\` commit that contains it`; return other.state === "MERGED" @@ -215,16 +221,25 @@ class Wait extends Error {} class Superseded extends Error {} /** True while the row still holds the request `r` was read with: an `off` and a new command both move requested_at, and an end moves the state. */ -const still = async (db: Db, r: RepinRow): Promise => - !!await db.get(db.k.selectFrom("main.autorepins").select((eb) => eb.lit(1).as("one")).where(isRow(r)).where("state", "=", r.state).where("requested_at", "=", r.requested_at)); +const still = async (db: Db, r: RepinRow): Promise => !!await reread(db, r, { state: r.state, requestedAt: r.requested_at }); -const isRow = (r: RepinRow) => (eb: ExpressionBuilder) => - eb.and([eb("repo", "=", r.repo), eb("number", "=", r.number), eb("ref_repo", "=", r.ref_repo)]); +/** The stored row of `r`'s pull request and dependency (optionally only while it holds `state` and `requestedAt`), or null. */ +async function reread(db: Db, r: RepinRow, o: { state?: string; requestedAt?: string } = {}): Promise { + const row = (await loadRepins(db, [{ repo: r.repo, number: r.number }])).get(refOf(r))?.find((x) => x.ref_repo === r.ref_repo); + if (!row || (o.state !== undefined && row.state !== o.state) || (o.requestedAt !== undefined && row.requested_at !== o.requestedAt)) return null; + return row as RepinRow; +} + +/** The row's key; its pair, dependency and asker as read. */ +const keyOf = (r: RepinRow): RepinKey => ({ repo: r.repo, number: r.number, refRepo: r.ref_repo, refNumber: r.ref_number, login: r.login }); +const patchRow = async (db: Db, r: RepinRow, patch: RepinPatch): Promise => void await saveRepins(db, [{ key: keyOf(r), patch }]); async function finish(db: Db, r: RepinRow, e: Ended, at: Date): Promise { await stopTask(db, r.task_id); - await db.run(db.k.updateTable("main.autorepins").set({ state: e.state, result: e.message || null, done_at: at.toISOString(), to_head: e.toHead, notice: e.notice }).where(isRow(r))); - await audit(db, AUDIT_LOGIN, "autorepin", refOf(r), { on: depRefOf(r), by: r.login, state: e.state, ...(e.message ? { result: e.message } : {}), ...(e.toHead ? { commit: e.toHead } : {}) }); + await db.write(async () => { + await patchRow(db, r, { state: e.state, result: e.message || null, done_at: at.toISOString(), to_head: e.toHead, notice: e.notice }); + await addAudit(db, [{ login: AUDIT_LOGIN, action: "autorepin", target: refOf(r), details: { on: depRefOf(r), by: r.login, state: e.state, ...(e.message ? { result: e.message } : {}), ...(e.toHead ? { commit: e.toHead } : {}) } }]); + }); } /** One step of an autorepin: from `waiting` it queues the lockfile task (or pushes, without a lockfile); from `locking` it takes the task's lockfile and pushes. Throws `Ended` when it is over, anything else to try again. */ @@ -239,9 +254,10 @@ async function step(db: Db, r: RepinRow, d: RepinDeps): Promise { throw failed("the lockfile task did not end within 3 hours"); } } - const me = await itemOf(db, r.repo, r.number); + const items = await itemsOf(db, [{ repo: r.repo, number: r.number }, { repo: r.ref_repo, number: r.ref_number }]); + const me = items.get(refOf(r)); if (me?.kind !== "pr" || me.state !== "OPEN") throw new Ended("cancelled", null, { notice: "none" }); - const other = await itemOf(db, r.ref_repo, r.ref_number); + const other = items.get(`${r.ref_repo}#${r.ref_number}`); if (!other) throw failed(`AutoCraft no longer has ${depRef}`); if (other.state === "CLOSED") throw new Ended("cancelled", `${depRef} was closed without merging, so nothing was repinned`); @@ -381,14 +397,14 @@ async function step(db: Db, r: RepinRow, d: RepinDeps): Promise { step: "autorepin", repo: r.repo, number: r.number, headSha: head, requires: { os: "linux", toolchains: ["rust-stable"] }, patch, plan: [{ name: "lock", cmd: ["sh", "-c", LOCK_SCRIPT], network: "fetch", timeoutSec: 900, artifacts: [LOCK] }], }); - await db.run(db.k.updateTable("main.autorepins").set({ state: "locking", sha: target, head, to_head: null, task_id: id }).where(isRow(r))); + await patchRow(db, r, { state: "locking", sha: target, head, to_head: null, task_id: id }); d.log?.(`autorepin ${refOf(r)}: lockfile task ${id} queued for ${dep} at ${short(target)}`); return; } - const t = await db.get(db.k.selectFrom("main.build_tasks").select("state").where("id", "=", r.task_id)); - if (t?.state !== "done") throw new Retry(`the lockfile task ${t ? t.state : "is gone"}`); - const art = await db.get(db.k.selectFrom("main.build_artifacts").select("file").where("task_id", "=", r.task_id).where("name", "=", LOCK)); - const file = art ? absolute(art.file) : null; + const t = r.task_id === null ? null : await getTask(db, r.task_id); + if (!t || t.state !== "done") throw new Retry(`the lockfile task ${t ? t.state : "is gone"}`); + const art = (await loadArtifactFiles(db, [{ taskId: t.id, name: LOCK }])).get(`${t.id}/${LOCK}`); + const file = art ? absolute(art) : null; if (!file) throw new Retry("the lockfile task returned no Cargo.lock"); const after = readFileSync(file, "utf8"); const no = lockRefusal(lock.content, after, dep, target); @@ -405,7 +421,7 @@ async function step(db: Db, r: RepinRow, d: RepinDeps): Promise { if (changes.some((x) => x[2] !== "M" || x[0] !== x[1]) || changes.map((x) => x[3]!).sort().join("\n") !== [...changed].sort().join("\n")) throw failed("the commit would change more than the revs and the lockfile"); if (!await still(db, r)) throw new Superseded("the request changed before the push"); // Written before the push, so a head that reaches the mirror before the outcome is recorded is already known as this commit (ownPush in src/preapproval). - await db.run(db.k.updateTable("main.autorepins").set({ head, to_head: commit }).where(isRow(r))); + await patchRow(db, r, { head, to_head: commit }); const push = await pushRepin({ db, login: AUDIT_LOGIN }, g, git, { repo: r.repo, number: r.number, remote: headRepo, branch: pr.headRefName, head, sha: commit }, { on: depRef, rev: target, files: changed, by: r.login }); if (push.code !== 0) { const err = oneLine(push.stderr); @@ -456,7 +472,7 @@ export function noticeText(r: Pick { // A quiet pull request (a security fix not yet published) gets no comment. if (await isQuiet(db, r.repo, r.number)) { - await db.run(db.k.updateTable("main.autorepins").set({ notice: "none" }).where(isRow(r))); + await patchRow(db, r, { notice: "none" }); return "none"; } const g = await guardRepo(db, r.repo, null, { operator: r.login }, undefined, r.login); @@ -472,7 +488,7 @@ async function notify(db: Db, r: RepinRow, d: RepinDeps): Promise<"posted" | "fa d.log?.(`autorepin ${refOf(r)}: the comment failed: ${oneLine(String((e as Error)?.message ?? e))}`); } } - await db.run(db.k.updateTable("main.autorepins").set({ notice }).where(isRow(r))); + await patchRow(db, r, { notice }); return notice; } @@ -500,7 +516,7 @@ export async function drainRepins(db: Db, deps: RepinDeps): Promise { else if (e instanceof Wait) { // Not a try, and it clears the count, so MAX_TRIES counts consecutive failures only: tried_at is set ahead, so the row is due again (repinsDue: a minute after tried_at) in BRANCH_POLL_MS. await stopTask(db, r.task_id); - await db.run(db.k.updateTable("main.autorepins").set({ state: "waiting", task_id: null, tries: 0, tried_at: new Date(clock().getTime() + BRANCH_POLL_MS - RETRY_MS).toISOString() }).where(isRow(r))); + await patchRow(db, r, { state: "waiting", task_id: null, tries: 0, tried_at: new Date(clock().getTime() + BRANCH_POLL_MS - RETRY_MS).toISOString() }); deps.log?.(`autorepin ${refOf(r)}: ${e.message}`); continue; } else { @@ -511,13 +527,13 @@ export async function drainRepins(db: Db, deps: RepinDeps): Promise { if (r.tries + 1 >= MAX_TRIES) await finish(db, r, failed(e instanceof Retry ? raw : UNEXPECTED), clock()); else { await stopTask(db, r.task_id); - await db.run(db.k.updateTable("main.autorepins").set((eb) => ({ state: "waiting", task_id: null, tries: eb("tries", "+", 1), tried_at: clock().toISOString() })).where(isRow(r))); + await patchRow(db, r, { state: "waiting", task_id: null, tries: r.tries + 1, tried_at: clock().toISOString() }); continue; } } } ended++; - r = (await db.get(db.k.selectFrom("main.autorepins").select(kx.cols("autorepins")).where(isRow(r)).$narrowType<{ state: RepinRow["state"] }>()))!; + r = (await reread(db, r))!; deps.log?.(`autorepin ${refOf(r)}: ${r.state}${r.result ? `: ${r.result}` : ""}`); } if (r.notice === null && (await notify(db, r, deps)) === "paced") break;