From b69e9fe290fa0b7c6ed7597d950eabcde893cbd9 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:44:29 +0000 Subject: [PATCH] Record the required-check outcome of every push of ours and trip a stage after repeated breakage push_outcomes records the required-check result before and after each fix-up, conflict, CI fix and fix-issue push. A push that turned the checks red makes the CI fix work on the pushed head first. A push stage pauses itself when 2 of its last 10 pushes broke a check; the merge path pauses when main CI turns red because of a merge of ours or a post-merge review finds a defect. An operator resumes a stage with autocraft pipeline resume or the Pipeline page. --- src/core/decide.ts | 12 ++- src/core/facts.ts | 12 ++- src/core/gates.ts | 5 + src/core/issue-facts.ts | 3 +- src/core/plan.ts | 6 ++ src/core/push-outcome.ts | 52 ++++++++++ src/core/select.ts | 2 +- src/dash/api/index.ts | 1 + src/dash/api/pipeline.ts | 13 +++ src/github/write.ts | 15 ++- src/live.ts | 4 +- src/mainci/index.ts | 3 + src/postmerge/review.ts | 2 + src/push-outcomes.ts | 140 ++++++++++++++++++++++++++ src/review/checks.ts | 2 + src/runner/autopilot.ts | 6 +- src/runner/index.ts | 13 ++- src/schema.sql | 32 ++++++ src/stages/registry.ts | 1 + test/decide-pr.test.ts | 10 ++ test/guard.test.ts | 9 ++ test/push-outcome.test.ts | 22 ++++ web/src/api/client.ts | 2 + web/src/api/http.ts | 1 + web/src/api/mock/pipelineMock.ts | 7 ++ web/src/api/types.ts | 2 + web/src/modules/pipeline/controls.tsx | 16 +++ 27 files changed, 377 insertions(+), 16 deletions(-) create mode 100644 src/core/push-outcome.ts create mode 100644 src/push-outcomes.ts create mode 100644 test/push-outcome.test.ts diff --git a/src/core/decide.ts b/src/core/decide.ts index ee672cbb..065d8ae6 100644 --- a/src/core/decide.ts +++ b/src/core/decide.ts @@ -155,8 +155,10 @@ export type CifixBucket = "work" | "unapproved" | "cannot-push" | "formatting" | /** Where the CI fix step stands for a PR whose CI fails at the reviewed head, or null when it is no candidate. */ export function cifixBucket(f: PrFacts): CifixBucket | null { const r = f.review, c = f.cifix; - if (declinedBy(f) || !r || !c || (r.verdict !== "take" && r.verdict !== "take-fix") || r.head !== f.head || f.ghState !== "OPEN" || f.ci !== "failure" || f.draft || !notHeld(f)) return null; - if (f.mergeable === "CONFLICTING" || r.stale || f.changesRequested || f.mergeHeld) return null; + // Our own push that turned the checks red is repaired against the pushed head, whose review is still the one of the head before. + const broke = !!f.brokeByUs; + if (declinedBy(f) || !r || !c || (r.verdict !== "take" && r.verdict !== "take-fix") || (r.head !== f.head && !broke) || f.ghState !== "OPEN" || (f.ci !== "failure" && !broke) || f.draft || !notHeld(f)) return null; + if (f.mergeable === "CONFLICTING" || (r.stale && !broke) || f.changesRequested || f.mergeHeld) return null; if (r.verdict === "take-fix") { const fx = fixupOf(f); if (fx && ["fix", "unapproved", "ask"].includes(fx.bucket)) return null; @@ -271,7 +273,11 @@ export function decidePr(f: PrFacts): Plan { } const cf = cifixOf(f); - if (cf && cf !== "other") actions.push(act("cifix", f.head, { bucket: cf })); + if (cf && cf !== "other") { + // Repairing our own breakage comes before every other action of the PR. + if (f.brokeByUs && (cf === "work" || cf === "collect")) actions.unshift(act("cifix", f.head, { bucket: cf })); + else actions.push(act("cifix", f.head, { bucket: cf })); + } // Stored model patches whose lint task ended: the collect step folds the format changes and pushes, or sends the findings back to the model. for (const l of f.lint) { diff --git a/src/core/facts.ts b/src/core/facts.ts index 08e527c0..b6ac7d1e 100644 --- a/src/core/facts.ts +++ b/src/core/facts.ts @@ -32,6 +32,7 @@ import { scopeAnswers } from "../review/candidates.ts"; import { NOT_RUST_REASON, PRIVATE_REASON, cachedRust } from "../verify/candidates.ts"; import { CIFIX_PUSH_STATES, CIFIX_TRY_STATES, MAX_FAILURES, sizeOf } from "./rules.ts"; import type { PrFacts, PrTier } from "./plan.ts"; +import { activeTrips, brokeHeads } from "../push-outcomes.ts"; export type { PrFacts } from "./plan.ts"; @@ -108,6 +109,8 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const inBatch = batchStates(db, opts.repo); const own = ownFixPrs(db, opts.repo); const mainRed = redMainRepos(db); + const tripped = activeTrips(db); + const brokeAt = brokeHeads(db, opts.repo); const answers = new Map(actionable(db).filter((a) => a.kind === "merge").map((a) => [a.id, a.answer])); const pipelineOn = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_enabled'").get() as { value: string } | undefined)?.value === "1"; const pipelineLogin = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? null; @@ -192,7 +195,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const head = batchRow?.commit_sha ?? headOf(r); const lines = (r.additions ?? 0) + (r.deletions ?? 0); const base: PrFacts = { - repo: r.repo, number: r.number, now, pipelineOn, ghState: r.state, head, draft: fresh ? r.c_state !== "OPEN" || !!r.c_draft : !!r.is_draft, + repo: r.repo, number: r.number, now, pipelineOn, tripped, ghState: r.state, head, draft: fresh ? r.c_state !== "OPEN" || !!r.c_draft : !!r.is_draft, author: r.author, authorIsPipeline: r.author !== null && r.author === pipelineLogin, tier: "not", lines, size: sizeOf(lines), label: null, needsDecisionFlag: false, scopeAnswer: scope.get(ref) ?? null, inScope, integration, batchPr: !!r.batch_pr, heldBacklog: !!r.held_backlog, heldDuplicate: !r.held_backlog && !!r.held_dup, mergeHeld: holds.has(ref), @@ -262,6 +265,8 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] const approvedPending = parseList(wait?.approved ?? "[]").length > 0; base.ci = checksHere ? (approvedPending ? "pending" : effectiveCi(db, r.repo, r.overall ?? "none", r.c_checks)) : "unknown"; base.runs = runsOf(wait, rf.f.ciApproved); + // Our push to this head turned its required checks red: the CI fix works on it now, without waiting for a review of the new head. + base.brokeByUs = brokeAt.get(ref) === head && r.c_head === head && effectiveCi(db, r.repo, r.overall ?? "none", r.c_checks) === "failure"; base.tier = (r.author ? tiers.get(r.author) : undefined) ?? "not"; // The pipeline's own Fix PRs count as whitelisted; an operator's deny still wins. if (base.tier === "not" && r.author && r.author === own.login && own.prs.has(ref)) base.tier = "whitelisted"; @@ -303,8 +308,9 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[] } for (const x of lintCifix.all(r.repo, r.number, r.r_head) as { lint_task: number | null }[]) base.lint.push({ step: "cifix", source: "review", ended: ended(x.lint_task) }); } - if (base.ci === "failure") { - const prior = cifixRows.all(r.repo, r.number, r.r_head) as { state: string; created_at: string; task_id: number | null; runs: string | null }[]; + if (base.ci === "failure" || base.brokeByUs) { + const cfHead = base.brokeByUs ? head : r.r_head; + const prior = cifixRows.all(r.repo, r.number, cfHead) as { state: string; created_at: string; task_id: number | null; runs: string | null }[]; const totals = cifixTotals.get(...CIFIX_PUSH_STATES, ...CIFIX_TRY_STATES, r.repo, r.number) as { pushes: number; tries: number }; const formatting = prior.find((x) => x.state === "formatting"); const task = formatting?.task_id != null ? getTask(db, formatting.task_id) : null; diff --git a/src/core/gates.ts b/src/core/gates.ts index 44368dd1..38de384a 100644 --- a/src/core/gates.ts +++ b/src/core/gates.ts @@ -1,6 +1,7 @@ // The gates on writes: the repo approvals each action needs and the global pipeline switch. Pure. The planner and the // guard (guard.ts) both use it; decide() does not (it shows what would run, approved or not). import type { ActionKind, ItemFacts, PrFacts } from "./plan.ts"; +import { tripStageOf } from "./push-outcome.ts"; /** Who asks for a write: the pipeline itself (the autopilot), or an operator (a job they requested, or a command they ran). */ export type By = "pipeline" | { operator: string }; @@ -50,6 +51,10 @@ export function approvalOf(f: { pushable?: boolean }, a: Want): Approval | null /** Why the write is refused, or null. */ export function gates(f: PrFacts | ItemFacts, a: Want, by: By): string | null { if (by === "pipeline" && !f.pipelineOn) return "the pipeline is off"; + // A stage that stopped itself (circuit breaker) writes nothing until an operator resumes it, whoever asks. + const stage = tripStageOf(a); + const tripped = stage && (f as { tripped?: Partial> }).tripped?.[stage]; + if (tripped) return `${stage} is paused: ${tripped}`; const need = approvalOf(f as { pushable?: boolean }, a); if (!need) return null; const r = f.repoFacts as Record; diff --git a/src/core/issue-facts.ts b/src/core/issue-facts.ts index c0783db3..ed44ae38 100644 --- a/src/core/issue-facts.ts +++ b/src/core/issue-facts.ts @@ -1,5 +1,6 @@ // Facts of open items (issues and PRs) for the triage steps: classification, priority, embedding, duplicates, scope decision, labels. // Loaded in one pass for a whole database or a slice. Reads only: the old selectors fill missing text hashes in the database on the way; here a missing hash is computed. +import { activeTrips } from "../push-outcomes.ts"; import type { DatabaseSync } from "node:sqlite"; import { notOwnIntegrationSql, groupHeldSql, backlogHeldSql } from "../dupes/held.ts"; import { FAST_FLOOR, fastScoreSql } from "../fasttrack.ts"; @@ -193,7 +194,7 @@ export function loadItemFacts(db: DatabaseSync, opts: ItemLoadOptions = {}): Ite const embedHash = r.embed_hash ?? (() => { const b = textOf.get(r.repo, r.number) as { title: string | null; body: string | null }; return hashOfText(b.title, b.body); })(); const note = labeled.get(ref) ?? null; return { - repo: r.repo, number: r.number, kind: r.kind, open: r.state === "OPEN", now, pipelineOn, draft: !!r.is_draft, + repo: r.repo, number: r.number, kind: r.kind, open: r.state === "OPEN", now, pipelineOn, tripped: activeTrips(db), draft: !!r.is_draft, inScope: !!r.in_pilot, integration: !r.not_integration, held: r.held_backlog ? "backlog" : r.held_dup ? "duplicate" : null, fast: (r.score ?? 0) >= FAST_FLOOR, score: r.score, repoFacts: { labelsApproved: labelsApproved(r.repo), commentApproved: repoOf(r.repo).comment, fixIssueApproved: repoOf(r.repo).fix }, diff --git a/src/core/plan.ts b/src/core/plan.ts index dfaf8486..cd51e432 100644 --- a/src/core/plan.ts +++ b/src/core/plan.ts @@ -86,6 +86,10 @@ export type PrFacts = { now: number; /** The global pipeline switch. decide() ignores it; gates() applies it to the pipeline's own writes. */ pipelineOn: boolean; + /** Stages that stopped themselves (circuit breaker), by stage name (fixup, cifix, fixissue, merge): the reason. gates() refuses their writes. */ + tripped?: Partial>; + /** A push of ours made the required checks at this head go red: CI fix works on it ahead of other work, even before a review of this head. */ + brokeByUs?: boolean; /** GitHub state as mirrored. */ ghState: "OPEN" | "MERGED" | "CLOSED"; /** The PR's current head commit (checks fetched after the mirror's last update win over the mirror). */ @@ -243,6 +247,8 @@ export type ItemFacts = { score: number | null; /** The global pipeline switch. decideItem ignores it; gates() applies it to the pipeline's own writes. */ pipelineOn: boolean; + /** As on PrFacts. */ + tripped?: Partial>; /** The repo's approvals for the writes below. decideItem does not apply them: gates() does. */ repoFacts: { labelsApproved: boolean; commentApproved: boolean; fixIssueApproved: boolean }; diff --git a/src/core/push-outcome.ts b/src/core/push-outcome.ts new file mode 100644 index 00000000..1dd613cb --- /dev/null +++ b/src/core/push-outcome.ts @@ -0,0 +1,52 @@ +// What a push of ours did to the PR's required checks, and when a stage stops itself because of it. Pure. + +/** The result of the required checks at one commit. Optional checks and skipped ones do not count. */ +export type Required = "green" | "red" | "pending" | "none"; +export type Outcome = "kept-green" | "fixed" | "broke" | "still-red" | "unknown"; + +/** The stages that push or merge, as the circuit breaker names them. */ +export const TRIP_STAGES = ["fixup", "cifix", "fixissue", "merge"] as const; +export type TripStage = (typeof TRIP_STAGES)[number]; + +/** Pushes the breaker looks at, and how many of them breaking a required check trips the stage. */ +export const BREAKER_WINDOW = 10; +export const BREAKER_BROKE = 2; + +export function requiredResult(checks: { name: string; state: string }[], optional: string[]): Required { + const req = checks.filter((c) => !optional.includes(c.name) && c.state !== "skipped"); + if (req.some((c) => c.state === "failure")) return "red"; + if (req.some((c) => c.state === "pending")) return "pending"; + return req.some((c) => c.state === "success") ? "green" : "none"; +} + +/** The outcome once the checks after the push are final, or null while they are not. A side without a known result gives `unknown`. */ +export function classifyPush(before: Required | "unknown", after: Required | "unknown"): Outcome | null { + if (after === "pending") return null; + if (after === "red") return before === "green" ? "broke" : before === "red" ? "still-red" : "unknown"; + if (after === "green") return before === "red" ? "fixed" : before === "green" ? "kept-green" : "unknown"; + return "unknown"; +} + +/** True when `broke` is at least BREAKER_BROKE of the newest BREAKER_WINDOW outcomes (newest first; null: not known yet). */ +export function breakerTripped(newestFirst: (Outcome | null)[]): boolean { + return newestFirst.slice(0, BREAKER_WINDOW).filter((o) => o === "broke").length >= BREAKER_BROKE; +} + +/** The breaker stage of an audit push action. */ +export const PUSH_STAGE: Record = { "fixup-push": "fixup", "conflict-push": "fixup", "cifix-push": "cifix", "fixissue-push": "fixissue" }; + +/** The breaker stage a runner step belongs to. */ +export const STEP_STAGE: Record = { fixup: "fixup", cifix: "cifix", fixissue: "fixissue", "fixissue-collect": "fixissue", merge: "merge" }; + +/** The stage an action's push or merge belongs to, or null for an action that writes no commit (asks, comments, reruns). */ +export function tripStageOf(a: { kind: string; bucket?: string }): TripStage | null { + switch (a.kind) { + case "fixup": return a.bucket === "fix" ? "fixup" : null; + case "conflict": return a.bucket === "merge" ? "fixup" : null; + case "cifix": return a.bucket === "work" || a.bucket === "collect" ? "cifix" : null; + case "lint": return a.bucket === "cifix" ? "cifix" : "fixup"; + case "fixissue": case "fixissue-collect": return "fixissue"; + case "merge": return "merge"; + default: return null; + } +} diff --git a/src/core/select.ts b/src/core/select.ts index 1f948792..3fd3ce71 100644 --- a/src/core/select.ts +++ b/src/core/select.ts @@ -41,6 +41,6 @@ export function planned(db: DatabaseSync, kind: ActionKind, opts: PlannedOptions if (action.kind === kind && (bucket === undefined || action.params?.bucket === bucket)) out.push({ facts, plan, action }); } } - return out.sort((a, b) => (a.facts.score === null ? 1 : 0) - (b.facts.score === null ? 1 : 0) || (b.facts.score ?? 0) - (a.facts.score ?? 0) + return out.sort((a, b) => (b.facts.brokeByUs ? 1 : 0) - (a.facts.brokeByUs ? 1 : 0) || (a.facts.score === null ? 1 : 0) - (b.facts.score === null ? 1 : 0) || (b.facts.score ?? 0) - (a.facts.score ?? 0) || (a.facts.repo < b.facts.repo ? -1 : a.facts.repo > b.facts.repo ? 1 : 0) || a.facts.number - b.facts.number); } diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index b176f57b..818281db 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -415,6 +415,7 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { { method: "PUT", pattern: "/api/pipeline/state", operator: true, handler: ok(pipeline.putState) }, { method: "PUT", pattern: "/api/pipeline/limits/:step", operator: true, handler: ok(pipeline.putLimit) }, { method: "POST", pattern: "/api/pipeline/limits/:step/reset", operator: true, handler: ok(pipeline.resetLimit) }, + { method: "POST", pattern: "/api/pipeline/trips/:stage/resume", operator: true, handler: ok(pipeline.resumeTrip) }, { method: "PUT", pattern: "/api/pipeline/pilot", operator: true, handler: ok(adm.putPilot) }, get("/api/prompts", prompts), get("/api/accounts", agents.accounts), diff --git a/src/dash/api/pipeline.ts b/src/dash/api/pipeline.ts index 84be747e..57d51211 100644 --- a/src/dash/api/pipeline.ts +++ b/src/dash/api/pipeline.ts @@ -9,6 +9,7 @@ import { LimitError, pipelineState, resetLimitCount, setEnabled, setLimit } from import { HEARTBEAT_KEY } from "../../runner/runner.ts"; import { loadSteps, type StepDef } from "../../runner/steps.ts"; import { audit } from "../audit.ts"; +import { resumeStage, TripError } from "../../push-outcomes.ts"; import { HttpError } from "../server/util.ts"; import type { Req } from "../types.ts"; import { hiddenRepos, visibleRepos } from "./visible.ts"; @@ -173,6 +174,18 @@ export async function putLimit(db: DatabaseSync, req: Req) { return (await pipelineState(db)).limits.find((l) => l.step === req.params.step)!; } +/** An operator clears a stage the circuit breaker paused. */ +export async function resumeTrip(db: DatabaseSync, req: Req) { + requireOperator(req); + try { + resumeStage(db, req.params.stage, req.user.login); + } catch (e) { + if (e instanceof TripError) throw new HttpError(e.status, e.message); + throw e; + } + return pipelineState(db); +} + /** Starts today's count of a step again from zero; the step `all` resets every stage. */ export async function resetLimit(db: DatabaseSync, req: Req) { requireOperator(req); diff --git a/src/github/write.ts b/src/github/write.ts index 39ea8976..ba2ca96b 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -7,6 +7,7 @@ import type { DatabaseSync } from "node:sqlite"; import { ORG } from "../act/templates.ts"; import { connect } from "../db.ts"; +import { recordPush } from "../push-outcomes.ts"; import type { Grant, Guarded, GuardedItem, GuardedRepo } from "../core/guard.ts"; /** The PR steps that push to a contributor's branch or ask on the PR where it is closed to us (`lint`: the collect step of a stored patch). */ @@ -273,20 +274,26 @@ export function ghRerunMainFailed(w: Writer, g: GuardedRepo, exec: Exec, o: { re export function pushBranch(w: Writer, git: Pick, action: string, g: Guarded, o: { remote: string; branch: string; sha: string }, details: Details = {}): Promise { const b = g.action.bucket; if ((g.action.kind === "fixup" && b === "ask") || (g.action.kind === "cifix" && b === "rerun")) throw new Error(`a ${g.action.kind}:${b} grant does not allow a push`); - return pushed(w, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details); + return pushed(w, git, action, refOf(g.repo, g.number), o, `--force-with-lease=refs/heads/${o.branch}:${g.head}`, details, { repo: g.repo, number: g.number }); } /** Pushes `sha` to `branch` of the pipeline's own fork, replacing the branch. */ export function pushOwnBranch(w: Writer, g: Grant, git: Pick, action: string, o: { repo: string; number?: number; remote: string; branch: string; sha: string }, details: Details = {}): Promise { covers(g, o.repo); - return pushed(w, git, action, o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number), o, "--force", details); + // A new branch has no PR yet: its outcome is matched to the PR by commit once the PR's checks arrive. + return pushed(w, git, action, o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number), o, "--force", details, { repo: o.repo, number: null }); } -function pushed(w: Writer, git: Pick, action: string, target: string, o: { remote: string; branch: string; sha: string }, lease: string, details: Details): Promise { - return recorded(w, action, target, { ...details, branch: o.branch, remote: o.remote, commit: o.sha }, +async function pushed(w: Writer, git: Pick, action: string, target: string, o: { remote: string; branch: string; sha: string }, lease: string, details: Details, pr: { repo: string; number: number | null }): Promise { + const r = await recorded(w, action, target, { ...details, branch: o.branch, remote: o.remote, commit: o.sha }, () => git.git(["push", "--quiet", lease, `https://github.com/${o.remote}.git`, `${o.sha}:refs/heads/${o.branch}`]), undefined, (r) => (r.code === 0 ? null : oneLine(r.stderr) || `exit code ${r.code}`)); + if (r.code === 0) { + // The push stands even when its bookkeeping cannot be written; the outcome stays unknown then. + try { recordPush(w.db, action, { ...pr, from: typeof details.from === "string" ? details.from : null, to: o.sha }); } catch (e) { console.error(`push outcome not recorded: ${oneLine(String((e as Error).message ?? e))}`); } + } + return r; } // ---- merges --------------------------------------------------------------------- diff --git a/src/live.ts b/src/live.ts index 17ea8529..8222cc0d 100644 --- a/src/live.ts +++ b/src/live.ts @@ -60,7 +60,7 @@ export const TOPIC_TABLES: Record = { fasttrack: [{ table: "fast_track" }], // The planner's Plan cache; its own output, so the planner does not plan again for it. plans: [{ table: "item_plans" }], - jobs: [{ table: "jobs" }, { table: "stage_limits" }], + jobs: [{ table: "jobs" }, { table: "stage_limits" }, { table: "stage_trips" }], usage: [{ table: "token_usage" }, { table: "account_usage_samples" }], accounts: [{ table: "claude_accounts" }, { table: "claude_account_status" }], agents: [{ table: "agent_runs" }, { table: "agent_run_items" }, { table: "agent_run_texts" }], @@ -85,7 +85,7 @@ export const TOPIC_TABLES: Record = { { table: "dupe_group_items" }, { table: "item_rank" }, { table: "classifications", ops: ["INSERT", "DELETE"] }, { table: "classifications", ops: ["UPDATE"], when: ["classifier", "run_id", "at", "type_label", "want", "reference", "flags", "dup_of", "reason", "probs", "input_hash"].map((c) => `old.${c} IS NOT new.${c}`).join(" OR ") }, { table: "opus_reviews" }, { table: "verifications" }, - { table: "fix_attempts" }, { table: "postmerge_followups" }, { table: "premerge_reviews" }, { table: "pr_checks" }, { table: "fast_track" }, { table: "merge_holds" }, { table: "merges" }, { table: "merge_batches" }, + { table: "fix_attempts" }, { table: "postmerge_followups" }, { table: "premerge_reviews" }, { table: "pr_checks" }, { table: "push_outcomes" }, { table: "stage_trips" }, { table: "fast_track" }, { table: "merge_holds" }, { table: "merges" }, { table: "merge_batches" }, { table: "merge_batch_prs" }, { table: "tracked_repos" }, { table: "settings", when: "new_key IN ('pilot_items', 'classify_run', 'pipeline_login')" }, ], diff --git a/src/mainci/index.ts b/src/mainci/index.ts index f6737e80..c48dc7b3 100644 --- a/src/mainci/index.ts +++ b/src/mainci/index.ts @@ -7,6 +7,7 @@ import type { Querier } from "../mirror.ts"; import { contextState, ORG, type CheckState } from "../review/checks.ts"; import { trackedNames } from "../repos.ts"; import { optionalChecks } from "../optional-checks.ts"; +import { mainRedAfterMerge } from "../push-outcomes.ts"; import { autocraftText } from "../mainfix/status.ts"; import { classify, derive, type Culprit, type HeadRow, type MainCheck, type MainCiState } from "./classify.ts"; @@ -95,6 +96,8 @@ export async function pollMainCi(db: DatabaseSync, client: Querier, only?: strin heads++; } } + // A red head whose culprit is a PR we merged stops the merge path. + for (const r of mainCiRepos(db)) if (r.state === "red" && r.culprit?.pr) mainRedAfterMerge(db, r.repo, r.culprit.pr, r.culprit.sha); if (!only) db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(KEY_POLLED_AT, new Date().toISOString()); log(`main-ci: ${heads} heads of ${repos.length} repos`); return { repos: repos.length, heads }; diff --git a/src/postmerge/review.ts b/src/postmerge/review.ts index e2ad14f3..91f57a3b 100644 --- a/src/postmerge/review.ts +++ b/src/postmerge/review.ts @@ -7,6 +7,7 @@ import { pool } from "../classify/run.ts"; import { runModelStep } from "../agents/step.ts"; import { POSTMERGE_OPUS } from "../agents/steps.ts"; import { audit } from "../dash/audit.ts"; +import { mergeDefect } from "../push-outcomes.ts"; import { CLAUDE_PROMPTS } from "../prompts/index.ts"; import { referenceDir } from "../reference.ts"; import { defaultSemanticDeps, type SemanticDeps } from "../reference-lint.ts"; @@ -131,6 +132,7 @@ export function saveReview(db: DatabaseSync, c: { repo: string; number: number } db.prepare("INSERT OR REPLACE INTO postmerge_reviews (repo, number, merge_sha, at, model, run_id, findings, error, tries) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)") .run(c.repo, c.number, r.sha, at, r.model, r.runId, r.findings ? JSON.stringify(r.findings) : null, error, tries); const skip = db.prepare("INSERT OR IGNORE INTO postmerge_followups (repo, number, review_at, finding, title, issue_number, url, state, at, duplicate_of) VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?)"); + mergeDefect(db, c.repo, c.number, (r.findings ?? []).filter((f) => f.severity === "defect").length); (r.findings ?? []).forEach((f, i) => { if (f.severity === "minor") skip.run(c.repo, c.number, at, i, f.title, "skipped-minor", at, null); else if (f.duplicate_of !== null) skip.run(c.repo, c.number, at, i, f.title, "skipped-duplicate", at, f.duplicate_of); diff --git a/src/push-outcomes.ts b/src/push-outcomes.ts new file mode 100644 index 00000000..0a0a9496 --- /dev/null +++ b/src/push-outcomes.ts @@ -0,0 +1,140 @@ +// What our pushes did to the required checks of their PRs, and the circuit breaker built on it (pure rules: core/push-outcome.ts). +// Recording happens where the push is audited (github/write.ts); the outcome is computed where the checks are stored (review/checks.ts). +import type { DatabaseSync } from "node:sqlite"; +import { audit } from "./dash/audit.ts"; +import { optionalChecks } from "./optional-checks.ts"; +import { + breakerTripped, classifyPush, PUSH_STAGE, requiredResult, STEP_STAGE, TRIP_STAGES, + type Outcome, type Required, type TripStage, +} from "./core/push-outcome.ts"; + +/** Unresolved pushes older than this get the outcome `unknown` (the head moved on, or the checks never ran). */ +const EXPIRE_MS = 3 * 24 * 3_600_000; + +type CheckRow = { name: string; state: string }[]; +const parse = (s: string | null | undefined): CheckRow => { try { const v = JSON.parse(s ?? "[]") as unknown; return Array.isArray(v) ? (v as CheckRow) : []; } catch { return []; } }; + +/** + * Records a push that succeeded: the required-check result at the head before it (from the stored checks, when they are for that head). + * A branch the push created has no earlier head and counts as green. Pushes of other kinds (batches, main fixes) are not recorded. + */ +export function recordPush(db: DatabaseSync, action: string, o: { repo: string; number: number | null; from: string | null; to: string }, at = new Date().toISOString()): void { + const stage = PUSH_STAGE[action]; + if (!stage) return; + let before: Required | "unknown" = "unknown"; + if (!o.from) before = "green"; + else if (o.number !== null) { + const row = db.prepare("SELECT head_oid, checks FROM pr_checks WHERE repo = ? AND number = ?").get(o.repo, o.number) as { head_oid: string; checks: string } | undefined; + if (row && row.head_oid === o.from) before = requiredResult(parse(row.checks), optionalChecks(db, o.repo)); + } + db.prepare("INSERT INTO push_outcomes (at, stage, action, repo, number, from_oid, to_oid, before_res) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + .run(at, stage, action, o.repo, o.number, o.from, o.to, before); +} + +/** + * Called with freshly stored checks: settles the pushes whose resulting commit is the PR's head and whose checks are final, + * expires old unsettled ones, and lets the breaker look at every stage that got a `broke`. + */ +export function resolvePushes(db: DatabaseSync, rows: { repo: string; number: number; head_oid: string; checks: CheckRow }[], at = new Date().toISOString()): void { + const find = db.prepare("SELECT id, stage, before_res FROM push_outcomes WHERE repo = ? AND to_oid = ? AND outcome IS NULL AND (number = ? OR number IS NULL)"); + const set = db.prepare("UPDATE push_outcomes SET number = ?, after_res = ?, outcome = ?, resolved_at = ? WHERE id = ?"); + const broke = new Set(); + for (const r of rows) { + const open = find.all(r.repo, r.head_oid, r.number) as { id: number; stage: string; before_res: string }[]; + if (!open.length) continue; + const after = requiredResult(r.checks, optionalChecks(db, r.repo)); + for (const p of open) { + const outcome = classifyPush(p.before_res as Required | "unknown", after); + if (outcome === null) continue; + set.run(r.number, after, outcome, at, p.id); + if (outcome === "broke") broke.add(p.stage); + } + } + const old = new Date(Date.parse(at) - EXPIRE_MS).toISOString(); + if (db.prepare("SELECT 1 FROM push_outcomes WHERE outcome IS NULL AND at < ? LIMIT 1").get(old)) + db.prepare("UPDATE push_outcomes SET outcome = 'unknown', resolved_at = ? WHERE outcome IS NULL AND at < ?").run(at, old); + for (const s of broke) evaluatePushBreaker(db, s as TripStage, at); +} + +/** The head the PR is at when our push to it broke a required check and nothing was pushed since, or null. */ +export function brokeHeads(db: DatabaseSync, repo?: string): Map { + const rows = db.prepare(`SELECT repo, number, to_oid FROM push_outcomes WHERE outcome = 'broke' AND number IS NOT NULL ${repo ? "AND repo = ?" : ""} ORDER BY id`).all(...(repo ? [repo] : [])) as { repo: string; number: number; to_oid: string }[]; + return new Map(rows.map((r) => [`${r.repo}#${r.number}`, r.to_oid])); +} + +// ---- circuit breaker -------------------------------------------------------------------------------------- + +type TripRow = { stage: string; active: number; reason: string; evidence: string; tripped_at: string; cleared_at: string | null; cleared_by: string | null }; +const tripRow = (db: DatabaseSync, stage: string): TripRow | undefined => db.prepare("SELECT * FROM stage_trips WHERE stage = ?").get(stage) as TripRow | undefined; + +/** Stages that are tripped now, with the reason. */ +export function activeTrips(db: DatabaseSync): Partial> { + const out: Partial> = {}; + for (const r of db.prepare("SELECT stage, reason FROM stage_trips WHERE active = 1").all() as { stage: string; reason: string }[]) out[r.stage as TripStage] = r.reason; + return out; +} + +/** Why the runner step cannot start because its stage tripped, or null. */ +export function tripReasonOfStep(db: DatabaseSync, step: string): string | null { + const stage = STEP_STAGE[step]; + const r = stage ? tripRow(db, stage) : undefined; + return r?.active ? `tripped: ${r.reason}; an operator resumes it` : null; +} + +/** Evidence of a trip, for the Pipeline page and the audit log. */ +export function tripEvidence(db: DatabaseSync, stage: string): string[] { + const r = tripRow(db, stage); + try { return r ? (JSON.parse(r.evidence) as string[]) : []; } catch { return []; } +} + +function trip(db: DatabaseSync, stage: TripStage, reason: string, evidence: string[], at: string): void { + const r = tripRow(db, stage); + if (r?.active) return; + db.prepare(`INSERT INTO stage_trips (stage, active, reason, evidence, tripped_at) VALUES (?, 1, ?, ?, ?) + ON CONFLICT (stage) DO UPDATE SET active = 1, reason = excluded.reason, evidence = excluded.evidence, tripped_at = excluded.tripped_at`) + .run(stage, reason, JSON.stringify(evidence), at); + audit(db, "pipeline", "stage-trip", stage, { reason, evidence }); +} + +const sinceOf = (db: DatabaseSync, stage: string): string => tripRow(db, stage)?.cleared_at ?? ""; + +/** Trips a push stage when BREAKER_BROKE of its last BREAKER_WINDOW pushes since the last resume broke a required check. */ +export function evaluatePushBreaker(db: DatabaseSync, stage: TripStage, at = new Date().toISOString()): void { + if (tripRow(db, stage)?.active) return; + const rows = db.prepare("SELECT outcome, repo, number, to_oid FROM push_outcomes WHERE stage = ? AND at > ? ORDER BY id DESC LIMIT 10").all(stage, sinceOf(db, stage)) as { outcome: Outcome | null; repo: string; number: number | null; to_oid: string }[]; + if (!breakerTripped(rows.map((r) => r.outcome))) return; + const bad = rows.filter((r) => r.outcome === "broke"); + trip(db, stage, `${bad.length} of the last ${rows.length} ${stage} pushes broke a required check`, bad.map((r) => `${r.repo}#${r.number}@${r.to_oid.slice(0, 8)}`), at); +} + +const weMerged = (db: DatabaseSync, repo: string, number: number): { at: string } | undefined => + db.prepare("SELECT at FROM merges WHERE repo = ? AND number = ? AND outcome = 'merged' ORDER BY at DESC LIMIT 1").get(repo, number) as { at: string } | undefined; + +/** The default branch of `repo` is red and its culprit is PR `number` (main CI): trips the merge path when we merged that PR after the last resume. */ +export function mainRedAfterMerge(db: DatabaseSync, repo: string, number: number, sha: string, at = new Date().toISOString()): void { + const m = weMerged(db, repo, number); + if (!m || m.at <= sinceOf(db, "merge")) return; + trip(db, "merge", `main CI of ${repo} is red after our merge of #${number}`, [`${repo}#${number}`, `${repo}@${sha.slice(0, 8)}`], at); +} + +/** A post-merge review of a PR we merged found defects. */ +export function mergeDefect(db: DatabaseSync, repo: string, number: number, defects: number, at = new Date().toISOString()): void { + if (defects < 1) return; + const m = weMerged(db, repo, number); + if (!m || m.at <= sinceOf(db, "merge")) return; + trip(db, "merge", `the post-merge review of ${repo}#${number} found ${defects} defect${defects === 1 ? "" : "s"}`, [`${repo}#${number}`], at); +} + +export class TripError extends Error { + status = 400; +} + +/** An operator clears a trip. Pushes and merges before this moment no longer count. */ +export function resumeStage(db: DatabaseSync, stage: string, by: string): void { + if (!(TRIP_STAGES as readonly string[]).includes(stage)) throw new TripError(`no such stage: ${stage}; stages: ${TRIP_STAGES.join(", ")}`); + const r = tripRow(db, stage); + if (!r?.active) throw new TripError(`${stage} is not paused by the circuit breaker`); + const at = new Date().toISOString(); + db.prepare("UPDATE stage_trips SET active = 0, cleared_at = ?, cleared_by = ? WHERE stage = ?").run(at, by, stage); + audit(db, by, "stage-resume", stage, { reason: r.reason }); +} diff --git a/src/review/checks.ts b/src/review/checks.ts index a95ae994..c23959cf 100644 --- a/src/review/checks.ts +++ b/src/review/checks.ts @@ -2,6 +2,7 @@ import type { DatabaseSync } from "node:sqlite"; import type { Querier } from "../mirror.ts"; import { pilotSql } from "../pilot.ts"; +import { resolvePushes } from "../push-outcomes.ts"; import { overallAt, recordRuns, type Suite } from "../merge/ci-approval.ts"; export const ORG = "storytold"; @@ -99,6 +100,7 @@ export function saveChecks(db: DatabaseSync, rows: PrChecks[], at = new Date().t for (const r of rows) ins.run(r.repo, r.number, r.head_oid, r.state, r.is_draft ? 1 : 0, r.overall, JSON.stringify(r.checks), r.mergeable, r.maintainer_can_modify ? 1 : 0, at); for (const r of rows) recordRuns(db, r, at); + resolvePushes(db, rows, at); } /** Fetches and stores the checks of the given PRs (all open PRs of the repo when none are given). */ diff --git a/src/runner/autopilot.ts b/src/runner/autopilot.ts index 75fcb697..a0e63bab 100644 --- a/src/runner/autopilot.ts +++ b/src/runner/autopilot.ts @@ -41,6 +41,8 @@ import { mainFixDue } from "../mainfix/index.ts"; import { latestRun } from "../classify/settled.ts"; import { enqueue, JobError, now, requestCancel, RUNNER_STOPPED } from "./jobs.ts"; import { claudePauseReason } from "../agents/accounts.ts"; +import { tripReasonOfStep } from "../push-outcomes.ts"; +import { STEP_STAGE } from "../core/push-outcome.ts"; import { knownStep, loadSteps, modelsOf, usesClaude, type Params, type StepDef } from "./steps.ts"; import { pilotItems, scopeRepos } from "../pilot.ts"; import { fastFirst, fastScoreOf } from "../fasttrack.ts"; @@ -591,6 +593,8 @@ const hhmm = (ms: number): string => `${new Date(ms).toISOString().slice(11, 16) /** Why the stage cannot start jobs now, or null. The one place a stage's pause is decided. A step's models are taken at their defaults. */ export function pauseReason(db: DatabaseSync, step: string, ms: number = Date.now(), o: { backoff?: boolean } = {}): string | null { const l = limitRow(db, step), used = usageToday(db, step, ms); + const tripped = tripReasonOfStep(db, step); + if (tripped) return tripped; if (l.per_day === 0) return "paused: the daily limit is 0"; if (l.per_day !== null && used >= l.per_day) return `daily limit of ${l.per_day} items reached; resumes at 00:00 UTC`; const b = o.backoff === false ? null : failureBackoff(db, step, ms); @@ -668,7 +672,7 @@ export async function stageLimits(db: DatabaseSync): Promise { const why = stageStatus(db); return LIMIT_STEPS.map((step) => { const l = limitRow(db, step); - return { step, title: steps.get(step)?.title ?? step, perDay: l.per_day, usedToday: usageToday(db, step), pausedReason: pauseReason(db, step), status: stepStatus(db, step, why[step]) }; + return { step, title: steps.get(step)?.title ?? step, perDay: l.per_day, usedToday: usageToday(db, step), pausedReason: pauseReason(db, step), tripped: tripReasonOfStep(db, step) !== null ? STEP_STAGE[step] : undefined, status: stepStatus(db, step, why[step]) }; }); } diff --git a/src/runner/index.ts b/src/runner/index.ts index 62a410e1..eff7680c 100644 --- a/src/runner/index.ts +++ b/src/runner/index.ts @@ -1,4 +1,5 @@ // autocraft runner serve | exec | enqueue | jobs | cancel | steps; autocraft pipeline on | off | status | limit +import { resumeStage, TripError } from "../push-outcomes.ts"; import { startWorkerServer } from "../build/worker-api.ts"; import { acquireLock } from "../mirror.ts"; import { connect } from "../db.ts"; @@ -110,7 +111,7 @@ function cancel(args: string[]): void { const SUB: Record Promise | void> = { serve, exec, steps, enqueue: enqueueCmd, jobs, cancel }; export const commands = { - pipeline: { summary: "pipeline switch and limits: on | off | status | limit --per-day N", run: (args: string[]) => pipeline(args) }, + pipeline: { summary: "pipeline switch and limits: on | off | status | limit --per-day N | resume ", run: (args: string[]) => pipeline(args) }, runner: { summary: "pipeline runner: serve | steps | enqueue | jobs | cancel", run: async (args: string[]) => { @@ -124,6 +125,7 @@ export const commands = { const PIPELINE_USAGE = `usage: autocraft pipeline on | off | status autocraft pipeline limit --per-day autocraft pipeline limit reset |--all + autocraft pipeline resume autocraft pipeline pilot set ... | show | clear`; // Recorded as `cli`: only someone with a shell on the host can run this. @@ -134,6 +136,15 @@ async function pipeline(args: string[]): Promise { setEnabled(db, sub === "on", "cli"); audit(db, "cli", "pipeline-switch", "pipeline", { enabled: sub === "on" }); console.log(`pipeline ${sub}`); + } else if (sub === "resume") { + if (rest.length !== 1) die(PIPELINE_USAGE); + try { + resumeStage(db, rest[0]!, "cli"); + console.log(`${rest[0]} resumed`); + } catch (e) { + if (e instanceof TripError) die(e.message); + throw e; + } } else if (sub === "limit" && rest[0] === "reset") { const target = rest[1] === "--all" ? "all" : rest[1]; if (!target || rest.length > 2) die(PIPELINE_USAGE); diff --git a/src/schema.sql b/src/schema.sql index e13a3d60..32652d57 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -1219,3 +1219,35 @@ CREATE TABLE IF NOT EXISTS item_plans ( planned_at TEXT NOT NULL, PRIMARY KEY (repo, number) ) WITHOUT ROWID; + +-- Every push of ours to a PR branch (fix-up, conflict merge, CI fix, fix-issue PR) and what it did to the PR's required checks. +-- before_res / after_res: green | red | pending | none | unknown (required checks only; optional ones are ignored). A branch created +-- by the push has no earlier head: it counts as green before. outcome stays NULL until the checks at to_oid are final; +-- then kept-green | fixed | broke | still-red | unknown. number is NULL for a fix-issue push until its PR's checks arrive. +-- stage: fixup | cifix | fixissue (the circuit breaker's stage); action: the audit action of the push. +CREATE TABLE IF NOT EXISTS push_outcomes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + at TEXT NOT NULL, + stage TEXT NOT NULL, + action TEXT NOT NULL, + repo TEXT NOT NULL, number INTEGER, + from_oid TEXT, to_oid TEXT NOT NULL, + before_res TEXT NOT NULL, + after_res TEXT, + outcome TEXT, + resolved_at TEXT +); +CREATE INDEX IF NOT EXISTS push_outcomes_to ON push_outcomes(repo, to_oid); +CREATE INDEX IF NOT EXISTS push_outcomes_stage ON push_outcomes(stage, id); + +-- Circuit breaker: a stage that stopped itself. One row per stage; active = 1 while tripped, and only an operator clears it +-- (autocraft pipeline resume , or the Resume button on the Pipeline page). Pushes and merges from before cleared_at +-- do not count towards the next trip. evidence: JSON of refs (repo#number and commits). +CREATE TABLE IF NOT EXISTS stage_trips ( + stage TEXT PRIMARY KEY, -- fixup | cifix | fixissue | merge + active INTEGER NOT NULL DEFAULT 1, + reason TEXT NOT NULL, + evidence TEXT NOT NULL, + tripped_at TEXT NOT NULL, + cleared_at TEXT, cleared_by TEXT +); diff --git a/src/stages/registry.ts b/src/stages/registry.ts index 1efa653e..ebd36eee 100644 --- a/src/stages/registry.ts +++ b/src/stages/registry.ts @@ -453,6 +453,7 @@ export const GLOBAL_WAITS: { name: string; why: string; howLong: string; showsAs { name: "Failed job", why: "Retry a real failure without hammering", howLong: "1, 2, 4, 8, 16, then 30 minutes; ends on a release, and after a single failure also on a changed input", showsAs: "\"failed N times in a row; retry at HH:MM UTC\"", kind: "backoff" }, { name: "Daily limit", why: "Cost control", howLong: "Until 00:00 UTC", showsAs: "\"daily limit of N items reached; resumes at 00:00 UTC\"", kind: "backoff" }, { name: "Jev unavailable", why: "Jev is switched off (`autocraft accounts jev off`), the `jev` command is missing, or its account fails: out of credit, or a missing or rejected key (status 401, 402, 403, or a message about credit, billing, quota or the key). Haiku does Jev's classify, priority and duplicate work through the Claude accounts. Off or not installed: no retry until it is switched on or the command exists (checked on each pass). Account failure: the first pass an hour after the last failure tries Jev again; no timer runs. Other Jev errors (timeouts, server errors, bad answers) are retried as before", howLong: "1 hour after an account failure", showsAs: "Accounts page and run logs", kind: "external" }, + { name: "Circuit breaker", why: "A push stage (fix-up, CI fix, fix issue) stops when 2 of its last 10 pushes turned a required check red; the merge path stops when main CI turns red because of a merge of ours or a post-merge review finds a defect in it", howLong: "Until an operator resumes the stage (`autocraft pipeline resume ` or the Resume button on the Pipeline page); no timer", showsAs: "\"tripped: ...\" as the stage's pause reason", kind: "external" }, { name: "Claude usage pause", why: "Account headroom", howLong: "Until usage reading recovers; re-read every minute", showsAs: "Claude pause reason", kind: "external" }, { name: "Rate limits", why: "GitHub", howLong: "Per the API's reset", showsAs: "Job log", kind: "external" }, { name: "Planner fallback", why: "Safety net; the planner normally runs on a change", howLong: "5 minutes", showsAs: "none", kind: "backoff" }, diff --git a/test/decide-pr.test.ts b/test/decide-pr.test.ts index 8f172e7c..dc833683 100644 --- a/test/decide-pr.test.ts +++ b/test/decide-pr.test.ts @@ -236,6 +236,11 @@ const rows: Row[] = [ { name: "cifix: a take-fix PR with its fix-up done is fixed", facts: { ...CI_FAIL, ...TAKE_FIX, fixup: fixup({ recorded: ["pushed"] }), cifix: cifix() }, expect: { actions: ["cifix:work"] } }, { name: "cifix: not when CI passes", facts: { cifix: cifix() }, expect: { state: "ready", actions: ["merge"] } }, + // ---- our push broke the checks: the head is the pushed one, reviewed only at the head before + { name: "broke: the CI fix works on the pushed head without a review of it", facts: { head: "pushed1", ci: "unknown", brokeByUs: true, cifix: cifix() }, expect: { actions: ["cifix:work", "review"] } }, + { name: "broke: a formatter result is collected the same way", facts: { head: "pushed1", ci: "unknown", brokeByUs: true, cifix: cifix({ states: ["formatting"], formattingTask: 7, formatterEnded: true, tries: 1 }) }, expect: { actions: ["cifix:collect", "review"] } }, + { name: "broke: without it, a pushed head waits for its review", facts: { head: "pushed1", ci: "unknown", cifix: cifix() }, expect: { actions: ["review"] } }, + // ---- post-merge review { name: "postmerge: merged by the pipeline, no review stored", facts: { ghState: "MERGED", postmerge: merged() }, expect: { state: "merged", actions: ["postmerge"] } }, { name: "postmerge: merged before the cut-off", facts: { ghState: "MERGED", postmerge: merged({ since: "2026-11-04T10:00:00.000Z" }) }, expect: { state: "merged", actions: [] } }, @@ -247,6 +252,11 @@ const rows: Row[] = [ { name: "postmerge: nothing for a closed PR the pipeline did not merge", facts: { ghState: "CLOSED", review: null }, expect: { state: "closed", actions: [] } }, ]; +test("broke: the CI fix comes first among the PR's actions", () => { + const p = decidePr(prFacts({ head: "pushed1", ci: "unknown", brokeByUs: true, cifix: cifix() })); + assert.equal(p.actions[0]?.kind, "cifix"); +}); + for (const row of rows) { test(row.name, () => { const p = decidePr(prFacts(row.facts)); diff --git a/test/guard.test.ts b/test/guard.test.ts index 3a2b5e1a..17f84a3a 100644 --- a/test/guard.test.ts +++ b/test/guard.test.ts @@ -88,6 +88,15 @@ test("gates: each action kind needs its approval", () => { assert.equal(gates(off("pushApproved"), { kind: "merge" }, OP), null); }); +test("gates: a tripped stage writes nothing, asks and other stages stay open", () => { + const f = prFacts({ tripped: { fixup: "2 of the last 10 fixup pushes broke a required check" } }); + for (const w of [{ kind: "fixup", bucket: "fix" }, { kind: "conflict", bucket: "merge" }, { kind: "lint", bucket: "fixup" }] as const) assert.match(gates(f, w, OP) ?? "", /fixup is paused: 2 of the last 10/); + assert.match(gates(f, { kind: "fixup", bucket: "fix" }, "pipeline") ?? "", /paused/); + assert.equal(gates(f, { kind: "fixup", bucket: "ask" }, OP), null); + assert.equal(gates(f, { kind: "cifix", bucket: "work" }, OP), null); + assert.match(gates(prFacts({ tripped: { merge: "main is red" } }), { kind: "merge" }, OP) ?? "", /merge is paused/); +}); + test("the merge command gets the reviewed head, and the built-in command refuses another head", async () => { const g = await guard(fresh([{ n: 1 }]), ref, MERGE, OP, live()); assert.ok(ok(g)); diff --git a/test/push-outcome.test.ts b/test/push-outcome.test.ts new file mode 100644 index 00000000..22292e1a --- /dev/null +++ b/test/push-outcome.test.ts @@ -0,0 +1,22 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { breakerTripped, classifyPush, requiredResult } from "../src/core/push-outcome.ts"; + +test("push outcome: green to red is broke, red to green is fixed, optional checks are ignored", () => { + const green = [{ name: "gate", state: "success" }, { name: "sonar", state: "failure" }]; + const red = [{ name: "gate", state: "failure" }, { name: "sonar", state: "success" }]; + const optional = ["sonar"]; + assert.equal(requiredResult(green, optional), "green"); + assert.equal(requiredResult(red, optional), "red"); + assert.equal(requiredResult([{ name: "gate", state: "pending" }], optional), "pending"); + assert.equal(classifyPush(requiredResult(green, optional), requiredResult(red, optional)), "broke"); + assert.equal(classifyPush(requiredResult(red, optional), requiredResult(green, optional)), "fixed"); + assert.equal(classifyPush("red", "red"), "still-red"); + assert.equal(classifyPush("green", "green"), "kept-green"); + assert.equal(classifyPush("unknown", "red"), "unknown"); + assert.equal(classifyPush("green", "pending"), null); + // A red optional check alone is no break. + assert.equal(classifyPush("green", requiredResult([{ name: "gate", state: "success" }, { name: "sonar", state: "failure" }], optional)), "kept-green"); + assert.equal(breakerTripped(["broke", "fixed", null, "broke"]), true); + assert.equal(breakerTripped(["broke", ...Array(9).fill("fixed"), "broke"]), false); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index c193ed90..1925a11f 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -208,6 +208,8 @@ export interface Api { setLimit(step: string, limit: { perDay: number | null }): Promise; /** Counts the stage's items today from zero again; `all` resets every stage. */ resetLimit(step: string): Promise; + /** Clears a stage the circuit breaker paused. */ + resumeTrip(stage: string): Promise; /** Limits the whole pipeline to these items ("repo#number"); an empty list clears the pilot. */ setPilot(items: string[]): Promise; }; diff --git a/web/src/api/http.ts b/web/src/api/http.ts index 8b33bee3..7992d72e 100644 --- a/web/src/api/http.ts +++ b/web/src/api/http.ts @@ -206,6 +206,7 @@ export function createHttpApi(): Api { setEnabled: (enabled) => put("/api/pipeline/state", { enabled }), setLimit: (step, limit) => put(`/api/pipeline/limits/${encodeURIComponent(step)}`, limit), resetLimit: (step) => post(`/api/pipeline/limits/${encodeURIComponent(step)}/reset`), + resumeTrip: (stage) => post(`/api/pipeline/trips/${encodeURIComponent(stage)}/resume`), setPilot: (items) => put("/api/pipeline/pilot", { items }), }, accounts: { diff --git a/web/src/api/mock/pipelineMock.ts b/web/src/api/mock/pipelineMock.ts index 32cfd298..5059b72a 100644 --- a/web/src/api/mock/pipelineMock.ts +++ b/web/src/api/mock/pipelineMock.ts @@ -91,6 +91,7 @@ export function createPipelineMock(me: User, changed: () => void): Pick= (perDay as number) ? `daily limit of ${perDay} items reached` : null, })); + Object.assign(limits.find((l) => l.step === "fixup")!, { tripped: "fixup", pausedReason: "tripped: 2 of the last 10 fixup pushes broke a required check; an operator resumes it" }); const pilot: string[] = []; const state = (): PipelineState => ({ ...flag, heartbeat: iso(0), limits, pilot: [...pilot] }); const requireOperator = () => { @@ -180,6 +181,12 @@ export function createPipelineMock(me: User, changed: () => void): Pick x.step === step); diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 8b628191..a0b2c325 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -991,6 +991,8 @@ export interface JobFilter { } export type StageLimit = { step: string; title: string; perDay: number | null; usedToday: number; pausedReason: string | null; + /** The circuit-breaker stage that paused this step (fixup, cifix, fixissue, merge); an operator resumes it. */ + tripped?: string; /** What the stage is doing when nothing pauses it: "running", "queued", or why it is not starting ("nothing to do", "waiting for CI on 3 PRs in x"). */ status?: string | null }; export type PipelineState = { enabled: boolean; changedBy: string | null; changedAt: string | null; heartbeat: string | null; limits: StageLimit[]; /** "repo#number" refs the pipeline is limited to; empty when there is no pilot. */ pilot: string[] }; diff --git a/web/src/modules/pipeline/controls.tsx b/web/src/modules/pipeline/controls.tsx index b88dc772..c60ff6bd 100644 --- a/web/src/modules/pipeline/controls.tsx +++ b/web/src/modules/pipeline/controls.tsx @@ -113,6 +113,20 @@ function ResetCount({ l }: { l: StageLimit }) { ); } +/** Operators clear a pause the circuit breaker set. */ +function ResumeTrip({ l }: { l: StageLimit }) { + const api = useApi(); + const write = useWrite(); + if (!l.tripped) return null; + const stage = l.tripped; + return ( + <> + void write.run("resume", () => api.pipeline.resumeTrip(stage))} /> + + + ); +} + function PauseBadge({ l }: { l: StageLimit }) { if (l.pausedReason) return {l.pausedReason}; return l.status ? {l.status} : null; @@ -161,6 +175,7 @@ export function StageLimitRow({ step }: { step: string }) { {operator && } + {operator && } {operator && } ); @@ -195,6 +210,7 @@ export function StageLimits() {
{l.pausedReason ? {l.pausedReason} : {l.status ?? "ready"}} + {operator && } {operator && }