Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ci): nightly watch retries transient GitHub 5xx and skips a poison historic run (6.16, GBRA-40)
time-attacka76e82c65549
diff --git a/scripts/lib/gh-issue.ts b/scripts/lib/gh-issue.tsindex 8d09039142..811e747570 100644--- a/scripts/lib/gh-issue.ts+++ b/scripts/lib/gh-issue.ts@@ -63,10 +63,29 @@ export function inertBlock(value: unknown, max = 1500): string {return s;}-/** Production client: REST with GH_TOKEN/GITHUB_TOKEN (Actions), else the authenticated `gh api` CLI (local dry runs). */-export function restClient(repo: string, token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN): GitHubClient {+/** Delays before each retry of a GET that failed with a 5xx (GitHub's transient 502/503/504); writes are never retried. */+export const GET_RETRY_DELAYS_MS = [1_000, 3_000];++async function retryingGet<T>(method: string, sleep: (ms: number) => Promise<unknown>, call: () => Promise<T>): Promise<T> {+ for (let attempt = 0; ; attempt++) {+ try {+ return await call();+ } catch (e) {+ const status = (e as { status?: number }).status ?? 0;+ if (method !== 'GET' || status < 500 || attempt >= GET_RETRY_DELAYS_MS.length) throw e;+ await sleep(GET_RETRY_DELAYS_MS[attempt]!);+ }+ }+}++/** Production client: REST with GH_TOKEN/GITHUB_TOKEN (Actions), else the authenticated `gh api` CLI (local dry runs); a GET that fails with a 5xx is retried per GET_RETRY_DELAYS_MS. */+export function restClient(repo: string, token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN, sleep: (ms: number) => Promise<unknown> = Bun.sleep): GitHubClient {const resolve = (path: string) => path.replace('{repo}', repo).replace(/^\//, '');- if (!token) return ghCliClient(resolve);+ const client = token ? tokenClient(resolve, token) : ghCliClient(resolve);+ return { ...client, request: <T>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown) => retryingGet(method, sleep, () => client.request<T>(method, path, body)) };+}++function tokenClient(resolve: (path: string) => string, token: string): GitHubClient {return {async request<T>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown): Promise<T> {const url = `https://api.github.com/${resolve(path)}`;diff --git a/scripts/lib/master-red.ts b/scripts/lib/master-red.tsindex 38e91c6294..ea3fc668e0 100644--- a/scripts/lib/master-red.ts+++ b/scripts/lib/master-red.ts@@ -376,7 +376,17 @@ export async function planMasterRed(client: GitHubClient, repo: string, run: Runif (counted.length > window.length) state.rebuilt = `${counted.length - window.length} older unevaluated run(s) were not read (more than ${MAX_FOLD} pending)`;for (const r of window) {const key = r.id * 1000 + r.run_attempt;- const ev = cache.get(key) ?? await collectEvidence(client, r, opts);+ let ev = cache.get(key);+ if (!ev) {+ try {+ ev = await collectEvidence(client, r, opts);+ } catch (e) {+ const status = (e as { status?: number }).status ?? 0;+ if (r.id === run.id || status < 500) throw e;+ console.log(`::warning::nightly-watch skipped ${r.name} run ${r.id} attempt ${r.run_attempt}: GitHub kept failing (${status}) after retries (${inert(e instanceof Error ? e.message : String(e), 200)}). It is not evaluated; the newer runs are.`);+ continue;+ }+ }cache.set(key, ev);const before = state.status;state = applyRun(state, r, ev);diff --git a/scripts/nightly-issue.ts b/scripts/nightly-issue.tsindex bf8fe0e522..1725d5e4c9 100644--- a/scripts/nightly-issue.ts+++ b/scripts/nightly-issue.ts@@ -25,7 +25,10 @@** --dry-run reads only and prints the action and the issue body it would* write. Exit 0 on any verdict; 1 when the run or the TSV cannot be read- * (the error says why and how to fix it); 2 usage error.+ * (the error says why and how to fix it); 2 usage error. A GET that fails+ * with a 5xx is retried (restClient); an older push run whose evidence still+ * fails with a 5xx is skipped with a ::warning:: naming its run id and+ * attempt, so one poison run never fails the whole watch.*/import { readFileSync } from 'node:fs';import { basename, join, resolve } from 'node:path';diff --git a/test/scripts/nightly-issue.test.ts b/test/scripts/nightly-issue.test.tsindex aa6fc3163a..944342585f 100644--- a/test/scripts/nightly-issue.test.ts+++ b/test/scripts/nightly-issue.test.ts@@ -14,7 +14,7 @@ import { load as loadYaml } from 'js-yaml';import { loadReceiptDir } from '../../scripts/ci-executed-counts.ts';import { buildManifest, checkManifest, failureSignature, junitMessages, MANIFEST_ARTIFACT, MANIFEST_SCHEMA, type CiManifest } from '../../scripts/ci-manifest.ts';import { failureSignature as gateSignature, parseExemptionBlocks } from '../fixtures/nightly-watch/stress-exemption-contract.ts';-import { inert, jsonBlock, labelNames, readJsonBlock, readZipEntry, type GitHubClient, type Issue } from '../../scripts/lib/gh-issue.ts';+import { GET_RETRY_DELAYS_MS, inert, jsonBlock, labelNames, readJsonBlock, readZipEntry, restClient, type GitHubClient, type Issue } from '../../scripts/lib/gh-issue.ts';import { FLAKE_MARKER, MR_MARKER, PUSH_ALLOWLIST, type FlakeRecord, type MasterRedState } from '../../scripts/lib/master-red.ts';import {JSON_MARKER, parseKnownRed, resolveTarget, routeRun, validateKnownRed, watch, watchRun, type IncidentRecord, type JobInfo, type KnownRow, type RunInfo,@@ -615,6 +615,64 @@ describe('master-red: push-to-master runs', () => {expect(masterIssue(blind)!.state).toBe('open');});+ test('a historic run whose jobs list keeps returning 502 is skipped with a warning; the watch evaluates the newer runs and the triggering run still fails loudly', async () => {+ const w = testWorld(T.g8315, T.r8320);+ await go(w, T.r8320);+ for (const r of [T.c8331, T.r8336, T.r8343, T.g8352]) w.addRun(r, existsSync(join(MR, `jobs-${r.id}.json`)) ? `jobs-${r.id}.json` : undefined);+ const poison = `/actions/runs/${T.r8336.id}/attempts/${T.r8336.run_attempt}/jobs`;+ w.failGet = p => p.includes(poison);+ const logs: string[] = [];+ const log = console.log;+ console.log = (...a: unknown[]) => { logs.push(a.join(' ')); };+ let r: Awaited<ReturnType<typeof go>>;+ try { r = await go(w, T.g8352); } finally { console.log = log; }+ expect(r.masterRed!.evaluated).toEqual([T.r8343.id, T.g8352.id]);+ expect(mrState(masterIssue(w)!).evaluated).toMatchObject({ run_id: T.g8352.id });+ expect(logs.filter(l => l.startsWith('::warning::'))).toEqual([expect.stringContaining(`run ${T.r8336.id} attempt ${T.r8336.run_attempt}`)]);++ const own = testWorld(T.g8315, T.r8320);+ own.failGet = p => p.includes(`/actions/runs/${T.r8320.id}/attempts/`);+ await expect(go(own, T.r8320)).rejects.toThrow('HTTP 502');+ });++ test('restClient retries a GET that returns 5xx and succeeds on a later 200; a persistent 502 throws after the bounded retries; writes are never retried', async () => {+ const real = globalThis.fetch;+ const calls: string[] = [];+ let script: number[] = [];+ globalThis.fetch = (async (url: string, init?: RequestInit) => {+ calls.push(`${init?.method ?? 'GET'} ${url}`);+ const status = script.shift() ?? 200;+ return new Response(status === 200 ? JSON.stringify({ jobs: [], total_count: 0 }) : 'bad gateway', { status });+ }) as typeof fetch;+ const slept: number[] = [];+ const client = restClient('o/r', 'token', async ms => { slept.push(ms); });+ try {+ script = [502, 200];+ expect(await client.request('GET', 'repos/{repo}/actions/runs/1/attempts/2/jobs')).toEqual({ jobs: [], total_count: 0 });+ expect(calls).toEqual(['GET https://api.github.com/repos/o/r/actions/runs/1/attempts/2/jobs', 'GET https://api.github.com/repos/o/r/actions/runs/1/attempts/2/jobs']);+ expect(slept).toEqual([GET_RETRY_DELAYS_MS[0]!]);++ calls.length = 0; slept.length = 0;+ script = [502, 502, 502, 502];+ const err = await client.request('GET', 'repos/{repo}/actions/runs/1/attempts/2/jobs').catch(e => e as { status?: number });+ expect(err.status).toBe(502);+ expect(calls).toHaveLength(GET_RETRY_DELAYS_MS.length + 1);+ expect(slept).toEqual(GET_RETRY_DELAYS_MS);++ calls.length = 0;+ script = [404];+ expect((await client.request('GET', 'repos/{repo}/actions/runs/9').catch(e => e as { status?: number })).status).toBe(404);+ expect(calls).toHaveLength(1);++ calls.length = 0;+ script = [502];+ expect((await client.request('POST', 'repos/{repo}/issues', { title: 't' }).catch(e => e as { status?: number })).status).toBe(502);+ expect(calls).toHaveLength(1);+ } finally {+ globalThis.fetch = real;+ }+ });+test('more than three failures are all listed; a database URL in run text is redacted and never reaches a reproduce command', async () => {const run: RunInfo = { ...T.r8320, id: 999001, run_number: 8321, head_sha: 'b'.repeat(40) };const w = testWorld(T.g8315, T.r8320);