Skip the second Free Tests run when a PR lands onto a moved main (GST-3303) (#4655)

When the land tool merges a PR whose base moved, it has already run Free
Tests on the exact merged tree. Main's push run now reuses that run
instead of running the whole suite again, and still runs it whenever
main moved again before the merge or the newest land run wasn't green.

This also fixes the outdated `QUEUE_LAND_MERGED_CHECKS` row in the
maintainers' land guide. Nothing to do: the next stale-base land shows
`REUSE: accepted run …` on main's push run.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-22 02:33:20 +00:00
1 parent 6e90fa3d31
commit 7abc1949e1
9 files changed
+91 -15

No files matched your search

+3 -1
View File
@@ -22,7 +22,9 @@ name: Free Tests
# uploads a `tested-tree` record (tree.json) only after strict verification
# passes. A push to main first runs `reuse`: when the merged pull request's
# head has the pushed tree and a green pull_request or workflow_dispatch run of
# this workflow verifies (lib/run-evidence.ts), every suite job is skipped and
# this workflow verifies (lib/run-evidence.ts), or when land's newest dispatch
# run on gstack-land/<pr> verifies with the pushed tree as its tested tree (a
# stale-base land, docs/pregate.md#ci-reuse), every suite job is skipped and
# the aggregate links that run instead. A pull request run reuses too, but
# only a run the pull request cannot control: a green push or dispatch run on
# main, or a dispatch run on its own branch, at the merge commit's exact tree,
@@ -0,0 +1 @@
- **A PR landed onto a moved main no longer runs Free Tests twice.** When `gstack-ship-queue land` merges a PR whose base moved, `land.merged_ci` has already run Free Tests on the merged tree on `gstack-land/<n>`. Main's push run now reuses that run when it passed and tested exactly the tree that landed; when main moved again before the merge, or the newest land run wasn't green, the push run tests the tree itself as before (docs/pregate.md#ci-reuse).
+1 -1
View File
@@ -594,7 +594,7 @@ What to do with each refusal (nothing was merged unless the code says so):
| `QUEUE_RECEIPT_MISSING` / `QUEUE_RECEIPT_STALE` | lane | /ship at the pin |
| `QUEUE_NOT_READY` | lane, or Captain | no READY note: `ready --pr <n> --no-screen` at the pin; `merge: train`: use the train; closed or retargeted PR: as named |
| `QUEUE_LAND_CHECKS` | Captain, then lane | pending: `gstack-pr-wait <n> --until green` and rerun; red: back to the lane (rule 16 rerun for a flaky case); missing: dispatch the workflow on the branch |
| `QUEUE_LAND_MERGED_CHECKS` | lane | a `land.merged_checks` command failed on the pin merged onto main: the lane merges main (rule 19), fixes it, /ship, `ready`, new READY |
| `QUEUE_LAND_MERGED_CHECKS` | Captain, then lane | the message says the checks changed files land's git or gh calls read: hold, nothing goes back to the lane yet; restore each named path from a trusted copy, release the lock with `land --pr <n> --pin <sha>` (no `--allow-repo-commands`), and find out why the checks wrote there. Otherwise a `land.merged_checks` command failed, or the `land.merged_ci` run was red, on the pin merged onto main: one rerun of land for a flaky case (rule 16), else back to the lane, which merges main (rule 19), fixes it, /ship, `ready`, new READY ([troubleshooting](../../docs/troubleshooting.md#queue-land-merged-checks)) |
| `QUEUE_LAND_NOT_CLEAN` | lane, or Captain | `CONFLICTING`, or the pin conflicts with main's tip on a stale base: the lane merges main (rule 19), /ship, `ready`; `UNKNOWN`: rerun in a minute |
| `QUEUE_TRAIN_FROZEN` / `QUEUE_LAND_LOCKED` | Captain | finish the repair or the holder first |
| `QUEUE_TRAIN_UNTRUSTED` | Captain | a fork head; rewrite on a crew branch |
+17 -1
View File
@@ -1507,13 +1507,29 @@ job keeps the workflow's `contents: read`). It runs
1. finds the pull request whose merge commit is the pushed commit
(`repos/{repo}/commits/{sha}/pulls`, one page of at most 10), merged into
main from a same-repository head (`no_pr`, `ambiguous_pr`, `fork_head`);
2. requires that head's tree to equal the pushed tree (`tree_mismatch`);
2. requires that head's tree to equal the pushed tree, with one exception
below for a stale-base land (`tree_mismatch`);
3. lists that head's `pull_request` and `workflow_dispatch` runs of the same
workflow, newest first, at most 10 (`no_candidate`); and
4. accepts the first one `verifyRun` accepts under the profile in the pushed
tree's `.gstack/pregate.json` (`no_verified_run` lists each refusal; a newer
red run on the head vetoes an older green one).
The exception is a pull request that `gstack-ship-queue land` merged onto a
base that had moved past it. Under `land.merged_ci`, land already ran this
workflow on the merged commit, on the scratch branch `gstack-land/<n>`
([ship-policy.md](ship-policy.md#land-direct)), and GitHub's merge has that
same tree unless main moved again before the merge. So when the head's tree
differs, `find` takes the newest `workflow_dispatch` run on `gstack-land/<n>`
and reuses it only when `verifyRun` accepts it and its `tested-tree` record
names the pushed tree (`no_verified_run` or `tree_mismatch` otherwise; a branch
with no such run keeps `tree_mismatch`). Only the newest run counts, newest by run id
rather than start time, so a red retry on the same tree is never hidden
behind an older green one, even when that older run is re-run later. Unlike a pull
request consumer, this one needs no byte-identical check on the reuse files:
the run executed the workflow in its own commit, whose tree is the pushed tree,
so the rules it ran under are the ones now on main, whoever dispatched it.
It writes `reused=true` with the run's id and link, or `reused=false` and the
reason, and prints one `REUSE:` line in the step summary. Every suite job
needs `reuse` and runs unless it succeeded with `reused=true`; their
+4 -1
View File
@@ -3053,7 +3053,10 @@ The run is on CI runners, so it needs no `--allow-repo-commands`, and
under `ci-reuse/free-tests`, so the whole free suite has run on a stale-base tree
before it lands (about 5 minutes); its `merged_checks` still run first and fail
fast. A rerun after the merge checks the landed tree with `merged_checks` only,
and main's own push run tests it in CI.
and main's own push run tests it in CI. When main didn't move again before
the merge, the landed tree is the one this run tested, so main's push run of
`free-tests.yml` reuses it instead of running the suite a second time
([pregate.md](pregate.md#ci-reuse)).
Then land runs `gh pr merge
--squash --match-head-commit <pin>` (`--merge` under `history: merge-only`),
+2 -2
View File
@@ -10,7 +10,7 @@
import { git, type QueueFailure } from '../crew/lib/ship-queue-gate';
import { repoSlug } from '../crew/lib/ship-queue-train-github';
import { MIN_POLL_MS, pollDelayMs, syncLimitEnv } from './gh-poll';
import { ghRunDeps, runProfileErrors, verifyRun, type ApiRun, type RunProfile } from './run-evidence';
import { ghRunDeps, landBranch, runProfileErrors, verifyRun, type ApiRun, type RunProfile } from './run-evidence';
import type { QueueContext } from './ship-queue';
export const CI_TIMEOUT_MS = 45 * 60_000;
@@ -33,7 +33,7 @@ export type CiResult = { ok: true; line: string } | { ok: false; red: boolean; d
/** One dispatch of `ci.workflow` on the merged commit and its verdict; red when the run itself failed, else land could not run or prove it. */
export function runMergedCi(deps: CiDeps, o: { pr: string; commit: string; tree: string; ci: MergedCi; timeoutMs?: number }): CiResult {
const branch = `gstack-land/${o.pr}`;
const branch = landBranch(o.pr);
const pushed = deps.push(o.commit, branch);
if (pushed) return { ok: false, red: false, detail: `cannot push the merged commit ${o.commit.slice(0, 12)} to ${branch}: ${pushed}` };
try {
+2
View File
@@ -105,6 +105,8 @@ const PROFILE_KEYS = ['workflow', 'events', 'jobs', 'artifact', 'max_age_hours',
const WORKFLOW_FILE = /^[A-Za-z0-9_.-]+\.ya?ml$/;
const NAME = /^[A-Za-z0-9_.\/-]{1,128}$/;
export const DEFAULT_MAX_AGE_HOURS = 24;
/** The scratch branch land.merged_ci runs CI on (lib/land-merged-ci.ts), whose run a main push of that land may reuse (scripts/ci-tree-reuse.ts). */
export const landBranch = (pr: number | string): string => `gstack-land/${pr}`;
const MAX_ARTIFACT_BYTES = 8 * 1024 * 1024;
/** Same-named artifacts one run may hold, one per attempt of the job that uploads it. */
const MAX_ARTIFACT_ATTEMPTS = 10;
+21 -7
View File
@@ -18,7 +18,11 @@
* this workflow (pull_request or workflow_dispatch, newest first, at most MAX_CANDIDATES), and accepts the
* first one lib/run-evidence.ts verifyRun accepts under the profile in the pushed tree's
* .gstack/pregate.json. A pull_request run counts only when its merge commit's tree is its head's tree
* (verifyRun). It writes reused=true, run_id, run_url and tree to GITHUB_OUTPUT, or reused=false and a
* (verifyRun). When the head's tree differs (land merged a stale-base pin), the only candidate is the newest
* workflow_dispatch run on landBranch(<pr>), the run land.merged_ci gated the merge on, and it counts only when
* verifyRun accepts it with the pushed tree as its tested tree (newest by run id, so a re-run of an older land run
* never outranks a later red one): that run executed this same tree's workflow, so
* the rules it ran under are the ones now on main. It writes reused=true, run_id, run_url and tree to GITHUB_OUTPUT, or reused=false and a
* reason, with one REUSE: line in the step summary. Every lookup failure is a refusal, never a pass: the
* workflow then runs every job as before. Dispatch runs never consume.
*
@@ -32,7 +36,7 @@
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { ghApiJson, ghRunDeps, runProfileErrors, verifyRun, type ApiRun, type RunDeps, type RunProfile } from '../lib/run-evidence';
import { ghApiJson, ghRunDeps, landBranch, runProfileErrors, verifyRun, type ApiRun, type RunDeps, type RunProfile } from '../lib/run-evidence';
export const MAX_PULLS = 10;
export const MAX_CANDIDATES = 10;
@@ -40,9 +44,8 @@ const SHA = /^[0-9a-f]{40}$/;
const OSES = ['Linux', 'macOS', 'Windows'];
export interface ApiPull { number: number; merged_at: string | null; merge_commit_sha: string | null; base: { ref: string; repo?: { full_name: string } | null }; head: { sha: string; repo: { full_name: string } | null } }
export interface ReuseDeps extends RunDeps { pullsForCommit(sha: string): ApiPull[] }
export interface PrReuseDeps extends RunDeps {
runsForBranch(workflow: string, branch: string): ApiRun[];
export interface ReuseDeps extends RunDeps { pullsForCommit(sha: string): ApiPull[]; runsForBranch(workflow: string, branch: string): ApiRun[] }
export interface PrReuseDeps extends RunDeps, Pick<ReuseDeps, 'runsForBranch'> {
commit(sha: string): { tree: string; parents: string[] } | null;
blob(sha: string, file: string): string | null;
}
@@ -71,8 +74,19 @@ export function findReuse(deps: ReuseDeps, o: { repo: string; base: string; push
const pushTree = deps.commitTree(o.pushSha);
const headTree = deps.commitTree(pr.head.sha);
if (!pushTree || !headTree) return refuse('api_error', `cannot read the tree of ${pushTree ? pr.head.sha : o.pushSha}`);
if (headTree !== pushTree) return refuse('tree_mismatch', `#${pr.number}'s head ${pr.head.sha.slice(0, 12)} has tree ${headTree.slice(0, 12)}, the push has ${pushTree.slice(0, 12)}`);
const events: string[] = o.profile.events.filter(e => e === 'pull_request' || e === 'workflow_dispatch');
if (headTree !== pushTree) {
const mismatch = `#${pr.number}'s head ${pr.head.sha.slice(0, 12)} has tree ${headTree.slice(0, 12)}, the push has ${pushTree.slice(0, 12)}`;
const branch = landBranch(pr.number);
const land = events.includes('workflow_dispatch')
? deps.runsForBranch(o.workflow, branch).filter(r => r.event === 'workflow_dispatch' && r.head_branch === branch).sort((a, b) => b.id - a.id)[0]
: undefined;
if (!land) return refuse('tree_mismatch', `${mismatch}, and ${branch} has no workflow_dispatch run of ${o.workflow}`);
const v = verifyRun(deps, { repo: o.repo, runRef: String(land.id), profileName: o.profileName, profile: o.profile, now: o.now });
if (!v.ok) return refuse('no_verified_run', `${mismatch}; land run ${land.id} on ${branch} reason=${v.reason} ${v.detail}`);
if (v.evidence.tree !== pushTree) return refuse('tree_mismatch', `${mismatch}, and land run ${land.id} on ${branch} tested tree ${v.evidence.tree.slice(0, 12)}`);
return { reused: true, run_id: v.evidence.run_id, run_attempt: v.evidence.run_attempt, event: v.evidence.event, pr: pr.number, head_sha: v.evidence.head_sha, tree: pushTree };
}
const candidates = deps.runsForHead(o.workflow, pr.head.sha).filter(r => events.includes(r.event))
.sort((a, b) => startedAt(b).localeCompare(startedAt(a)) || b.id - a.id).slice(0, MAX_CANDIDATES);
if (!candidates.length) return refuse('no_candidate', `#${pr.number}'s head ${pr.head.sha.slice(0, 12)} has no ${events.join(' or ') || 'pull_request or workflow_dispatch'} run of ${o.workflow}`);
@@ -210,6 +224,7 @@ function find(args: string[]): number {
...ghRunDeps(repo, process.cwd()),
commitTree: sha => (SHA.test(sha) ? ghApiJson<{ tree?: { sha?: string } }>(`repos/${repo}/git/commits/${sha}`).tree?.sha ?? null : null),
pullsForCommit: sha => ghApiJson<ApiPull[]>(`repos/${repo}/commits/${sha}/pulls?per_page=${MAX_PULLS}`),
runsForBranch: (wf, branch) => ghApiJson<{ workflow_runs?: ApiRun[] }>(`repos/${repo}/actions/workflows/${wf}/runs?branch=${encodeURIComponent(branch)}&per_page=${MAX_CANDIDATES}`).workflow_runs ?? [],
};
if (mainPush) return settle(findReuse(deps, { repo, base: 'main', pushSha: env.GITHUB_SHA ?? '', workflow, profileName, profile, now: new Date() }));
let event: { pull_request?: { number?: number; head?: { sha?: string; ref?: string; repo?: { full_name?: string } | null }; base?: { ref?: string } } };
@@ -218,7 +233,6 @@ function find(args: string[]): number {
const pr: PrContext = { number: Number(p.number), mergeSha: env.GITHUB_SHA ?? '', headSha: p.head?.sha ?? '', headRef: p.head?.ref ?? '', headRepo: p.head?.repo?.full_name ?? '', baseRef: p.base?.ref ?? '', runId: Number(env.GITHUB_RUN_ID), runAttempt: Number(env.GITHUB_RUN_ATTEMPT) };
const prDeps: PrReuseDeps = {
...deps,
runsForBranch: (wf, branch) => ghApiJson<{ workflow_runs?: ApiRun[] }>(`repos/${repo}/actions/workflows/${wf}/runs?branch=${encodeURIComponent(branch)}&per_page=${MAX_CANDIDATES}`).workflow_runs ?? [],
commit: sha => {
if (!SHA.test(sha)) return null;
const c = ghApiJson<{ tree?: { sha?: string }; parents?: Array<{ sha?: string }> }>(`repos/${repo}/git/commits/${sha}`);
+40 -2
View File
@@ -20,7 +20,7 @@ const NOW = new Date('2026-10-30T12:00:00Z');
const PROFILE: RunProfile = { workflow: 'free-tests.yml', events: ['pull_request', 'workflow_dispatch'], jobs: ['free-plan', 'free-tests'], artifact: 'tested-tree', os: 'Linux' };
const SCRIPT = path.resolve(import.meta.dir, '..', 'scripts', 'ci-tree-reuse.ts');
interface Fake { id: number; event?: string; conclusion?: string | null; status?: string; started?: string; head?: string; record?: Partial<TreeRecord> | Error; jobs?: ApiJob[] }
interface Fake { id: number; event?: string; conclusion?: string | null; status?: string; started?: string; head?: string; branch?: string; record?: Partial<TreeRecord> | Error; jobs?: ApiJob[] }
interface World { pulls: ApiPull[] | Error; runs: Fake[]; trees: Record<string, string | null> }
const pull = (over: Partial<ApiPull> = {}): ApiPull => ({ number: 42, merged_at: '2026-10-30T11:00:00Z', merge_commit_sha: PUSH, base: { ref: 'main', repo: { full_name: REPO } }, head: { sha: HEAD, repo: { full_name: REPO } }, ...over });
function world(over: Partial<World> = {}): World {
@@ -28,7 +28,7 @@ function world(over: Partial<World> = {}): World {
}
function deps(w: World, reads: number[] = []): ReuseDeps {
const api = (f: Fake): ApiRun => ({
id: f.id, run_attempt: 1, status: f.status ?? 'completed', conclusion: f.conclusion === undefined ? 'success' : f.conclusion, event: f.event ?? 'workflow_dispatch', head_sha: f.head ?? HEAD,
id: f.id, run_attempt: 1, status: f.status ?? 'completed', conclusion: f.conclusion === undefined ? 'success' : f.conclusion, event: f.event ?? 'workflow_dispatch', head_sha: f.head ?? HEAD, head_branch: f.branch ?? 'feat',
path: '.github/workflows/free-tests.yml', created_at: f.started ?? '2026-10-30T10:00:00Z', run_started_at: f.started ?? '2026-10-30T10:00:00Z', updated_at: '2026-10-30T10:30:00Z',
repository: { full_name: REPO }, head_repository: { full_name: REPO },
});
@@ -37,6 +37,7 @@ function deps(w: World, reads: number[] = []): ReuseDeps {
pullsForCommit: () => { if (w.pulls instanceof Error) throw w.pulls; return w.pulls; },
run: id => { reads.push(id); return api(byId(id)); },
runsForHead: (wf, sha) => (wf === 'free-tests.yml' ? w.runs.filter(r => (r.head ?? HEAD) === sha).map(api) : []),
runsForBranch: (wf, branch) => (wf === 'free-tests.yml' ? w.runs.filter(r => (r.branch ?? 'feat') === branch).map(api) : []),
jobs: id => byId(id).jobs ?? [{ name: 'free-plan', conclusion: 'success' }, { name: 'free-tests', conclusion: 'success' }],
artifact: id => {
const f = byId(id);
@@ -80,6 +81,43 @@ describe('findReuse: candidate discovery for a main push', () => {
expect(reads).toEqual([]);
});
describe('a stale-base land: the head lacks main\'s newer commits, so only land\'s merged_ci run can be reused', () => {
const LAND = '5'.repeat(40);
const OTHER = '6'.repeat(40);
const stale = (runs: Fake[], trees: Record<string, string> = {}) => world({ runs, trees: { [PUSH]: TREE, [HEAD]: OTHER, [LAND]: TREE, ...trees } });
const landRun = (over: Partial<Fake> = {}): Fake => ({ id: 300, head: LAND, branch: 'gstack-land/42', ...over });
test('the newest green dispatch run on gstack-land/<pr> that tested the pushed tree is reused', () => {
expect(find(stale([{ id: 100 }, landRun()]))).toEqual({ reused: true, run_id: 300, run_attempt: 1, event: 'workflow_dispatch', pr: 42, head_sha: LAND, tree: TREE });
});
test('only the newest land run counts, so a red retry on the same tree is never hidden behind an older green one', () => {
const LAND2 = '7'.repeat(40);
const v = find(stale([landRun({ started: '2026-10-30T10:00:00Z' }), landRun({ id: 301, head: LAND2, conclusion: 'failure', started: '2026-10-30T10:40:00Z' })], { [LAND2]: TREE }));
expect(v).toMatchObject({ reused: false, reason: 'no_verified_run' });
expect(!v.reused && v.detail).toContain('land run 301 on gstack-land/42 reason=run_not_success');
expect(why(stale([landRun({ status: 'in_progress', conclusion: null })]))).toBe('no_verified_run');
const rerunOlder = find(stale([landRun({ started: '2026-10-30T11:00:00Z' }), landRun({ id: 301, head: LAND2, conclusion: 'failure', started: '2026-10-30T10:40:00Z' })], { [LAND2]: TREE }));
expect(rerunOlder).toMatchObject({ reused: false, reason: 'no_verified_run', detail: expect.stringContaining('land run 301 on gstack-land/42 reason=run_not_success') });
});
test('a land run that tested another tree (main moved before the merge) is refused, and the suite runs', () => {
const v = find(stale([landRun({ record: { tree: OTHER } })], { [LAND]: OTHER }));
expect(v).toMatchObject({ reused: false, reason: 'tree_mismatch' });
expect(!v.reused && v.detail).toContain('land run 300 on gstack-land/42 tested tree');
});
test('nothing else on a mismatched head is a candidate: no land run, a pull_request run on the land branch, another branch, or a profile without dispatch', () => {
const reads: number[] = [];
expect(find(stale([{ id: 100 }]), reads)).toMatchObject({ reused: false, reason: 'tree_mismatch', detail: expect.stringContaining('gstack-land/42 has no workflow_dispatch run') });
expect(reads).toEqual([]);
expect(why(stale([landRun({ event: 'pull_request' })]))).toBe('tree_mismatch');
expect(why(stale([landRun({ branch: 'gstack-land/43' })]))).toBe('tree_mismatch');
const prOnly = findReuse(deps(stale([landRun()])), { repo: REPO, base: 'main', pushSha: PUSH, workflow: 'free-tests.yml', profileName: 'ci-reuse/free-tests', profile: { ...PROFILE, events: ['pull_request'] }, now: NOW });
expect(prOnly).toMatchObject({ reused: false, reason: 'tree_mismatch' });
});
});
test('a reuse record is never evidence: a run that itself reused another run is refused', () => {
expect(find(world({ runs: [{ id: 100, record: { reused: true } }] }))).toMatchObject({ reused: false, reason: 'no_verified_run', detail: expect.stringContaining('reason=artifact_reused') });
expect(find(world({ runs: [{ id: 100, record: new Error('no artifact named tested-tree') }] }))).toMatchObject({ reused: false, detail: expect.stringContaining('reason=artifact_missing') });