Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
nightly-watch: cancelled jobs are not run
garrytanb478cf2e02d4
diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 0aaf88c3ae..b136fcbdc5 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/lib/gh-issue.ts` — the GitHub seam shared by the CI watchers. `inert()` makes run-derived text (job, step and test names, error text) safe to show an agent: control characters stripped, length capped, backticks and pipes replaced, mentions and links neutralized; `redactCredentials()` strips user:password from database URLs. `GitHubClient` is the one interface the watchers call (`restClient()` uses `GH_TOKEN`/`GITHUB_TOKEN` in Actions or the authenticated `gh api` locally; `download()` reads artifact archives without forwarding the token to blob storage). `findIssueByTitle` finds an issue by label and exact title, open first, else the most recently updated closed one; `listLabeled`, `getIssue` and `linkedPulls` (PRs cross-referencing an issue) back master-red and CI health; `fetchArtifactJson` + `readZipEntry` read one JSON file from a run artifact and return a reason instead of throwing.- `.github/workflows/ci-health.yml` + `scripts/ci-health-report.ts` — CI health report. Reads one window (`--days`, default 7, or `--since/--until`, also dispatch inputs) of same-repository pull-request and push-to-master runs of test.yml and e2e.yml (runs, jobs, check-run annotations, issues; never logs, fork runs or fork artifacts), paging the whole window (`listRuns` splits a query over the 1000-result search cap). It reports first-attempt pass rates (`firstAttempt()`), the exit criteria (master >= 95%, PR >= 90%; met, missed or indeterminate when the window cannot be read in full), stress-gate failures, failure classes, cancellation and completion coverage, master-red time to first response, the nightly-watch residual, the test files with the most failure annotations, shard spread and the count of fork runs it did not read; an explicit window with a missed target opens a follow-up issue. Tests: `test/scripts/ci-health-report.test.ts`. Docs: `docs/ci-red-runbook.md#ci-health-report`.- `scripts/lib/master-red.ts` — master-red reconciliation for push-to-master runs of Test and E2E Tests (`PUSH_ALLOWLIST`). Each watch evaluates every completed push run above the high-water mark (`evaluated`: run number, then attempt) stored in the newest `Master red: <workflow>` issue's `master-red:json` block (`applyRun` folds runs; cancelled runs change nothing); a missing or malformed block is rebuilt from the actions API (`pendingRuns`). It opens on red with the suspect range (`suspectRange`: compare plus commit-to-PR lookups), updates while red, closes when every previously failing job (E2E Tests: every failing file, from the manifest) ran and passed with complete evidence, records an incident that opened and closed between watches, and keeps a not-run-since failure open with the manual-close step. `externalPass` lets a scheduled run or an issue-bound E2E replay clear failures. Closing without a merged linked repair PR opens `flake` issues (`flakeFor`, `flake:json`); `closeFlakes` closes one after its repair PR merged and a later complete run passed its file and arm. Writes re-read the issue first and re-plan when it moved; a create race closes the newer duplicate. Tests: `test/scripts/nightly-issue.test.ts`. Docs: `docs/ci-red-runbook.md`.-- `scripts/lib/ci-run.ts` — one run's failure evidence (`collectEvidence`): jobs, failing jobs' annotations and, for test.yml and e2e.yml, the `ci-manifest` artifact, returned as structured records (job, step, every failing test file and identity) apart from sanitized excerpts, with `complete`/`problems` (an unreadable page, annotation or manifest is incomplete evidence, never zero failures). `reproduceCommand` builds `bun run test:stress <file> --iterations 10 [--postgres]` from a validated test path only.+- `scripts/lib/ci-run.ts` — one run's failure evidence (`collectEvidence`): jobs, failing jobs' annotations and, for test.yml and e2e.yml, the `ci-manifest` artifact, returned as structured records (job, step, every failing test file and identity) apart from sanitized excerpts; a cancelled job is not run (listed in `cancelled`) unless its annotation says it timed out, and a red run whose only failures are aggregators of cancelled jobs is `ignored`; with `complete`/`problems` (an unreadable page, annotation or manifest is incomplete evidence, never zero failures). `reproduceCommand` builds `bun run test:stress <file> --iterations 10 [--postgres]` from a validated test path only.- `scripts/ci-manifest.ts` — the versioned failure and execution manifest (`gbrain-ci-manifest/v1`). The `executed-receipts` job of test.yml and e2e.yml builds it from every lane's receipts (via `scripts/ci-executed-counts.ts`, declared skips from the expected-deltas TSV), binds it to the workflow, event, SHA, run id and attempt, and uploads it as `ci-manifest`; `checkManifest` refuses a manifest for another run or attempt; `passedFiles` lists files that executed tests and failed none. Docs: `docs/ci-red-runbook.md#ci-failure-manifest`.- `scripts/release-gate.ts` — release.yml's `ci-gate` job. Polls the push-to-master runs of Test and E2E Tests on the release commit and writes `publish`/`sha`: both green publishes; a failed run publishes nothing and fails with the next step; a run cancelled by a newer push is followed to the next master commit with the same VERSION (published there) or marks the version superseded; non-master refs are refused; it fails with the backfill command after 110 minutes. Build, release, `latest-stable` and the publish jobs use the gated commit. Tests: `test/scripts/release-gate.test.ts`. Docs: `docs/RELEASING.md#release-ci-gate`.- `scripts/regen-all.ts` — one entry point for every generated artifact (`ARTIFACTS`: regen and check command per artifact). `bun run regen:all` regenerates offline and keyless (provider keys and database URLs removed) and lists what changed; a second run changes nothing. `--check` is read-only and runs in `verify` as `check:regen-all`; `--goldens` also regenerates the offline contract goldens. Postgres goldens are named with their own commands, and `llms.txt` regenerates last because it inlines other generated docs. Tests: `test/scripts/regen-all.test.ts`.diff --git a/docs/ci-red-runbook.md b/docs/ci-red-runbook.mdindex 2130d307ad..80e804cf14 100644--- a/docs/ci-red-runbook.md+++ b/docs/ci-red-runbook.md@@ -33,6 +33,11 @@ response: a repair PR whose body says `Fixes #<issue>`.re-run is a newer attempt; a run cancelled by a newer push changes nothing.The first watch for a workflow with no master-red issue yet opens only anincident that is still red.+- **Cancelled jobs are not run:** a job cancelled with its run (a newer push,+ a user, fail-fast) neither fails nor clears anything, in master-red and+ nightly-red alike. A run whose only failures are aggregators of cancelled+ jobs changes no state. A cancelled job whose annotation says it exceeded its+ timeout is a timed-out failure.- **Missing or malformed JSON block:** the state is rebuilt from the actions APIby folding from the last green run before the newest red one. The body saysso. If the API cannot be read, the watch fails and writes nothing.diff --git a/scripts/lib/ci-run.ts b/scripts/lib/ci-run.tsindex 7d1a0e02b1..a9afec06bf 100644--- a/scripts/lib/ci-run.ts+++ b/scripts/lib/ci-run.ts@@ -3,7 +3,9 @@* and master-red watchers (scripts/nightly-issue.ts, scripts/lib/master-red.ts).** `collectEvidence` reads the run's jobs, the failing jobs' check-run- * annotations and, for workflows that upload it, the `ci-manifest` artifact+ * annotations (a cancelled job is not run unless its annotation says it hit+ * timeout-minutes; a red run whose only failures are aggregators of cancelled+ * jobs is ignored, changing no state) and, for workflows that upload it, the `ci-manifest` artifact* (scripts/ci-manifest.ts). It returns structured failure records (job, step,* every failing test file and test identity) kept apart from sanitized error* excerpts, plus `complete` and `problems`: a jobs page, annotation or@@ -46,7 +48,10 @@ export interface FailedTest { file: string; test: string; lane: string; arm: strexport interface FailedJob { job: string; job_id: number; step: string; conclusion: string; files: string[]; excerpt: string[]; owner_signal: boolean }export interface RunEvidence {verdict: 'red' | 'green' | 'ignored';+ /** Jobs as evaluated: a cancelled job GitHub stamped as timed out reads `timed_out`. */jobs: JobInfo[];+ /** Jobs cancelled with their run, by a user or by fail-fast: not run, so they neither fail nor clear anything. */+ cancelled: string[];annotations: Record<number, Annotation[]>;failed: FailedJob[];succeeded: string[];@@ -58,7 +63,9 @@ export interface RunEvidence {problems: string[];}-export const FAILING = new Set(['failure', 'timed_out', 'cancelled', 'startup_failure']);+/** Job conclusions that are failures. A cancelled job is not run (see `collectEvidence`), unless GitHub stamped it as timed out. */+export const FAILING = new Set(['failure', 'timed_out', 'startup_failure']);+export const TIMED_OUT_ANNOTATION = /has exceeded the maximum execution time/;export const RED_CONCLUSIONS = new Set(['failure', 'timed_out', 'startup_failure']);export const AGGREGATORS = new Set(['test-status', 'e2e-status']);export const MANIFEST_WORKFLOWS = new Set(['test.yml', 'e2e.yml']);@@ -120,22 +127,32 @@ export interface EvidenceOptions { manifest?: (run: RunInfo) => Promise<{ value?export async function collectEvidence(client: GitHubClient, run: RunInfo, opts: EvidenceOptions = {}): Promise<RunEvidence> {const problems: string[] = [];- const { jobs, complete: jobsComplete } = await pagedJobs(client, run);- if (!jobsComplete) problems.push(`the jobs list of run ${run.id} was truncated`);- const failing = jobs.filter(j => FAILING.has(j.conclusion ?? ''));- const shown = failing.some(j => !AGGREGATORS.has(j.name)) ? failing.filter(j => !AGGREGATORS.has(j.name)) : failing;- const failed: FailedJob[] = [];+ const listed = await pagedJobs(client, run);+ if (!listed.complete) problems.push(`the jobs list of run ${run.id} was truncated`);const byJob: Record<number, Annotation[]> = {};- for (const job of shown) {- let annotations: Annotation[] = [];+ const read = async (job: JobInfo) => {+ if (byJob[job.id]) return byJob[job.id]!;try {- annotations = await client.request<Annotation[]>('GET', `repos/{repo}/check-runs/${job.id}/annotations?per_page=50`);+ byJob[job.id] = await client.request<Annotation[]>('GET', `repos/{repo}/check-runs/${job.id}/annotations?per_page=50`);} catch (e) {problems.push(`annotations of job '${inert(job.name)}' could not be read (${inert(e instanceof Error ? e.message : String(e), 120)})`);+ byJob[job.id] = [];}- byJob[job.id] = annotations;- failed.push(failedJobRecord(job, annotations));+ return byJob[job.id]!;+ };+ const cancelled: string[] = [];+ const jobs: JobInfo[] = [];+ for (const job of listed.jobs) {+ if (job.conclusion !== 'cancelled') { jobs.push(job); continue; }+ const timedOut = (await read(job)).some(a => TIMED_OUT_ANNOTATION.test(a.message));+ if (timedOut) jobs.push({ ...job, conclusion: 'timed_out' });+ else { jobs.push(job); cancelled.push(inert(job.name)); }}+ const failing = jobs.filter(j => FAILING.has(j.conclusion ?? ''));+ const real = failing.filter(j => !AGGREGATORS.has(j.name));+ const shown = real.length ? real : cancelled.length ? [] : failing;+ const failed: FailedJob[] = [];+ for (const job of shown) failed.push(failedJobRecord(job, await read(job)));const tests: FailedTest[] = [];let passed: string[] = [];let manifestState: RunEvidence['manifest'] = 'not-expected';@@ -163,9 +180,11 @@ export async function collectEvidence(client: GitHubClient, run: RunInfo, opts:}}const files = [...new Set([...tests.map(t => t.file), ...failed.flatMap(j => j.files)])].sort();+ const verdict = verdictOf(run.conclusion) === 'red' && !failed.length && cancelled.length ? 'ignored' : verdictOf(run.conclusion);return {- verdict: verdictOf(run.conclusion),+ verdict,jobs,+ cancelled,annotations: byJob,failed,succeeded: jobs.filter(j => j.conclusion === 'success').map(j => inert(j.name)),diff --git a/scripts/lib/master-red.ts b/scripts/lib/master-red.tsindex 6d81925e5b..ecdf46f982 100644--- a/scripts/lib/master-red.ts+++ b/scripts/lib/master-red.ts@@ -142,6 +142,7 @@ export function applyRun(prev: MasterRedState, run: RunInfo, ev: RunEvidence): Mconst state: MasterRedState = structuredClone(prev);const ref = refOf(run);state.evaluated = ref;+ if (ev.verdict === 'ignored') return state;state.evidence = { run_id: run.id, complete: ev.complete, problems: ev.problems };if (ev.verdict === 'red') {if (state.status !== 'red') {diff --git a/scripts/nightly-issue.ts b/scripts/nightly-issue.tsindex 0895fb6024..8ce4015fe5 100644--- a/scripts/nightly-issue.ts+++ b/scripts/nightly-issue.ts@@ -326,6 +326,10 @@ export async function watchRun(opts: WatchOptions): Promise<WatchResult> {throw new Error(`run ${run.id} is a ${run.event} run; the nightly-red path only tracks scheduled runs. Fix: pass a scheduled run id, or add --dry-run to preview.`);}const evidence = await collectEvidence(client, run, opts);+ if (run.event === 'schedule' && (run.conclusion === 'cancelled' || evidence.verdict === 'ignored')) {+ const plan: Plan = { action: 'none', title: `Nightly red: ${inert(run.name, 100)}`, labels: [], reason: 'run or its failing lanes were cancelled (not run); no state change' };+ return { plan, assessment: { state: 'green', failures: [], unmatched: [], matched: [], stale: [], reviewPassed: [] }, run, evidence, flakesClosed: [] };+ }const assessment = assessRun(run, evidence.jobs, evidence.annotations, opts.rows, opts.today);const greens = await client.request<{ workflow_runs: Array<{ head_sha: string }> }>('GET',`repos/{repo}/actions/workflows/${run.workflow_id}/runs?event=schedule&status=success&per_page=1`).catch(() => ({ workflow_runs: [] }));diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 0b5a63fd7d..2fa50dec93 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -278,6 +278,7 @@ test/scripts/heavy-door-workflow.test.ts heavy door supply chain and coverage gatest/scripts/native-lock-prebuilds.test.ts native lock distribution integrity 2 readFileSynctest/scripts/nightly-e2e.test.ts nightly E2E scheduling 4 readFileSynctest/scripts/nightly-issue.test.ts .github/nightly-known-red.tsv 2 readFileSync+test/scripts/nightly-issue.test.ts master-red: push-to-master runs 19 readFileSynctest/scripts/nightly-issue.test.ts nightly-watch coverage ratchet 1 readFileSynctest/scripts/nightly-issue.test.ts nightly-watch incidents 9 readFileSynctest/scripts/nightly-issue.test.ts nightly-watch routing and guard 9 readFileSyncdiff --git a/test/scripts/nightly-issue.test.ts b/test/scripts/nightly-issue.test.tsindex cc844147cc..131685e660 100644--- a/test/scripts/nightly-issue.test.ts+++ b/test/scripts/nightly-issue.test.ts@@ -503,6 +503,73 @@ describe('master-red: push-to-master runs', () => {expect(issue.comments.at(-1)).toContain('has not run and passed since it failed');});+ test('cancelled jobs are not run: a concurrency or user cancel changes no state and never clears a failure; a timed-out cancel is a failure', async () => {+ const cancelNote = (id: number, message: string) => [{ annotation_level: 'failure', message }].map(a => ({ ...a, id }));+ const w = testWorld(T.g8315, T.r8320);+ await go(w, T.r8320);+ const failing = 'persistence-validation / Unit-lane PostgreSQL arms 2/2 / Bun 1.4.0';++ const onlyCancelled: RunInfo = { ...T.r8320, id: 999101, run_number: 8321, head_sha: 'd'.repeat(40) };+ w.runs.set(onlyCancelled.id, onlyCancelled);+ w.jobs.set(`${onlyCancelled.id}/1`, { total_count: 3, jobs: [+ { id: 7001, name: failing, conclusion: 'cancelled', steps: [] },+ { id: 7002, name: 'coverage-full-e2e (1)', conclusion: 'cancelled', steps: [] },+ { id: 7003, name: 'test-status', conclusion: 'failure', steps: [] },+ ] });+ w.annotations.set(7001, cancelNote(7001, 'Canceling since a higher priority waiting request for Test-refs/heads/master exists'));+ w.annotations.set(7002, cancelNote(7002, 'The run was canceled by @someone.'));+ w.manifests.set(`${onlyCancelled.id}/1`, completeManifest(onlyCancelled));+ const before = mrState(masterIssue(w)!);+ const r1 = await go(w, onlyCancelled);+ const after = mrState(masterIssue(w)!);+ expect(r1.masterRed!.evidence!.verdict).toBe('ignored');+ expect(r1.masterRed!.evidence!.cancelled).toEqual([failing, 'coverage-full-e2e (1)']);+ expect(after.open_jobs).toEqual(before.open_jobs);+ expect(after.latest_red).toEqual(before.latest_red);+ expect(after.evaluated!.run_id).toBe(onlyCancelled.id);+ expect(masterIssue(w)!.comments).toEqual([]);++ const green: RunInfo = { ...T.g8352 };+ w.addRun(green, `jobs-${green.id}.json`);+ const jobs = w.jobs.get(`${green.id}/1`)!;+ const cancelledId = jobs.jobs.find(j => j.name === failing)!.id;+ w.jobs.set(`${green.id}/1`, { ...jobs, jobs: jobs.jobs.map(j => (j.name === failing ? { ...j, conclusion: 'cancelled' } : j)) });+ w.annotations.set(cancelledId, cancelNote(cancelledId, 'The run was canceled by @someone.'));+ const r2 = await go(w, green);+ expect(r2.masterRed!.action).toBe('update');+ expect(masterIssue(w)!.state).toBe('open');+ expect(mrState(masterIssue(w)!).blocked).toEqual([failing]);++ const timedOut: RunInfo = { ...T.r8320, id: 999102, run_number: 8360, head_sha: 'e'.repeat(40) };+ w.runs.set(timedOut.id, timedOut);+ w.jobs.set(`${timedOut.id}/1`, { total_count: 2, jobs: [{ id: 7101, name: 'test (4)', conclusion: 'cancelled', steps: [] }, { id: 7102, name: 'test-status', conclusion: 'failure', steps: [] }] });+ w.annotations.set(7101, cancelNote(7101, 'The job running on runner ubicloud-x has exceeded the maximum execution time of 30 minutes.'));+ w.manifests.set(`${timedOut.id}/1`, completeManifest(timedOut));+ const r3 = await go(w, timedOut);+ expect(r3.masterRed!.evidence!.verdict).toBe('red');+ expect(mrState(masterIssue(w)!).open_jobs.find(j => j.job === 'test (4)')!.conclusion).toBe('timed_out');+ });++ test('nightly-red: a cancelled job is not a failure, and a previously failing job that was cancelled keeps the incident open', async () => {+ const h = heavy();+ const cancelledAll = h.jobs.jobs.map(j => (j.conclusion === 'failure' ? { ...j, conclusion: 'cancelled' } : j));+ const notes = Object.fromEntries(cancelledAll.filter(j => j.conclusion === 'cancelled').map(j => [j.id, [{ annotation_level: 'failure', message: 'Canceling since a higher priority waiting request for Heavy Tests-refs/heads/master exists' }]]));+ const quiet = fakeClient({ ...h, jobs: { ...h.jobs, jobs: cancelledAll }, annotations: notes });+ const r = await watchRun({ client: quiet.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });+ expect(r.assessment.failures).toEqual([]);+ expect(r.evidence.cancelled.length).toBeGreaterThan(0);+ expect(quiet.calls.some(c => c.method === 'POST' && c.path === 'repos/{repo}/issues')).toBe(false);++ const green = { run: load<RunInfo>('run-macos-green.json'), jobs: load<{ jobs: JobInfo[]; total_count: number }>('jobs-macos-green.json') };+ const target = green.jobs.jobs[0]!;+ const open = fakeClient({ ...green, jobs: { ...green.jobs, jobs: green.jobs.jobs.map(j => (j.id === target.id ? { ...j, conclusion: 'cancelled' } : j)) },+ annotations: { [target.id]: [{ annotation_level: 'failure', message: 'The run was canceled by @someone.' }] },+ issues: [{ ...issueWith('open', { failing: [{ job: target.name, job_id: 1, step: 's', errors: [] }] }), title: 'Nightly red: macOS 26 validation' }] });+ const kept = await watchRun({ client: open.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });+ expect(kept.plan.action).toBe('none');+ expect(open.calls.some(c => c.method === 'PATCH')).toBe(false);+ });+test('incomplete evidence (unreadable manifest or annotations) never closes and is reported, never read as zero failures', async () => {const w = testWorld(T.g8315, T.r8320);await go(w, T.r8320);