diff --git a/changelog.d/pregate-ci-reuse-unions-green-runs.md b/changelog.d/pregate-ci-reuse-unions-green-runs.md new file mode 100644 index 000000000..22cd46d63 --- /dev/null +++ b/changelog.d/pregate-ci-reuse-unions-green-runs.md @@ -0,0 +1 @@ +**`gstack-pregate` now reuses every green CI run at your exact code, not just the first one it checks.** When a repository declares several run profiles (a Test run and an E2E run, say), each verified run at HEAD's tree counts, so files the second run already passed no longer run again on your machine; a red run, or one that tested other code, still counts for nothing. docs/pregate.md#ci-carry (GST-3381) diff --git a/docs/pregate.md b/docs/pregate.md index bd6c297b1..83f3ddbca 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -1182,15 +1182,20 @@ already passed at this tree ([guard carry](#guard-carry)). **The tests stage.** Without `--from-run`, when the base branch declares `run_profiles`, `gstack-pregate` looks up the newest verified run at HEAD under -the profiles `--from-run` would use and applies it as `--from-run` does: the -selected local files its `tree.json` lists count as passed, and only the rest -run. On a small machine a selection the run covers records no remote gate -obligation. It prints `CI_CARRY: accepted ` or `CI_CARRY: none -()` on stderr; `--no-ci-carry` skips the lookup. +each profile `--from-run` would use and applies them as `--from-run` does: the +selected local files any of their `tree.json` files lists count as passed, and +only the rest run. So a green E2E run beside the Test run at the same tree +shortens the remainder too; a profile whose run is red, missing or on another +tree adds nothing. On a small machine a selection the runs cover records no +remote gate obligation. It prints `CI_CARRY: accepted + …` +(one receipt per carried run) or `CI_CARRY: none ()` on stderr; +`--no-ci-carry` skips the lookup. When files are left over, the remote gate obligation still clears from the -same run when the base declares `remote_gate_runs` naming that run's profile: -the run must pass every `clear --run` check, with the carried files counted +carried run under the profile the base's `remote_gate_runs` names (a +`remote_gate_runs` that names two profiles is refused here, since one carried +run is offered; clear it with `clear --run`, one run per profile): the run +must pass every `clear --run` check, with the carried files counted as selected files. So a remainder of only files the gate's `skipped` command names (gstack's paid evals, which the gate itself reports as `PREGATE_REMOTE_PAID_ONLY` with `tests=0`) clears with `skipped=` in the diff --git a/lib/pregate/checks/lanes.ts b/lib/pregate/checks/lanes.ts index 12ed426a5..36a1856be 100644 --- a/lib/pregate/checks/lanes.ts +++ b/lib/pregate/checks/lanes.ts @@ -41,7 +41,7 @@ import { selectLanes, type Selection } from '../lane-selection'; import { launchRuntime } from '../runtime'; import { cargoModel, type CargoModel } from '../rust'; import { adapterFor, readRange, STALL_IDLE, supervise, type Counter, type Supervised } from '../supervise'; -import { ranFiles, verifyFromRun, type RunProfile } from '../../run-evidence'; +import { ranFiles, runChanged, runReceiptFields, verifyFromRun, type RunProfile } from '../../run-evidence'; import { matchesAny } from '../../ship-policy'; import { testFileArgs } from '../../test-paths'; import type { CheckDef, CheckResult, PregateContext, RemoteObligation } from '../types'; @@ -734,14 +734,22 @@ export function fromRunProfiles(ctx: PregateContext, profiles: Record verifyFromRun(check, r.ref, r.profile ? names.filter(n => n === r.profile) : names, ctx.wtree, ctx.head)); + const ok = verdicts.flatMap(v => (v.ok ? [v.evidence] : [])); + const v = verdicts[0]!; + if (!ok.length && !v.ok) return { line: `REUSE: refused reason=${v.reason} — ${v.detail}; every selected test runs here`, passed: [] }; + let changed: string | null = null; + try { for (const e of ok.length > 1 ? ok : []) changed ??= runChanged(check.deps, e.run_id, e.run_attempt); } + catch (err) { changed = `reading the runs again failed: ${String((err as Error)?.message ?? err).slice(0, 200)}`; } + if (changed) return { line: `REUSE: refused reason=run_changed — ${changed}; every selected test runs here`, passed: [] }; + const ran = new Set(ok.flatMap(ranFiles)); const passed = sel.localTests.filter(t => ran.has(t)); - const skipped = sel.localTests.filter(t => v.evidence.skipped?.includes(t)).length; - return { line: `REUSE: accepted ${passed.length} of ${sel.localTests.length} selected local test file(s) from ${v.receipt}; ${sel.localTests.length - passed.length} still run${skipped ? ` (${skipped} skipped every test in the run)` : ''}`, passed, receipt: v.receipt }; + const skipped = sel.localTests.filter(t => !ran.has(t) && ok.some(e => e.skipped?.includes(t))).length; + const receipt = `run tree=${ctx.wtree.slice(0, 12)} tests=${ok.reduce((n, e) => n + (e.tests ?? e.files.length), 0)} ${runReceiptFields(ok, check.now)}`; + return { line: `REUSE: accepted ${passed.length} of ${sel.localTests.length} selected local test file(s) from ${receipt}; ${sel.localTests.length - passed.length} still run${skipped ? ` (${skipped} skipped every test in the run)` : ''}`, passed, receipt }; } /** diff --git a/lib/pregate/index.ts b/lib/pregate/index.ts index a901513e7..c0603a62d 100644 --- a/lib/pregate/index.ts +++ b/lib/pregate/index.ts @@ -59,8 +59,8 @@ export function applyDowngrades(ctx: PregateContext, result: CheckResult, def: C /** * The tests stage's automatic `--from-run` (GSTA-258): when the base branch declares run profiles and no run was named, - * the newest verified CI run at HEAD's clean tree under a profile for this OS becomes `ctx.fromRun`, so its tree.json - * files count as passed and only the rest run (on a small machine, an all-covered selection records no remote gate + * the newest verified CI run at HEAD's clean tree under each profile for this OS goes into `ctx.fromRun`, so the tree.json + * files of every one of them count as passed and only the rest run (on a small machine, an all-covered selection records no remote gate * obligation). Returns the CI_CARRY line, or null when the base declares no profiles. Security scans, guards and the * preflight stage are never carried. */ @@ -75,12 +75,17 @@ export function autoCarry(ctx: PregateContext): string | null { if (!names.length) return none('no_profile: no base run profile for this OS covers a lane this machine runs'); const wtree = () => { const fp = wtreeFingerprint({ cwd: ctx.repoRoot }); return 'tree' in fp ? fp.tree : null; }; const refusals: string[] = []; + const runs: Array<{ ref: string; profile: string }> = []; + const receipts: string[] = []; for (const name of names) { const v = findCarry(check, { profiles: [name], head: ctx.head, tree, wtree }); - if (v.ok) { ctx.fromRun = { ref: String(v.runs[0]!.run_id), check }; return `CI_CARRY: accepted ${v.receipt}`; } - refusals.push(`${v.reason}: ${v.detail}`); + if (!v.ok) { refusals.push(`${v.reason}: ${v.detail}`); continue; } + runs.push({ ref: String(v.runs[0]!.run_id), profile: name }); + receipts.push(v.receipt); } - return none(refusals.join(' | ')); + if (!runs.length) return none(refusals.join(' | ')); + ctx.fromRun = { ref: (runs.find(r => check.gateRuns?.profiles.includes(r.profile)) ?? runs[0]!).ref, check, runs }; + return `CI_CARRY: accepted ${receipts.join(' + ')}`; } const git = (cwd: string, args: string[]): string | null => { diff --git a/lib/pregate/types.ts b/lib/pregate/types.ts index 8bbb5d103..4601da11a 100644 --- a/lib/pregate/types.ts +++ b/lib/pregate/types.ts @@ -64,8 +64,8 @@ export interface PregateContext { cores: number; testBackend: string; policyFrom: 'base' | 'head'; - /** `--from-run`: a Free Tests run whose tree.json files count as passed for this tree (lanes, lib/run-evidence.ts verifyFromRun), with the base branch's run check or why it could not be built. */ - fromRun?: { ref: string; check: RunSource | { error: string } }; + /** `--from-run`: a Free Tests run whose tree.json files count as passed for this tree (lanes, lib/run-evidence.ts verifyFromRun), with the base branch's run check or why it could not be built. The CI carry sets `runs`, every profile's verified run at this tree (`ref` is the remote gate's, else the first), and their files count together. */ + fromRun?: { ref: string; check: RunSource | { error: string }; runs?: Array<{ ref: string; profile: string }> }; /** `--no-ci-carry`: false skips the tests stage's automatic --from-run (lib/ci-carry.ts findCarry at HEAD's clean tree). */ ciCarry?: boolean; /** `--remote`: run the declared remote gate now, under this spend cap. */ diff --git a/test/pregate-ci-carry-profiles.test.ts b/test/pregate-ci-carry-profiles.test.ts new file mode 100644 index 000000000..28b0818b1 --- /dev/null +++ b/test/pregate-ci-carry-profiles.test.ts @@ -0,0 +1,126 @@ +/** + * GST-3381 (a): the CI carry (the tests stage's automatic --from-run) takes the newest verified run under every run + * profile for this machine at HEAD's tree, not only the first, so a second green workflow at the same tree (an E2E run + * beside the Test run) also shortens the local remainder. A profile whose run is red or tested another tree adds + * nothing. The Actions API is a gh shim on PATH; trees come from the fixture repository. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { buildContext } from '../lib/pregate/context'; +import { runPregate } from '../lib/pregate/index'; +import type { RunProfile } from '../lib/run-evidence'; +import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +const savedPath = process.env.PATH; +const savedRoot = process.env.GSTACK_STATE_ROOT; +afterEach(() => { + while (repos.length) cleanup(repos.pop()!); + process.env.PATH = savedPath; + if (savedRoot === undefined) delete process.env.GSTACK_STATE_ROOT; else process.env.GSTACK_STATE_ROOT = savedRoot; +}); + +const LOCAL_OS = process.platform === 'darwin' ? 'macOS' : 'Linux'; +const PROFILES: Record = { + 'ci-reuse/free-tests': { workflow: 'free-tests.yml', events: ['workflow_dispatch'], jobs: ['unit'], artifact: 'tested-tree', os: LOCAL_OS }, + 'ci-reuse/e2e': { workflow: 'e2e.yml', events: ['workflow_dispatch'], jobs: ['e2e'], artifact: 'e2e-tree', os: LOCAL_OS }, +}; +const E2E_WORKFLOW = 'name: E2E\non: [workflow_dispatch]\njobs:\n e2e:\n runs-on: ubuntu-24.04\n steps:\n - uses: actions/checkout@v4\n - name: Run e2e tests\n run: node --test test/*.test.js\n'; + +function fixture(): FixtureRepo { + const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, run_profiles: PROFILES }, baseFiles: { '.github/workflows/e2e.yml': E2E_WORKFLOW } }); + repos.push(repo); + process.env.GSTACK_STATE_ROOT = repo.home; + commit(repo, { 'lib/util.js': 'exports.add = (a, b) => a + b + 0;\n', 'lib/retry.js': 'exports.MAX_RETRIES = 3;\nexports.TIMEOUT_MS = 5000;\nexports.retry = (fn) => fn();\nexports.touched = true;\n' }, 'touch two subjects'); + repo.git('push', '-q', 'origin', 'feature'); + repo.git('remote', 'set-url', 'origin', 'https://github.com/fx/fx.git'); + repo.git('config', `url.${repo.origin}.insteadOf`, 'https://github.com/fx/fx.git'); + return repo; +} + +interface Run { id: number; workflow: string; job: string; artifact: string; files: string[]; conclusion?: string; tree?: string } +/** A gh on PATH answering the Actions reads ghRunDeps makes, for `runs` at HEAD; `flip` moves run `run` to a red attempt 2 once run `after`'s tree.json has been downloaded `downloads` times. */ +function ghShim(repo: FixtureRepo, runs: Run[], flip?: { run: number; after: number; downloads: number }): void { + const head = repo.git('rev-parse', 'HEAD'); + const tree = repo.git('rev-parse', 'HEAD^{tree}'); + const at = new Date(Date.now() - 600_000).toISOString(); + const data = Object.fromEntries(runs.map(r => [r.id, { + run: { id: r.id, run_attempt: 1, status: 'completed', conclusion: r.conclusion ?? 'success', event: 'workflow_dispatch', head_sha: head, path: `.github/workflows/${r.workflow}`, created_at: at, updated_at: at, repository: { full_name: 'fx/fx' }, head_repository: { full_name: 'fx/fx' } }, + jobs: [{ name: r.job, conclusion: r.conclusion ?? 'success', completed_at: at }], + artifact: r.artifact, + tree: { run_id: r.id, run_attempt: 1, event: 'workflow_dispatch', sha: head, tree: r.tree ?? tree, os: [LOCAL_OS], files: r.files, tests: r.files.length * 4 }, + }])); + const dir = path.join(repo.root, 'gh-shim'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'data.json'), JSON.stringify({ runs: data, flip: flip ?? null, dir })); + fs.writeFileSync(path.join(dir, 'gh'), [ + '#!/usr/bin/env node', + `const d = require(${JSON.stringify(path.join(dir, 'data.json'))}); const a = process.argv.slice(2); const fs = require('fs');`, + 'const p = a.find(x => x.startsWith(\'repos/fx/fx/actions/\')) || \'\'; const lines = xs => { for (const x of xs) console.log(JSON.stringify(x)); process.exit(0); };', + 'const id = (/\\/runs\\/(\\d+)/.exec(p) || [])[1];', + 'const count = n => { try { return Number(fs.readFileSync(d.dir + \'/dl-\' + n, \'utf8\')); } catch { return 0; } };', + 'if (d.flip && count(d.flip.after) >= d.flip.downloads) d.runs[d.flip.run].run = { ...d.runs[d.flip.run].run, run_attempt: 2, conclusion: \'failure\' };', + 'if (a[0] === \'run\' && a[1] === \'download\' && d.runs[a[2]]) { fs.writeFileSync(d.dir + \'/dl-\' + a[2], String(count(a[2]) + 1)); fs.writeFileSync(a[a.indexOf(\'--dir\') + 1] + \'/tree.json\', JSON.stringify(d.runs[a[2]].tree)); process.exit(0); }', + 'const wf = (/\\/workflows\\/([^/]+)\\/runs\\?/.exec(p) || [])[1];', + 'if (wf) lines(Object.values(d.runs).filter(r => r.run.path === \'.github/workflows/\' + wf).map(r => r.run));', + 'if (id && d.runs[id] && p === \'repos/fx/fx/actions/runs/\' + id) { console.log(JSON.stringify(d.runs[id].run)); process.exit(0); }', + 'if (id && d.runs[id] && p.includes(\'/jobs?\')) lines(d.runs[id].jobs);', + 'if (id && d.runs[id] && p.includes(\'/artifacts?\')) lines([{ id: Number(id), name: d.runs[id].artifact, size_in_bytes: 200, expired: false }]);', + 'console.error(\'gh shim: unsupported \' + a.join(\' \')); process.exit(1);', + '', + ].join('\n'), { mode: 0o755 }); + process.env.PATH = `${dir}${path.delimiter}${savedPath ?? ''}`; +} + +async function carried(repo: FixtureRepo) { + const progress: string[] = []; + const loaded = buildContext({ repoRoot: repo.work, base: 'main', policyFrom: 'base', allowRepoCommands: true, env: { ...process.env, ...repo.env }, progress: l => progress.push(l), cores: 16, testBackend: 'local' }); + if (!('ctx' in loaded)) throw new Error('fixture context refused'); + const file = await runPregate(loaded.ctx, { stage: 'tests' }); + const lanes = file.checks.find(c => c.id === 'lanes')!; + return { lanes, carry: progress.find(l => l.startsWith('CI_CARRY: ')) ?? '', ran: (lanes.lines ?? []).find(l => l.startsWith('ran: ')) ?? '' }; +} + +const TEST_RUN: Run = { id: 100, workflow: 'free-tests.yml', job: 'unit', artifact: 'tested-tree', files: ['test/util.test.js'] }; +const E2E_RUN: Run = { id: 101, workflow: 'e2e.yml', job: 'e2e', artifact: 'e2e-tree', files: ['test/retry.test.js'] }; + +describe.skipIf(process.platform === 'win32')('the CI carry unions every verified profile at the tree (GST-3381)', () => { + // Value: protects=a second green workflow at the same tree shortens the local remainder; + // fails_when=the carry stops at the first verified profile and runs the E2E run's files again here; + // why_new=GST-3381 (a), relayed from gbrain branches with Test and E2E runs; seam=runPregate with a gh shim + test('a green Test run and a green E2E run at the tree both count', async () => { + const repo = fixture(); + ghShim(repo, [TEST_RUN, E2E_RUN]); + const { lanes, carry, ran } = await carried(repo); + expect(carry).toMatch(/^CI_CARRY: accepted ci-carry .* runs=100\/1 profiles=ci-reuse\/free-tests .* \+ ci-carry .* runs=101\/1 profiles=ci-reuse\/e2e /); + expect(lanes.from_run?.files.sort()).toEqual(['test/retry.test.js', 'test/util.test.js']); + expect(lanes.from_run?.receipt).toMatch(/ tests=8 runs=100\/1,101\/1 profiles=ci-reuse\/free-tests,ci-reuse\/e2e /); + expect(ran).not.toContain('test/retry.test.js'); + expect(lanes.status).toBe('pass'); + }, 120_000); + + // Value: protects=the kept runs are read again once the union is built, as findCarry does (docs/pregate.md run evidence); + // fails_when=the Test run moves to a red attempt while the E2E run is verified and its stale files still count; + // why_new=GST-3381 cross-family trail read on #4671; seam=runPregate with a gh shim that flips run 100 after run 101's second download + test('a run that moves to a new attempt while the other is verified refuses the union, and everything runs here', async () => { + const repo = fixture(); + ghShim(repo, [TEST_RUN, E2E_RUN], { run: 100, after: 101, downloads: 2 }); + const { lanes, ran } = await carried(repo); + expect(lanes.lines).toContainEqual(expect.stringMatching(/^REUSE: refused reason=run_changed — run 100 .*; every selected test runs here$/)); + expect(lanes.from_run).toBeUndefined(); + expect([ran.includes('test/util.test.js'), ran.includes('test/retry.test.js')]).toEqual([true, true]); + }, 120_000); + + // Value: protects=only a verified run at this tree adds coverage; fails_when=a red run or a run of another tree shortens the remainder + test('an E2E run that is red, or that tested another tree, adds nothing', async () => { + for (const e2e of [{ ...E2E_RUN, conclusion: 'failure' }, { ...E2E_RUN, tree: 'f'.repeat(40) }]) { + const repo = fixture(); + ghShim(repo, [TEST_RUN, e2e]); + const { lanes, carry, ran } = await carried(repo); + expect(carry).toMatch(/^CI_CARRY: accepted ci-carry .* runs=100\/1 profiles=ci-reuse\/free-tests [^+]*$/); + expect(lanes.from_run?.files).toEqual(['test/util.test.js']); + expect(ran).toContain('test/retry.test.js'); + } + }, 240_000); +});