From 2b183292cedae2fec871bc39fda5fd27a9c8beeb Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:21:38 +0000 Subject: [PATCH] CI-fix triage ignores the gate runner's summary line; add src/prepush lint library (fmt + clippy task, hunk filter, format fold) --- src/cifix/triage.ts | 4 +- src/prepush/index.ts | 169 +++++++++++++++++++++++++++++++++++++++++++ test/cifix.test.ts | 6 ++ test/prepush.test.ts | 22 ++++++ 4 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 src/prepush/index.ts create mode 100644 test/prepush.test.ts diff --git a/src/cifix/triage.ts b/src/cifix/triage.ts index d7fadbf8..323e7d05 100644 --- a/src/cifix/triage.ts +++ b/src/cifix/triage.ts @@ -16,6 +16,8 @@ const INFRA_CONCLUSION = new Set(["timed_out", "startup_failure", "stale"]); const INFRA_LOG = /could not resolve host|temporary failure in name resolution|connection (reset|timed out|refused)|network is unreachable|tls handshake|failed to download|unable to access 'https|spurious network error|\b50[234] (bad gateway|service unavailable|gateway time-?out)|rate limit exceeded|runner has received a shutdown signal|lost communication with the server|no space left on device|ETIMEDOUT|ECONNRESET|failed to fetch|error: failed to get `|couldn't connect to server/i; /** A compiler, clippy or test failure in the PR's code (case sensitive: `Error: Process completed` is the runner's line). */ const CODE_MARK = /^\s*error(\[E\d+\])?: |test result: FAILED|panicked at|^failures:$|could not compile|assertion `|-D warnings/m; +/** The gate runner's own summary line (`error: ci failed at \`fmt\``): it names the failed stage and says nothing about the code. */ +const GATE_SUMMARY = /^\s*error: ci failed at .*$/gm; const FORMAT_STEP = /\b(fmt|format(ting)?)\b/i; const FORMAT_DIFF = /^Diff in \S+:\d+/m; const FORMAT_DIFF_PATH = /^Diff in (\S+?):\d+/gm; @@ -38,7 +40,7 @@ export function triage(f: CiFailure): Triage { if (checks.length && checks.every((c) => INFRA_CONCLUSION.has(c.conclusion))) return { kind: "infra", why: `the run was ${checks[0]!.conclusion.replace("_", " ")}` }; const steps = checks.flatMap((c) => c.steps); if (!steps.length) return { kind: "unreadable", why: "no failure log" }; - const text = steps.map((s) => s.tail).join("\n"); + const text = steps.map((s) => s.tail).join("\n").replace(GATE_SUMMARY, ""); if (INFRA_LOG.test(text) && !CODE_MARK.test(text)) return { kind: "infra", why: "the log shows a network or runner error and no error in the code" }; const formatStep = (s: { step: string; tail: string }) => FORMAT_STEP.test(s.step) || FORMAT_DIFF.test(s.tail); // The formatter's own output does not carry compiler markers, so any marker means something besides formatting failed. diff --git a/src/prepush/index.ts b/src/prepush/index.ts new file mode 100644 index 00000000..4d002fc8 --- /dev/null +++ b/src/prepush/index.ts @@ -0,0 +1,169 @@ +// Lint before push: one build task runs rustfmt on the files a model-written Rust patch changes and clippy on the patched +// tree. The formatter's changes are folded into the patch; clippy diagnostics on lines the patch added or changed go back to the model. +import { readFileSync } from "node:fs"; +import type { DatabaseSync } from "node:sqlite"; +import type { TaskStep } from "../../web/src/api/types.ts"; +import { absolute } from "../build/artifacts.ts"; +import { createTask, getTask, warmKeyOf, type Warm } from "../build/tasks.ts"; +import { FORMAT_ARTIFACT, FORMAT_SCRIPT, gitFormatDiff } from "../cifix/index.ts"; +import { formattingOnly } from "../cifix/guard.ts"; +import { rustPlan } from "../worker/rust.ts"; + +export const CLIPPY_ARTIFACT = "clippy.txt"; +export const CLIPPY_ERR_ARTIFACT = "clippy-err.txt"; +/** The most files one formatter step names. */ +export const LINT_FILES_MAX = 40; +/** Characters of one diagnostic's rendered text kept for the model. */ +const RENDERED_CAP = 2000; + +// The step ends in `true`: clippy exits non-zero on findings, and the artifacts must come back either way. +const CLIPPY_SCRIPT = `cargo clippy --offline --locked --workspace --all-targets --message-format=json -- -D warnings > /out/${CLIPPY_ARTIFACT} 2> /out/${CLIPPY_ERR_ARTIFACT}; true`; + +/** The paths of the patch's `.rs` files, new side (deleted files excluded). */ +export function changedRsFiles(patch: string): string[] { + return [...new Set(patchLines(patch).keys())].filter((p) => p.endsWith(".rs")); +} + +/** Fetch, rustfmt on the named files (diff artifact), clippy (JSON artifact). null when the patch changes no `.rs` file. */ +export function lintPlan(changedRs: string[]): TaskStep[] | null { + const files = [...new Set(changedRs.filter((f) => f.endsWith(".rs")))]; + if (!files.length) return null; + if (files.length > LINT_FILES_MAX) files.length = LINT_FILES_MAX; + const [fetch] = rustPlan({ test: false }); + return [ + fetch!, + { name: "format", cmd: ["sh", "-c", FORMAT_SCRIPT, "format", ...files], network: "none", timeoutSec: 600, artifacts: [FORMAT_ARTIFACT] }, + { name: "clippy", cmd: ["sh", "-c", CLIPPY_SCRIPT], network: "none", timeoutSec: 3600, artifacts: [CLIPPY_ARTIFACT, CLIPPY_ERR_ARTIFACT] }, + ]; +} + +export type LintJob = { + /** The pipeline step that queues it (fixup, cifix, fixissue). */ + step: string; repo: string; number: number | null; head: string; base: string | null; + /** The model's patch, applied to the checkout before the plan runs. */ + patch: string; + /** Default: the repo's key, role `use`, as the fix-issue rounds do. */ + warm?: Warm; +}; + +/** Queues the lint task for the patch; null when it changes no `.rs` file. */ +export function queueLint(db: DatabaseSync, j: LintJob): number | null { + const plan = lintPlan(changedRsFiles(j.patch)); + if (!plan) return null; + return createTask(db, { + step: j.step, repo: j.repo, number: j.number, headSha: j.head, baseSha: j.base ?? j.head, requires: { os: "linux", toolchains: ["rust-stable"] }, + warm: j.warm ?? { key: warmKeyOf(j.repo), role: "use" }, plan, patch: j.patch, + }); +} + +export type Finding = { level: "warning" | "error"; code: string | null; message: string; file: string; line: number; rendered: string }; +export type LintRead = { kind: "pending" } | { kind: "infra-failed"; reason: string } | { kind: "result"; formatDiff: string | null; findings: Finding[] }; + +/** Lines each file's patch adds or changes, by new-side line number. */ +export function patchLines(patch: string): Map> { + const out = new Map>(); + let set: Set | null = null, at = 0; + for (const l of patch.split("\n")) { + const f = /^\+\+\+ (?:b\/)?(\S+)/.exec(l); + if (f) { set = f[1] === "/dev/null" ? null : (out.get(f[1]!) ?? out.set(f[1]!, new Set()).get(f[1]!)!); continue; } + const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(l); + if (h) { at = Number(h[1]); continue; } + if (!set || l.startsWith("--- ") || l.startsWith("diff ") || l.startsWith("\\")) continue; + if (l.startsWith("+")) set.add(at++); + else if (l.startsWith(" ")) at++; + } + return out; +} + +type Span = { file_name: string; line_start: number; line_end: number; is_primary: boolean }; +type Message = { level?: string; message?: string; code?: { code?: string } | null; spans?: Span[]; rendered?: string }; + +const trimRendered = (s: string): string => s.trim().slice(0, RENDERED_CAP); + +/** + * The diagnostics of clippy's JSON lines that belong to the patch: a primary span touching an added line, or a compile + * error (no lint code) anywhere, since the patch broke the build. A failed build with no diagnostic at all is one finding + * made of cargo's own output. + */ +export function findingsOf(jsonLines: string, stderr: string, patch: string): Finding[] { + const lines = patchLines(patch); + const touched = (file: string, a: number, b: number): boolean => { + for (const [p, set] of lines) if (p === file || file.endsWith(`/${p}`) || p.endsWith(`/${file}`)) for (let n = a; n <= b; n++) if (set.has(n)) return true; + return false; + }; + const out: Finding[] = []; + let finished: boolean | null = null, diagnostics = 0; + for (const raw of jsonLines.split("\n")) { + if (!raw.startsWith("{")) continue; + let o: { reason?: string; success?: boolean; message?: Message }; + try { o = JSON.parse(raw); } catch { continue; } + if (o.reason === "build-finished") finished = o.success === true; + if (o.reason !== "compiler-message" || !o.message) continue; + const m = o.message; + if (m.level !== "warning" && m.level !== "error") continue; + const span = m.spans?.find((s) => s.is_primary); + if (!span) continue; + diagnostics++; + const code = m.code?.code ?? null; + const compileError = m.level === "error" && !(code ?? "").startsWith("clippy::"); + if (!compileError && !touched(span.file_name, span.line_start, span.line_end)) continue; + out.push({ level: m.level, code, message: m.message ?? "", file: span.file_name, line: span.line_start, rendered: trimRendered(m.rendered ?? m.message ?? "") }); + } + if (!out.length && !diagnostics && finished !== true) { + const text = trimRendered(stderr) || "cargo clippy failed without output"; + out.push({ level: "error", code: null, message: "cargo clippy failed", file: "", line: 0, rendered: text }); + } + return out; +} + +const artifactText = (db: DatabaseSync, taskId: number, name: string): string | null => { + const row = db.prepare("SELECT file FROM build_artifacts WHERE task_id = ? AND name = ?").get(taskId, name) as { file: string } | undefined; + const path = row ? absolute(row.file) : null; + return path ? readFileSync(path, "utf8") : null; +}; + +/** The lint task's state, and once it is done the formatter diff (git format) and the findings on the patch's own lines. */ +export function readLint(db: DatabaseSync, taskId: number): LintRead { + const t = getTask(db, taskId); + if (!t) return { kind: "infra-failed", reason: "the lint task is gone" }; + if (t.state === "queued" || t.state === "claimed" || t.state === "running") return { kind: "pending" }; + if (t.state !== "done") return { kind: "infra-failed", reason: `the lint task ${t.state}${t.summary ? `: ${t.summary.slice(0, 200)}` : ""}` }; + const patch = (db.prepare("SELECT patch FROM build_tasks WHERE id = ?").get(taskId) as { patch: string | null } | undefined)?.patch ?? ""; + const fmt = artifactText(db, taskId, FORMAT_ARTIFACT); + const clippy = artifactText(db, taskId, CLIPPY_ARTIFACT); + if (clippy === null) return { kind: "infra-failed", reason: "the lint task returned no clippy output" }; + return { kind: "result", formatDiff: fmt && fmt.trim() ? gitFormatDiff(fmt) : null, findings: findingsOf(clippy, artifactText(db, taskId, CLIPPY_ERR_ARTIFACT) ?? "", patch) }; +} + +export type Fold = { ok: true; patch: string } | { ok: false; reason: string }; + +/** The two sides of a file's diff, hunk bodies only, joined: enough to compare their token streams. */ +function sides(diff: string): Map { + const out = new Map(); + let cur: { before: string[]; after: string[] } | null = null, inHunk = false; + for (const l of diff.split("\n")) { + const f = /^diff --git a\/(\S+) b\/\S+$/.exec(l); + if (f) { cur = { before: [], after: [] }; out.set(f[1]!, cur); inHunk = false; continue; } + if (l.startsWith("@@")) { inHunk = true; cur?.before.push(""); cur?.after.push(""); continue; } + if (!cur || !inHunk || l.startsWith("\\")) continue; + if (l.startsWith("-")) cur.before.push(l.slice(1)); + else if (l.startsWith("+")) cur.after.push(l.slice(1)); + else if (l.startsWith(" ")) { cur.before.push(l.slice(1)); cur.after.push(l.slice(1)); } + } + return out; +} + +/** + * The patch followed by the formatter's diff, which `git apply` applies in order to the same files. Refused unless every + * file's formatter changes are whitespace-only (by tokens), whatever produced the diff. + */ +export function foldFormat(patch: string, formatDiff: string): Fold { + if (!formatDiff.trim()) return { ok: true, patch }; + const allowed = new Set(changedRsFiles(patch)); + for (const [path, s] of sides(formatDiff)) { + if (!allowed.has(path)) return { ok: false, reason: `the formatter changed ${path}, which the patch does not change` }; + const why = formattingOnly(path, s.before.join("\n"), s.after.join("\n")); + if (why) return { ok: false, reason: why }; + } + return { ok: true, patch: `${patch.replace(/\n*$/, "\n")}${formatDiff.replace(/\n*$/, "\n")}` }; +} diff --git a/test/cifix.test.ts b/test/cifix.test.ts index 20fffeb4..2bb37255 100644 --- a/test/cifix.test.ts +++ b/test/cifix.test.ts @@ -74,6 +74,12 @@ describe("triage", () => { assert.equal(triage(failure("failure", [step("lint", "cargo clippy", "error: this could be `x` (clippy::needless)\n")])).kind, "code"); }); + test("the gate runner's `error: ci failed at` line is not a compiler error", () => { + const log = "Diff in /w/src/lib.rs:1:\n-fn a() {}\n+fn a() { }\nerror: ci failed at `fmt`\n"; + assert.equal(triage(failure("failure", [step("gate", "Run cargo xtask ci", log)])).kind, "format"); + assert.equal(triage(failure("failure", [step("gate", "Run cargo xtask ci", "error: ci failed at `clippy`\n")])).kind, "code"); + }); + test("a timed out run, or a network error without a code error, is infra; infra is tested before format", () => { assert.equal(triage(failure("failure", [step("fmt", "Check formatting", "Diff in /w/src/lib.rs:1:\nCould not resolve host: x\n")])).kind, "infra"); diff --git a/test/prepush.test.ts b/test/prepush.test.ts new file mode 100644 index 00000000..4651aa71 --- /dev/null +++ b/test/prepush.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import { describe, test } from "node:test"; +import { findingsOf, foldFormat } from "../src/prepush/index.ts"; + +const PATCH = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1,3 +1,4 @@\n fn a() {}\n fn b() {}\n+fn c(){ }\n fn d() {}\n"; +const diag = (line: number) => JSON.stringify({ reason: "compiler-message", message: { level: "warning", message: "needless", code: { code: "clippy::needless_return" }, spans: [{ file_name: "src/lib.rs", line_start: line, line_end: line, is_primary: true }], rendered: "warning: needless\n" } }); + +describe("prepush", () => { + test("a clippy diagnostic counts only on a line the patch added", () => { + const f = findingsOf(`${diag(1)}\n${diag(3)}\n{"reason":"build-finished","success":true}\n`, "", PATCH); + assert.deepEqual(f.map((x) => [x.file, x.line, x.code]), [["src/lib.rs", 3, "clippy::needless_return"]]); + }); + + test("a failed build without diagnostics is one finding; a formatter diff folds in only when it is whitespace", () => { + assert.equal(findingsOf("", "error: could not find Cargo.toml", PATCH)[0]!.rendered, "error: could not find Cargo.toml"); + const fmt = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -2,3 +2,3 @@\n fn b() {}\n-fn c(){ }\n+fn c() {}\n fn d() {}\n"; + const ok = foldFormat(PATCH, fmt); + assert.ok(ok.ok && ok.patch === PATCH + fmt); + const bad = foldFormat(PATCH, fmt.replace("+fn c() {}", "+fn e() {}")); + assert.ok(!bad.ok); + }); +});