diff --git a/changelog.d/land-reuses-merged-tree-ci-run.md b/changelog.d/land-reuses-merged-tree-ci-run.md new file mode 100644 index 000000000..3903b7e29 --- /dev/null +++ b/changelog.d/land-reuses-merged-tree-ci-run.md @@ -0,0 +1 @@ +**Landing a PR no longer starts a new CI run when one for the same merged code is already running or has passed.** When main had moved, each `gstack-ship-queue land --pin` dispatched a fresh Free Tests run on the merged tree and gave up after 45 minutes, so a slow macOS runner queue refused the land, and the next try queued yet another run while the first one finished green unused. Land now reuses the newest earlier run on the same merged tree. It lands at once on a green run, waits on one still queued and refuses on a red one, and a timeout names the run the next try will wait on. diff --git a/crew/docs/captain.md b/crew/docs/captain.md index deb0adba2..c347d5f2b 100644 --- a/crew/docs/captain.md +++ b/crew/docs/captain.md @@ -654,7 +654,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 --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 --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` | 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 --pin ` (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_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 --pin ` (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 for a flaky case (rule 16; for a red `land.merged_ci` run that is `gh run rerun ` then land, since land reuses that run), 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. land takes over a lock whose land exited or expired by itself; a lock it refuses says why: a land still running (wait, or stop the process it names if stuck), another machine's land (rerun after the expiry it prints, or `--break-lock` once you know that land stopped), or a deliberate hold (release it as the `LOCK:` line says) | | `QUEUE_TRAIN_UNTRUSTED` | Captain | a fork head; rewrite on a crew branch | diff --git a/docs/ship-policy.md b/docs/ship-policy.md index a694e6b1a..ee4098f60 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -82,7 +82,7 @@ branch that changes the policy. | `docs` | `{ caps: [{ path, max_bytes }] }` or `null` | `null` | Documentation files with a byte cap. `/ship` Step 14.5 runs `gstack-ship-receipt docs-caps --base ` (the caps come from `origin/`'s policy, never the branch's copy; `--policy ` is for a repository bootstrapping its policy) before the verification gate and prints one `DOCS_CAP: / ok\|over` line per cap; any `over` (an absent file counts) exits 1 and blocks the ship until the file is trimmed or the cap raised on the base branch (`DOCS_AUDIT_BLOCKED`). At most 64 caps, each path contained. See [the ship receipt](#ship-receipt). Needs `min_gstack_version`. | | `train` | `{ gate_workflow, free_workflow, full_gate_check, record_artifact, max_size, fill_hours, screen_selection, trial_reservation_usd, land? }`, `{ gates, land, max_size, fill_hours }` or `null` | `null` | Turns on [merge trains](#run-a-merge-train), read from the base revision only. Every field is required and an unknown field is `POLICY_INVALID`: `max_size` 1 to 6, `fill_hours` above 0 and at most 24, `screen_selection` `gstack-paid` \| `none`, `trial_reservation_usd` above 0 and at most 100. A block with `gates` ([any repository](#train-gates)) takes `max_size` 1 to 5 and needs `min_gstack_version` at least `TRAIN_GATES_KEY_VERSION`. `null` keeps the per-PR queue exactly as it is. Needs `min_gstack_version`. | | `merge` | `train` \| `direct` | `train` | `direct` lands each READY PR at its own green head with [`land --pr --pin `](#land-direct): no train and no stamp commit, and `train build` refuses. A PR then leaves VERSION, the `package.json` version and the CHANGELOG at its merge base, and the release sets them. Needs `changelog_fragments`, and the stamping `land --pr ` refuses under it. `train` keeps merge trains. Read from the base revision only. Needs `min_gstack_version`. | -| `land` | `{ merged_checks?, docs_only_skip?, merge_commit_paths?, merged_ci? }` or `null` | `null` | Under `merge: direct`, the shell commands (1 to 16, one line of at most 512 characters each, 15 minutes each) [`land --pin`](#land-direct) runs on the pin merged onto the base tip when the base moved past the pin's merge base; it lands only when every one exits 0. They are repo commands, so land runs them only with `--allow-repo-commands`, never under `--dry-run`. `null` lands a stale base untested with a `STALE_BASE: warn` line. `docs_only_skip` lists `merged_checks` commands to skip for a docs-only pin ([pregate.md](pregate.md#docs-only)) and needs `min_gstack_version` at its own release (`LAND_DOCS_ONLY_SKIP_KEY_VERSION`), because older releases refuse it. `merge_commit_paths` (1 to 64 git glob pathspecs, no `..`) makes every land form keep a merge commit, with the plain subject and body, for a PR that changes a matching path, such as an eval results PR whose run records point to its own commits; with it, `merged_checks` may be left out, and it needs `min_gstack_version` at its own release (`LAND_MERGE_COMMIT_PATHS_KEY_VERSION`). `merged_ci` (`{ workflow, profile }`) dispatches that workflow on the merged commit after any `merged_checks` pass and lands only when its run passes the named run profile of `.gstack/pregate.json` ([land --pin](#land-direct)); with it, `merged_checks` may be left out, and an older gstack ignores it with a warning. Any other key under `land` is a warning, ignored. Read from the base revision only. Needs `min_gstack_version`. | +| `land` | `{ merged_checks?, docs_only_skip?, merge_commit_paths?, merged_ci? }` or `null` | `null` | Under `merge: direct`, the shell commands (1 to 16, one line of at most 512 characters each, 15 minutes each) [`land --pin`](#land-direct) runs on the pin merged onto the base tip when the base moved past the pin's merge base; it lands only when every one exits 0. They are repo commands, so land runs them only with `--allow-repo-commands`, never under `--dry-run`. `null` lands a stale base untested with a `STALE_BASE: warn` line. `docs_only_skip` lists `merged_checks` commands to skip for a docs-only pin ([pregate.md](pregate.md#docs-only)) and needs `min_gstack_version` at its own release (`LAND_DOCS_ONLY_SKIP_KEY_VERSION`), because older releases refuse it. `merge_commit_paths` (1 to 64 git glob pathspecs, no `..`) makes every land form keep a merge commit, with the plain subject and body, for a PR that changes a matching path, such as an eval results PR whose run records point to its own commits; with it, `merged_checks` may be left out, and it needs `min_gstack_version` at its own release (`LAND_MERGE_COMMIT_PATHS_KEY_VERSION`). `merged_ci` (`{ workflow, profile }`) dispatches that workflow on the merged commit after any `merged_checks` pass, or waits on an earlier land's run of it on the same merged tree, and lands only when that run passes the named run profile of `.gstack/pregate.json` ([land --pin](#land-direct)); with it, `merged_checks` may be left out, and an older gstack ignores it with a warning. Any other key under `land` is a warning, ignored. Read from the base revision only. Needs `min_gstack_version`. | | `docs_only` | `{ allow, deny?, tests? }` or `null` | `null` | Human-docs paths beyond `README.md`, `docs/**.md` and `changelog.d/*.md` for the [docs-only class](pregate.md#repo-docs-paths) (`{ "allow": ["wiki/board/**.md"] }`). `allow` (1 to 16) takes narrow Markdown globs: each ends in `.md`, starts with a literal directory or file name, and passes through no hidden, code, test or agent directory; `**`, `*`, `*.md` and patterns naming agent files are `POLICY_INVALID` with an example of a narrow one. `deny` (up to 64 globs) removes paths, built-in ones included. `tests` (up to 16 test files) are the repository's checks for those directories: the docs lane runs them, and a non-prose file that reads an allowed directory refuses the class unless it is tied to one; a listed test missing from the branch refuses it too. The built-in deny list always wins. Any other key under `docs_only` is a warning, and the classifier then ignores `allow`. Read from the base revision only; a pull request that edits this file is never docs-only. Needs `min_gstack_version`. | | `release_gate` | `{ cadence_hours, gate_workflow, branch, stable_ref, check_name, on_red, bisect_spend_cap_usd }` or `null` | `null` | One full paid gate on main every `cadence_hours` (8 to 168) instead of the per-push main backstop, feeding the stable release; see [release_gate](#release-gate). Every field is required: `on_red` is `hold-release`, `bisect_spend_cap_usd` 0 to 500 (0 skips the bisect). `null` keeps the per-push backstop. Needs `min_gstack_version`. | | `bookkeeping` | glob list | `[]` | Root-anchored globs of bookkeeping tables a verify or ratchet step rewrites (size baselines, serial lists, limits), each ending in `.tsv`, `.csv` or `.txt` and never under `.gstack/` or `.github/` (`["scripts/*-baseline.tsv"]`). A matching file changed at most 20 lines after review binds, first touched or not, takes finish's [one scoped reader](review-policy.md#bounded-post-review-edits) instead of Steps 5–11.5; the reader still reads every changed row. Read from the base revision only. Needs `min_gstack_version`. | @@ -3105,10 +3105,27 @@ on the same merged tree: it pushes the merged commit to the scratch branch `gstack-land/`, dispatches the workflow there, waits up to 45 minutes, and prints `MERGED_CI: pass run on the merged tree (profile )` only when `lib/run-evidence.ts` accepts the run under that run profile -of the base's `.gstack/pregate.json`, with the merged commit as its head and the +of the base's `.gstack/pregate.json`, with the run's head commit as its head and the merged tree as its tested tree. A red run refuses with `QUEUE_LAND_MERGED_CHECKS`; a run that can't be pushed, dispatched, finished in time or proved refuses with `QUEUE_NOT_READY`; the branch is deleted either way. + +Every land builds a new merged commit, so before it dispatches, land looks for a +run an earlier land already started on the same tree: a `workflow_dispatch` run +of the workflow on `gstack-land/` (GitHub keeps the run and its branch name +after the branch is deleted) or at this merged commit, whose head commit has the +merged tree. It matches on the tree, never the commit. The newest such run that +wasn't cancelled decides: a finished green run lands with no new dispatch (the +`MERGED_CI` line adds `run by an earlier land at , not dispatched +again`), a run still queued or running is waited on for up to 45 minutes, and a +red one refuses with `QUEUE_LAND_MERGED_CHECKS`. Only a finished green run that +no longer proves the tree (its artifact expired, or it is past the profile's +`max_age_hours`) is passed over for a fresh dispatch. So when GitHub's runner +queue is slower than 45 minutes, the timeout's `QUEUE_NOT_READY` names the run, +and rerunning the same `land` while main hasn't moved waits on that run, or lands +at once when it has already passed, instead of joining the queue again. For a +flaky red run, rerun the run once (`gh run rerun `) and then land, which +waits on its new attempt; rerunning land alone finds the same red run. The run is on CI runners, so it needs no `--allow-repo-commands`, and `--dry-run` dispatches nothing. gstack's own policy dispatches `free-tests.yml` under `ci-reuse/free-tests`, so the whole free suite has run on a stale-base tree diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index c886c1334..9254acc86 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -6287,7 +6287,11 @@ green, a name in `changelog_fragments.required_checks` is missing or not green there, the PR's base is no longer the train's base, the stamp push failed while the branch still read the pin, `gh pr merge` refused, or the merge is not yet visible on main. `land` also uses it when a land lock push to origin failed and -origin's lock ref could not be read to tell whether the push landed. +origin's lock ref could not be read to tell whether the push landed, and when +the `land.merged_ci` run on the merged tree could not be pushed, dispatched, +finished within 45 minutes or proved ([land --pin](ship-policy.md#land-direct)). +A timeout names the run it was waiting on, which is often just sitting in +GitHub's macOS runner queue. **Fix.** Commit and push, wait for CI on that head, rerun `gstack-pregate run --allow-repo-commands` when the tree changed, then rerun @@ -6298,7 +6302,12 @@ trial-merge fetch timeout, fetch the named refs by hand (`git fetch origin `) or raise `GSTACK_TRIAL_FETCH_TIMEOUT_MS`, then rerun ready. For an unreadable land lock, rerun the same `land` command once origin answers; it -resumes its own lock. +resumes its own lock. For a `land.merged_ci` timeout, rerun the same `land` +command whenever you like and don't cancel the named run: while `origin/main` +hasn't moved, the merged tree is the same, so land waits on that run for up to +45 more minutes, or lands at once when it has already passed, instead of +dispatching a new run that waits in the same queue. Once main moves, the merged +tree changes and land dispatches a run for the new one. ### `QUEUE_BASE_UNFETCHED` @@ -6620,7 +6629,10 @@ added) before any git command in that checkout, then release the lock without running the checks with `gstack-ship-queue land --pr --pin ` (no `--allow-repo-commands`), and find out why the PR's checks wrote there before it lands. For a failed command or a red CI run, read the output or the failed job; -a flaky case gets one rerun of land, and a real failure goes back to the lane, +a flaky case gets one rerun (for a failed command, rerun land; for a red +`land.merged_ci` run, rerun that run with `gh run rerun ` and then land, +which waits on its new attempt, because land reuses the newest run on the same +merged tree and would otherwise find the same red run), and a real failure goes back to the lane, which merges `origin/main` into the branch, fixes it, pushes, waits for the required checks, runs /ship and `ready` at the new head, and sends a new READY. diff --git a/lib/land-merged-checks.ts b/lib/land-merged-checks.ts index 3b85c3871..d11b79233 100644 --- a/lib/land-merged-checks.ts +++ b/lib/land-merged-checks.ts @@ -108,7 +108,7 @@ function changedGitPaths(before: Map, after: Map !same(before.get(p), after.get(p))).sort(); } -export const LAND_EXPLANATION = '{ merged_checks, docs_only_skip? } or null, read from the base revision only: under merge: direct, when the base moved past a pin\'s merge base, `land --pin` builds the pin merged onto the base tip in a fresh clone outside the checkout (its own .git, a copy of the checkout\'s node_modules) and runs each merged_checks command there (at most 16, 512 characters each, 15 minutes each); it lands only when every one exits 0, and refuses on a conflict (QUEUE_LAND_NOT_CLEAN) or a failure (QUEUE_LAND_MERGED_CHECKS). They are repo commands: land runs them only with --allow-repo-commands (else REPO_COMMANDS_NOT_ALLOWED), never under --dry-run, with PATH and locale as the only environment and a throwaway HOME. null lands a stale base unchecked with a STALE_BASE: warn line. docs_only_skip names merged_checks commands land skips for a pin lib/docs-only.ts calls human docs only (docs/pregate.md#docs-only) and needs min_gstack_version at its own introducing release. merge_commit_paths lists git glob pathspecs (at most 64, 256 characters each, no `..`): a PR that changes one lands as a merge commit instead of a squash, so an eval results PR keeps the commits its run receipts point to (docs/writing-prs.md#the-commit-on-main); it needs min_gstack_version at its own introducing release, and with it merged_checks may be left out. merged_ci { workflow, profile } runs CI on the tree that would land, after any merged_checks pass: land pushes the merged commit to the scratch branch gstack-land/, dispatches the workflow there, waits up to 45 minutes, and lands only when lib/run-evidence.ts accepts that run under the named run profile of the base\'s .gstack/pregate.json with the merged tree as its tested tree (a red run refuses with QUEUE_LAND_MERGED_CHECKS; a run that cannot start, finish or be proved refuses with QUEUE_NOT_READY); it runs on CI, so it needs no --allow-repo-commands, never runs under --dry-run, and the branch is deleted whatever the outcome; with it merged_checks may be left out, and an older gstack ignores it with a warning. An unknown key under land is a warning, ignored.'; +export const LAND_EXPLANATION = '{ merged_checks, docs_only_skip? } or null, read from the base revision only: under merge: direct, when the base moved past a pin\'s merge base, `land --pin` builds the pin merged onto the base tip in a fresh clone outside the checkout (its own .git, a copy of the checkout\'s node_modules) and runs each merged_checks command there (at most 16, 512 characters each, 15 minutes each); it lands only when every one exits 0, and refuses on a conflict (QUEUE_LAND_NOT_CLEAN) or a failure (QUEUE_LAND_MERGED_CHECKS). They are repo commands: land runs them only with --allow-repo-commands (else REPO_COMMANDS_NOT_ALLOWED), never under --dry-run, with PATH and locale as the only environment and a throwaway HOME. null lands a stale base unchecked with a STALE_BASE: warn line. docs_only_skip names merged_checks commands land skips for a pin lib/docs-only.ts calls human docs only (docs/pregate.md#docs-only) and needs min_gstack_version at its own introducing release. merge_commit_paths lists git glob pathspecs (at most 64, 256 characters each, no `..`): a PR that changes one lands as a merge commit instead of a squash, so an eval results PR keeps the commits its run receipts point to (docs/writing-prs.md#the-commit-on-main); it needs min_gstack_version at its own introducing release, and with it merged_checks may be left out. merged_ci { workflow, profile } runs CI on the tree that would land, after any merged_checks pass: land pushes the merged commit to the scratch branch gstack-land/, dispatches the workflow there, waits up to 45 minutes, and lands only when lib/run-evidence.ts accepts that run (an earlier land\'s workflow_dispatch run on gstack-land/ whose head commit has the same merged tree is reused instead of a new dispatch: waited on while it runs, refused when red) under the named run profile of the base\'s .gstack/pregate.json with the merged tree as its tested tree (a red run refuses with QUEUE_LAND_MERGED_CHECKS; a run that cannot start, finish or be proved refuses with QUEUE_NOT_READY); it runs on CI, so it needs no --allow-repo-commands, never runs under --dry-run, and the branch is deleted whatever the outcome; with it merged_checks may be left out, and an older gstack ignores it with a warning. An unknown key under land is a warning, ignored.'; /** The keys this gstack reads under land; any other is a warning (lib/ship-policy.ts policyWarnings), never an error. */ export const LAND_KEYS: readonly string[] = ['merged_checks', 'docs_only_skip', 'merge_commit_paths', 'merged_ci']; diff --git a/lib/land-merged-ci.ts b/lib/land-merged-ci.ts index f1bd306a1..c4108986f 100644 --- a/lib/land-merged-ci.ts +++ b/lib/land-merged-ci.ts @@ -3,9 +3,15 @@ * merge base, the pin's own pull_request runs never tested the merged tree, and land.merged_checks runs only what land's * machine can afford. So land pushes the merged commit to a scratch branch, gstack-land/, dispatches the policy's * workflow there, waits for that run, and lands only when lib/run-evidence.ts verifyRun accepts it under the named run - * profile from the base's .gstack/pregate.json, with the merged commit as its head and the merged tree as its tested - * tree. The scratch branch is deleted whatever the outcome. The run executes on CI runners, so no repo command runs on - * land's machine and it needs no --allow-repo-commands. + * profile from the base's .gstack/pregate.json, with the run's head as its head and the merged tree as its tested tree. + * Each land builds a new merged commit, so before dispatching land looks for a run an earlier land started (any + * workflow_dispatch run on gstack-land/, or one at this merged commit) whose head commit has the merged tree: the + * newest one that was not cancelled decides. A finished green run that verifyRun accepts lands with no dispatch, a run + * still going is waited on, and a red one refuses; only a finished green run that no longer proves the tree (an expired + * artifact, past the profile's max age) falls through to a fresh dispatch. GitHub keeps a run and its record of the + * branch after the branch is deleted, and serves its head commit by sha, so the scratch branch is deleted whatever the + * outcome. The run executes on CI runners, so no repo command runs on land's machine and it needs no + * --allow-repo-commands. */ import { git, type QueueFailure } from '../crew/lib/ship-queue-gate'; import { repoSlug } from '../crew/lib/ship-queue-train-github'; @@ -23,36 +29,60 @@ export interface CiDeps { dispatch(workflow: string, branch: string): string | null; /** The workflow's workflow_dispatch runs at the commit, newest first. */ runsAt(workflow: string, commit: string): ApiRun[]; + /** The workflow's workflow_dispatch runs on the branch, newest first, including runs on a branch since deleted. */ + runsOn(workflow: string, branch: string): ApiRun[]; run(id: number): ApiRun; verify(id: number): { ok: true; head: string; tree: string } | { ok: false; detail: string }; sleep(ms: number): void; now(): number; url(id: number): string; } -export type CiResult = { ok: true; line: string } | { ok: false; red: boolean; detail: string }; +/** `run`: the run the refusal is about: a red run, or one still going that the next land on the same merged tree waits on. */ +export type CiResult = { ok: true; line: string } | { ok: false; red: boolean; detail: string; run?: number }; +type CiInput = { pr: string; commit: string; tree: string; ci: MergedCi; timeoutMs?: number }; -/** 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 { +/** The newest workflow_dispatch run of `ci.workflow` on the scratch branch or at the merged commit whose head commit has the merged tree, unless it was cancelled. */ +function earlierRun(deps: CiDeps, o: CiInput, branch: string): ApiRun | undefined { + const runs = [...deps.runsAt(o.ci.workflow, o.commit), ...deps.runsOn(o.ci.workflow, branch).filter(r => r.head_branch === branch)]; + return runs.filter(r => r.event === 'workflow_dispatch' && r.head_commit?.tree_id === o.tree).sort((a, b) => b.id - a.id).find(r => r.conclusion !== 'cancelled'); +} + +/** Wait from `started` for `first` (or the run that appears at the merged commit) to finish, then its verdict. */ +function settle(deps: CiDeps, o: CiInput, branch: string, first: ApiRun | undefined, started: number): CiResult { + let run = first; + for (;;) { + run = run ? deps.run(run.id) : deps.runsAt(o.ci.workflow, o.commit)[0]; + if (run?.status === 'completed') break; + if (deps.now() - started >= (o.timeoutMs ?? CI_TIMEOUT_MS)) { + if (!run) return { ok: false, red: false, detail: `no ${o.ci.workflow} run appeared on ${branch} at ${o.commit.slice(0, 12)}` }; + return { ok: false, red: false, run: run.id, detail: `${o.ci.workflow} run ${deps.url(run.id)} is still ${run.status} after ${Math.round((deps.now() - started) / 60_000)} minutes; it tests the merged tree ${o.tree.slice(0, 12)}, so the next land onto the same base waits on this run instead of dispatching another` }; + } + deps.sleep(pollDelayMs(MIN_POLL_MS)); + } + const at = `${o.ci.workflow} run ${deps.url(run.id)} on the merged tree ${o.tree.slice(0, 12)}`; + if (run.conclusion !== 'success') return { ok: false, red: true, run: run.id, detail: `${at} concluded ${run.conclusion ?? 'unknown'}` }; + const v = deps.verify(run.id); + if (!v.ok) return { ok: false, red: false, detail: `${at} passed, but it does not prove the tree under ${o.ci.profile}: ${v.detail}` }; + if (v.head !== run.head_sha || v.tree !== o.tree) return { ok: false, red: false, detail: `${at} tested ${v.head.slice(0, 12)} (tree ${v.tree.slice(0, 12)}), not the merged commit ${o.commit.slice(0, 12)} or a commit with its tree` }; + const earlier = run.head_sha === o.commit ? '' : `; run by an earlier land at ${run.head_sha.slice(0, 12)}, not dispatched again`; + return { ok: true, line: `MERGED_CI: pass ${at} (profile ${o.ci.profile}${earlier})` }; +} + +/** The verdict of `ci.workflow` on the merged tree: an earlier land's run on that tree when there is one, else one new dispatch on the merged commit; red when the run itself failed, else land could not run or prove it. */ +export function runMergedCi(deps: CiDeps, o: CiInput): CiResult { const branch = landBranch(o.pr); + const earlier = earlierRun(deps, o, branch); + if (earlier) { + const r = settle(deps, o, branch, earlier, deps.now()); + if (r.ok || earlier.status !== 'completed' || earlier.conclusion !== 'success') { deps.remove(branch); return r; } + } 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 { const started = deps.now(); const sent = deps.dispatch(o.ci.workflow, branch); if (sent) return { ok: false, red: false, detail: `gh workflow run ${o.ci.workflow} --ref ${branch} failed: ${sent}` }; - let run: ApiRun | undefined; - for (;;) { - run = run ? deps.run(run.id) : deps.runsAt(o.ci.workflow, o.commit)[0]; - if (run?.status === 'completed') break; - if (deps.now() - started >= (o.timeoutMs ?? CI_TIMEOUT_MS)) return { ok: false, red: false, detail: run ? `${o.ci.workflow} run ${deps.url(run.id)} is still ${run.status} after ${Math.round((deps.now() - started) / 60_000)} minutes` : `no ${o.ci.workflow} run appeared on ${branch} at ${o.commit.slice(0, 12)}` }; - deps.sleep(pollDelayMs(MIN_POLL_MS)); - } - const at = `${o.ci.workflow} run ${deps.url(run.id)} on the merged tree ${o.tree.slice(0, 12)}`; - if (run.conclusion !== 'success') return { ok: false, red: true, detail: `${at} concluded ${run.conclusion ?? 'unknown'}` }; - const v = deps.verify(run.id); - if (!v.ok) return { ok: false, red: false, detail: `${at} passed, but it does not prove the tree under ${o.ci.profile}: ${v.detail}` }; - if (v.head !== o.commit || v.tree !== o.tree) return { ok: false, red: false, detail: `${at} tested ${v.head.slice(0, 12)} (tree ${v.tree.slice(0, 12)}), not the merged commit ${o.commit.slice(0, 12)}` }; - return { ok: true, line: `MERGED_CI: pass ${at} (profile ${o.ci.profile})` }; + return settle(deps, o, branch, undefined, started); } finally { deps.remove(branch); } @@ -73,6 +103,7 @@ export function ghCiDeps(ctx: QueueContext, remote: string, tip: string, ci: Mer remove: branch => { git(root, ['push', '-q', remote, `:refs/heads/${branch}`]); }, dispatch: (workflow, branch) => { const r = ctx.gh(['workflow', 'run', workflow, '--ref', branch]); return r.ok ? null : (r.err ?? r.out).trim().slice(0, 160) || 'no output'; }, runsAt: (workflow, commit) => { try { return api<{ workflow_runs?: ApiRun[] }>(`repos/${slug}/actions/workflows/${workflow}/runs?head_sha=${commit}&event=workflow_dispatch&per_page=20`).workflow_runs ?? []; } catch { return []; } }, + runsOn: (workflow, branch) => { try { return api<{ workflow_runs?: ApiRun[] }>(`repos/${slug}/actions/workflows/${workflow}/runs?branch=${encodeURIComponent(branch)}&event=workflow_dispatch&per_page=20`).workflow_runs ?? []; } catch { return []; } }, run: id => { try { return api(`repos/${slug}/actions/runs/${id}`); } catch { return { id, run_attempt: 1, status: 'unknown', conclusion: null, event: 'workflow_dispatch', head_sha: '' }; } }, verify: id => { const v = verifyRun(evidence, { repo: slug, runRef: String(id), profileName: ci.profile, profile: profile!, now: new Date() }); @@ -90,6 +121,8 @@ export function landMergedCi(ctx: QueueContext, o: { remote: string; tip: string if ('error' in deps) return { failure: { code: 'QUEUE_NOT_READY', message: `${o.moved}, and land cannot run land.merged_ci: ${deps.error}; nothing merged`, fix: 'fix what the message names, then rerun land' } }; const r = runMergedCi(deps, o); if (r.ok) return { line: r.line }; - if (r.red) return { failure: { code: 'QUEUE_LAND_MERGED_CHECKS', message: `${o.moved}; on the pin merged onto it, ${r.detail}`, fix: `read the failed job in that run; a flaky case gets one rerun of land; a real failure goes back to the lane, which merges the base into the branch, fixes it, runs /ship and gstack-ship-queue ready --pr ${o.pr} at the new head` } }; - return { failure: { code: 'QUEUE_NOT_READY', message: `${o.moved}, and land.merged_ci could not run or prove CI on the pin merged onto it: ${r.detail}; nothing merged`, fix: `fix what the message names, then rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin}` } }; + const rerun = `gstack-ship-queue land --pr ${o.pr} --pin ${o.pin}`; + if (r.red) return { failure: { code: 'QUEUE_LAND_MERGED_CHECKS', message: `${o.moved}; on the pin merged onto it, ${r.detail}`, fix: `read the failed job in that run; for a flaky case rerun the run once (gh run rerun ${r.run}), then rerun ${rerun}, which waits on its new attempt (a rerun of land alone finds the same red run and refuses again); a real failure goes back to the lane, which merges the base into the branch, fixes it, runs /ship and gstack-ship-queue ready --pr ${o.pr} at the new head` } }; + if (r.run !== undefined) return { failure: { code: 'QUEUE_NOT_READY', message: `${o.moved}, and land.merged_ci timed out waiting for CI on the pin merged onto it: ${r.detail}; nothing merged`, fix: `rerun ${rerun} at any time: while origin/main stays at ${o.tip.slice(0, 12)} it waits up to 45 more minutes on run ${deps.url(r.run)} (or lands at once when it already passed) instead of dispatching a new one` } }; + return { failure: { code: 'QUEUE_NOT_READY', message: `${o.moved}, and land.merged_ci could not run or prove CI on the pin merged onto it: ${r.detail}; nothing merged`, fix: `fix what the message names, then rerun ${rerun}` } }; } diff --git a/lib/run-evidence.ts b/lib/run-evidence.ts index 459e714ed..ecf082e0c 100644 --- a/lib/run-evidence.ts +++ b/lib/run-evidence.ts @@ -64,6 +64,7 @@ export interface ApiRun { id: number; run_attempt: number; status: string; conclusion: string | null; event: string; head_sha: string; path?: string; created_at?: string; run_started_at?: string; updated_at?: string; repository?: { full_name: string } | null; head_repository?: { full_name: string } | null; head_branch?: string | null; + head_commit?: { tree_id?: string } | null; } export interface ApiStep { number: number; name: string; conclusion: string | null; started_at?: string | null; completed_at?: string | null } export interface ApiJob { id?: number; name: string; conclusion: string | null; started_at?: string | null; completed_at?: string | null; steps?: ApiStep[] } diff --git a/test/land-merged-ci.test.ts b/test/land-merged-ci.test.ts index 2695c5499..6a9c98ee4 100644 --- a/test/land-merged-ci.test.ts +++ b/test/land-merged-ci.test.ts @@ -16,15 +16,16 @@ const COMMIT = 'c'.repeat(40), TREE = 't'.repeat(40); const CI = { workflow: 'free-tests.yml', profile: 'ci-reuse/free-tests' }; type Calls = string[]; -function fake(o: { runs?: ApiRun[][]; verify?: ReturnType; push?: string; dispatch?: string } = {}): { deps: CiDeps; calls: Calls } { +function fake(o: { runs?: ApiRun[][]; verify?: ReturnType; push?: string; dispatch?: string; earlier?: ApiRun[]; atCommit?: ApiRun[] } = {}): { deps: CiDeps; calls: Calls } { const calls: Calls = []; - let clock = 0, polls = 0; + let clock = 0, polls = 0, sent = false; const runs = o.runs ?? [[{ id: 7, run_attempt: 1, status: 'completed', conclusion: 'success', event: 'workflow_dispatch', head_sha: COMMIT }]]; const deps: CiDeps = { push: (c, b) => { calls.push(`push ${c.slice(0, 4)} ${b}`); return o.push ?? null; }, remove: b => { calls.push(`remove ${b}`); }, - dispatch: (w, b) => { calls.push(`dispatch ${w} ${b}`); return o.dispatch ?? null; }, - runsAt: () => runs[Math.min(polls++, runs.length - 1)] ?? [], + dispatch: (w, b) => { calls.push(`dispatch ${w} ${b}`); sent = true; return o.dispatch ?? null; }, + runsAt: () => (sent ? runs[Math.min(polls++, runs.length - 1)] ?? [] : o.atCommit ?? []), + runsOn: (w, b) => { calls.push(`runsOn ${w} ${b}`); return o.earlier ?? []; }, run: id => { const r = runs[Math.min(polls++, runs.length - 1)]?.[0]; return r ?? { id, run_attempt: 1, status: 'queued', conclusion: null, event: 'workflow_dispatch', head_sha: COMMIT }; }, verify: () => o.verify ?? { ok: true, head: COMMIT, tree: TREE }, sleep: ms => { clock += ms; }, @@ -34,6 +35,7 @@ function fake(o: { runs?: ApiRun[][]; verify?: ReturnType; pus return { deps, calls }; } const run = (deps: CiDeps, timeoutMs?: number) => runMergedCi(deps, { pr: '42', commit: COMMIT, tree: TREE, ci: CI, timeoutMs }); +const noLookup = (calls: Calls) => calls.filter(c => !c.startsWith('runsOn ')); const queued: ApiRun = { id: 7, run_attempt: 1, status: 'in_progress', conclusion: null, event: 'workflow_dispatch', head_sha: COMMIT }; describe('land.merged_ci', () => { @@ -41,7 +43,7 @@ describe('land.merged_ci', () => { const { deps, calls } = fake({ runs: [[], [queued], [queued], [{ ...queued, status: 'completed', conclusion: 'success' }]] }); const r = run(deps); expect(r).toEqual({ ok: true, line: 'MERGED_CI: pass free-tests.yml run https://example.invalid/runs/7 on the merged tree tttttttttttt (profile ci-reuse/free-tests)' }); - expect(calls).toEqual(['push cccc gstack-land/42', 'dispatch free-tests.yml gstack-land/42', 'remove gstack-land/42']); + expect(noLookup(calls)).toEqual(['push cccc gstack-land/42', 'dispatch free-tests.yml gstack-land/42', 'remove gstack-land/42']); }); test('a red run refuses as red, naming its conclusion, and the branch is still deleted', () => { @@ -74,7 +76,7 @@ describe('land.merged_ci', () => { expect(sent.calls.at(-1)).toBe('remove gstack-land/42'); const pushed = fake({ push: 'rejected' }); expect(run(pushed.deps)).toMatchObject({ ok: false, red: false }); - expect(pushed.calls).toEqual(['push cccc gstack-land/42']); + expect(noLookup(pushed.calls)).toEqual(['push cccc gstack-land/42']); }); test('the policy key: { workflow, profile } only, a workflow file name and a run profile name; it may stand without merged_checks', () => { @@ -91,6 +93,107 @@ describe('land.merged_ci', () => { }); }); +describe('land.merged_ci reuses an earlier run on the merged tree (GST-3634)', () => { + const OLD = 'a'.repeat(40), OTHER = 'o'.repeat(40); + const earlier = (over: Partial): ApiRun => ({ id: 9, run_attempt: 1, status: 'completed', conclusion: 'success', event: 'workflow_dispatch', head_sha: OLD, head_branch: 'gstack-land/42', head_commit: { tree_id: TREE }, ...over }); + const provesOld = { ok: true as const, head: OLD, tree: TREE }; + + test('a finished green run an earlier land dispatched on gstack-land/, at another commit with the merged tree, lands with no push and no new dispatch', () => { + const green = earlier({}); + const { deps, calls } = fake({ earlier: [green], runs: [[green]], verify: provesOld }); + const r = run(deps); + expect(r.ok).toBe(true); + expect(r.ok ? r.line : '').toBe('MERGED_CI: pass free-tests.yml run https://example.invalid/runs/9 on the merged tree tttttttttttt (profile ci-reuse/free-tests; run by an earlier land at aaaaaaaaaaaa, not dispatched again)'); + expect(calls.some(c => c.startsWith('push ') || c.startsWith('dispatch '))).toBe(false); + expect(calls).toContain('runsOn free-tests.yml gstack-land/42'); + }); + + test('a run still in progress on the merged tree is adopted and waited on, not duplicated', () => { + const going = earlier({ status: 'queued', conclusion: null }); + const { deps, calls } = fake({ earlier: [going], runs: [[going], [{ ...going, status: 'in_progress' }], [{ ...going, status: 'completed', conclusion: 'success' }]], verify: provesOld }); + expect(run(deps).ok).toBe(true); + expect(calls.some(c => c.startsWith('push ') || c.startsWith('dispatch '))).toBe(false); + }); + + test('a red run on the merged tree refuses as red with no new dispatch, naming the run', () => { + const red = earlier({ conclusion: 'failure' }); + const { deps, calls } = fake({ earlier: [red], runs: [[red]], verify: provesOld }); + const r = run(deps); + expect(r).toMatchObject({ ok: false, red: true, run: 9 }); + expect(r.ok ? '' : r.detail).toContain('runs/9 on the merged tree tttttttttttt concluded failure'); + expect(calls.some(c => c.startsWith('dispatch '))).toBe(false); + }); + + test('the match is on the tree, never the commit: runs on other trees and cancelled runs are skipped, and the newest live run on the tree decides', () => { + const otherTree = fake({ earlier: [earlier({ id: 11, head_commit: { tree_id: OTHER } })] }); + expect(run(otherTree.deps).ok).toBe(true); + expect(otherTree.calls).toContain('dispatch free-tests.yml gstack-land/42'); + const cancelledOnly = fake({ earlier: [earlier({ conclusion: 'cancelled' })] }); + run(cancelledOnly.deps); + expect(cancelledOnly.calls).toContain('dispatch free-tests.yml gstack-land/42'); + const sameCommitOtherTree = fake({ earlier: [earlier({ head_sha: COMMIT, head_commit: { tree_id: OTHER } })] }); + run(sameCommitOtherTree.deps); + expect(sameCommitOtherTree.calls).toContain('dispatch free-tests.yml gstack-land/42'); + const green = earlier({ id: 45249277829 }); + const pr4753 = fake({ earlier: [earlier({ id: 45268196043, head_sha: 'b'.repeat(40), conclusion: 'cancelled' }), green], runs: [[green]], verify: provesOld }); + const r = run(pr4753.deps); + expect(r.ok ? r.line : r.detail).toContain('runs/45249277829'); + expect(pr4753.calls.some(c => c.startsWith('dispatch '))).toBe(false); + }); + + test('a finished green run that no longer proves the tree (an expired artifact, past max age) is no reason to refuse: land dispatches a fresh run', () => { + let verified = 0; + const green = earlier({}); + const { deps, calls } = fake({ earlier: [green], runs: [[green], [], [queued], [{ ...queued, status: 'completed', conclusion: 'success' }]] }); + let post = 0; + const runAt = deps.runsAt; + deps.runsAt = (w, c) => { if (calls.some(x => x.startsWith('dispatch '))) post++; return runAt(w, c); }; + deps.verify = () => (verified++ === 0 ? { ok: false, detail: 'run_stale: finished 30 hours ago' } : { ok: true, head: COMMIT, tree: TREE }); + expect(run(deps).ok).toBe(true); + expect(calls).toContain('dispatch free-tests.yml gstack-land/42'); + expect(post).toBe(2); + }); + + test('a run found at the merged commit itself counts, with no branch listing needed', () => { + const green = earlier({ head_sha: COMMIT, head_branch: 'gstack-land/42' }); + const { deps, calls } = fake({ atCommit: [green], runs: [[green]] }); + expect(run(deps).ok).toBe(true); + expect(calls.some(c => c.startsWith('push ') || c.startsWith('dispatch '))).toBe(false); + }); + + test('an adopted run that finishes green but cannot be proved refuses without dispatching', () => { + const going = earlier({ status: 'in_progress', conclusion: null }); + const { deps, calls } = fake({ earlier: [going], runs: [[going], [{ ...going, status: 'completed', conclusion: 'success' }]], verify: { ok: false, detail: 'artifact_missing: tested-tree' } }); + const r = run(deps); + expect(r).toMatchObject({ ok: false, red: false }); + expect(r.ok ? '' : r.detail).toContain('does not prove the tree'); + expect(calls.some(c => c.startsWith('push ') || c.startsWith('dispatch '))).toBe(false); + }); + + test('an adopted run that times out names that run and does not dispatch', () => { + const going = earlier({ status: 'queued', conclusion: null }); + const { deps, calls } = fake({ earlier: [going], runs: [[going]], verify: provesOld }); + expect(run(deps, 60_000)).toMatchObject({ ok: false, red: false, run: 9 }); + expect(calls.some(c => c.startsWith('push ') || c.startsWith('dispatch '))).toBe(false); + expect(calls.at(-1)).toBe('remove gstack-land/42'); + }); + + test('a timed-out wait names the run the next land adopts, and that land adopts it after the scratch branch was deleted', () => { + const going: ApiRun = { ...queued, id: 77, head_branch: 'gstack-land/42', head_commit: { tree_id: TREE } }; + const first = fake({ runs: [[going]] }); + const r1 = run(first.deps, 60_000); + expect(r1).toMatchObject({ ok: false, red: false, run: 77 }); + expect(r1.ok ? '' : r1.detail).toContain('runs/77 is still in_progress after'); + expect(r1.ok ? '' : r1.detail).toContain('the next land onto the same base waits on this run instead of dispatching another'); + expect(first.calls.at(-1)).toBe('remove gstack-land/42'); + const done = { ...going, status: 'completed', conclusion: 'success' }; + const second = fake({ earlier: [done], runs: [[done]] }); + const r2 = run(second.deps); + expect(r2.ok ? r2.line : r2.detail).toContain('runs/77 on the merged tree tttttttttttt'); + expect(second.calls.some(c => c.startsWith('push ') || c.startsWith('dispatch '))).toBe(false); + }); +}); + describe('queue git hooks', () => { test.skipIf(process.platform === 'win32')('a queue git call runs the checkout\'s hooks until land turns them off, so wave and train pushes keep the managed pre-push guard', () => { const gate = JSON.stringify(path.join(import.meta.dir, '..', 'crew', 'lib', 'ship-queue-gate.ts'));