diff --git a/.github/workflows/rollup.yml b/.github/workflows/rollup.yml new file mode 100644 index 00000000000..419361019ca --- /dev/null +++ b/.github/workflows/rollup.yml @@ -0,0 +1,81 @@ +name: Roll up stacks + +on: + workflow_dispatch: + inputs: + operation: + description: Create, resume, refresh source snapshots, or cancel a rollup + type: choice + options: [create, resume, refresh, cancel] + default: create + pull_requests: + description: 'Create: stack-tip PR numbers, e.g. 1571,1591 (dependencies included)' + type: string + rollup: + description: 'Resume/refresh/cancel: the existing rollup PR number' + type: string + base: + description: 'Create: destination branch' + type: choice + options: [master, develop] + default: master + queue: + description: 'Create: request merging once all conflicts are resolved' + type: boolean + default: false + pull_request_target: + types: [synchronize, closed, converted_to_draft] + +# Claiming/restoring source holds and refreshing integration branches must not +# race another rollup. Never cancel an operation halfway through publication. +concurrency: + group: github-rollup-management + cancel-in-progress: false + +permissions: {} + +jobs: + rollup: + if: >- + (github.event_name == 'workflow_dispatch' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) || + (github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name == github.repository && + ((startsWith(github.head_ref, 'rollup/') && github.event.action != 'converted_to_draft') || contains(github.event.pull_request.labels.*.name, 'rollup:source'))) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Create rollup app token + id: token + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ vars.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + permission-issues: write + permission-workflows: write + + # Execute only the trusted default-branch controller. The controller + # reads source commits as git data in a disposable separate checkout. + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: 24 + + - name: Configure git authentication + env: + GH_TOKEN: ${{ steps.token.outputs.token }} + run: gh auth setup-git + + - name: Manage rollup + env: + GH_TOKEN: ${{ steps.token.outputs.token }} + ROLLUP_OPERATION: ${{ inputs.operation }} + ROLLUP_TIPS: ${{ inputs.pull_requests }} + ROLLUP_NUMBER: ${{ inputs.rollup }} + ROLLUP_BASE: ${{ inputs.base }} + ROLLUP_QUEUE: ${{ inputs.queue }} + run: node scripts/github-rollup.mjs diff --git a/.mergify.yml b/.mergify.yml index 4b3ee02b1e8..a2081735352 100644 --- a/.mergify.yml +++ b/.mergify.yml @@ -25,6 +25,8 @@ scopes: - scripts/check-mergify-batch.test.mjs - scripts/check-mergify-queue-title.mjs - scripts/check-mergify-queue-title.test.mjs + - scripts/rollup-plan.mjs + - scripts/rollup-plan.test.mjs pr-policy: include: - .github/workflows/pr-title.yml @@ -36,6 +38,8 @@ scopes: - scripts/check-mergify-batch.test.mjs - scripts/check-mergify-queue-title.mjs - scripts/check-mergify-queue-title.test.mjs + - scripts/rollup-plan.mjs + - scripts/rollup-plan.test.mjs capacities: core: 2 pr-policy: 1 diff --git a/AGENTS.md b/AGENTS.md index 6a3103a84c7..cb0ce268555 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -85,6 +85,11 @@ endpoint. `master` (no stable-lane release check or release-impact check); the merge queue validates them in full. +The GitHub **Roll up stacks** workflow is the integration exception: it owns +synthetic `rollup/*` branches and publishes an aggregate PR while preserving +source commits. Use that workflow for rollup creation, refresh and cancellation; +do not rewrite the original stack branches or close their PRs manually. + ## Adding tests When adding tests, consider adding them to `crates/celox-test-suite` so diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0ef49c3e082..f513c48bdc3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -158,6 +158,51 @@ chain on the stack root, bottom-up. Queueing the top member queues every member below it. The batch validator resolves each member's root through the same marker chain, so a stack branch without it is still refused. +### Roll up conflicting stacks from GitHub + +Use **Actions → Roll up stacks → Run workflow** on `master`. Choose `create`, +enter the **tip PR numbers** of the stacks (for example `1571,1591`), and select +`master` or `develop` as the destination. The workflow follows the `Depends-On` +chains, deduplicates shared predecessors, and creates one rollup PR. Fork PRs, +drafts, dependency cycles and chains targeting another destination are rejected. +The existing Release App credentials are used, including workflow-write access +when the selected changes include workflow files. + +The workflow pins each source head, preserves the original commits, and adds +`rollup:source` and `release:hold` to its sources. Their branches are never +rewritten. Another managed rollup cannot claim the same sources. The rollup's +title is derived from the highest release impact of all included commits, +including sources still waiting on conflict resolution. `Release-As` commits +must use the release workflow instead. + +When two sources conflict, the rollup stays draft and links a **resolution PR**. +Open that PR and use GitHub's **Resolve conflicts** button, then commit the +resolution. This edits a copy of the source branch. The workflow automatically +resumes the rollup; repeat for any further conflicts. If the rollup itself +conflicts with its destination, use **Resolve conflicts** on the main rollup +PR. GitHub's editor supports simple text conflicts; for conflicts it cannot +edit, resolve and push only the indicated rollup/resolution branch locally. + +Once every source is integrated, the workflow marks the rollup ready for review. +Add `merge-ready` to queue it, or select the **queue** checkbox when creating it +to request queueing automatically when conflict resolution completes. The normal +combined-tree queue checks still apply. Source updates or conversion to draft +stop an active rollup; queue validation also checks the pins and commit ancestry. + +To recover an interrupted run, select `resume` and enter the **rollup PR number**. +To incorporate new source heads, select `refresh` with that number. Refresh +rebuilds the integration from the new snapshots; previous conflict resolutions +are not reused across changed snapshots. If stack membership changes, cancel +and create a new rollup. Sources merged as part of the rollup retain their +history; the rollup also carries closing references for source PR cleanup. + +To abandon it, select `cancel` with the rollup PR number, or close the rollup +PR. The controller closes its resolution PRs, removes `rollup:source`, and +restores only the holds it added. Holds present before the rollup stay in place. +The same cleanup runs after a successful merge. Source PRs are never closed by +the cancellation operation. Controller results and recovery errors appear in +the Actions run summary. + Lydite tests use the independent change-selected and daily cadence described below, including on Mergify queue draft PRs. The `Queue validation` merge condition requires the selected checks in `ci.yml` to pass; diff --git a/scripts/check-mergify-batch.mjs b/scripts/check-mergify-batch.mjs index 0bea49aafeb..e907bc063b4 100644 --- a/scripts/check-mergify-batch.mjs +++ b/scripts/check-mergify-batch.mjs @@ -1,6 +1,7 @@ import { readFileSync } from "node:fs"; import { pathToFileURL } from "node:url"; import { isConventionalPrTitle } from "./check-pr-title.mjs"; +import { validateRollupSources } from "./rollup-plan.mjs"; import { githubJson, loadPullRequestCommits, @@ -140,6 +141,7 @@ export async function validateBatch( if (errors.length) throw new Error(`#${sourceNumber}: ${errors.join("; ")}`); } + await validateRollupSources(repository, source, api); } return numbers; } diff --git a/scripts/check-mergify-batch.test.mjs b/scripts/check-mergify-batch.test.mjs index bd0f701f5c6..d82453e7465 100644 --- a/scripts/check-mergify-batch.test.mjs +++ b/scripts/check-mergify-batch.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { renderBody } from "./rollup-plan.mjs"; import { batchPullRequestNumbers, stackDependency, @@ -72,6 +73,24 @@ test("validates every source PR against policy from the exact batch tree", async assert.ok(f.calls.includes("/repos/o/r/pulls/13")); }); +test("queue batches reject stale rollup source snapshots", async () => { + const f = fixture(); + const pinned = "d".repeat(40); + f.input.metadata = { pull_requests: [{ number: 12 }] }; + Object.assign(f.source, { number: 12, head: { sha: sourceSha, ref: "rollup/123", repo: { full_name: "o/r" } }, + body: renderBody({ repository: "o/r", id: "123", base: "master", baseSha, + tips: [34], queue: true, sources: [{ number: 34, sha: pinned, heldBefore: false }] }, "Ready") }); + let head = pinned; + const api = async (path) => { + if (path === "/repos/o/r/pulls/34") return { state: "open", head: { sha: head, repo: { full_name: "o/r" } } }; + if (path === `/repos/o/r/compare/${pinned}...${sourceSha}`) return { status: "ahead" }; + return f.api(path); + }; + assert.deepEqual(await validateBatch(f.input, api, f.commits, f.policy), [12]); + head = "e".repeat(40); + await assert.rejects(validateBatch(f.input, api, f.commits, f.policy), /source #34 changed/); +}); + test("rejects spoofed batch authors, forks, stale heads, and non-drafts", async () => { for (const mutate of [ (f) => (f.batch.user.login = "someone"), diff --git a/scripts/github-rollup.mjs b/scripts/github-rollup.mjs new file mode 100644 index 00000000000..f3730b431d7 --- /dev/null +++ b/scripts/github-rollup.mjs @@ -0,0 +1,554 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, appendFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { stackDependency } from "./check-mergify-batch.mjs"; +import { commitReleaseImpact } from "./check-pr-release-impact.mjs"; +import { + pullNumbers, + readPlan, + renderBody, + rollupBranch, + resolutionBranch, + sourceLabel, + validatePlan, +} from "./rollup-plan.mjs"; + +export async function github(path, method = "GET", body) { + return JSON.parse( + execFileSync( + "gh", + [ + "api", + path, + "--method", + method, + ...(body === undefined ? [] : ["--input", "-"]), + ], + { + encoding: "utf8", + maxBuffer: 16 * 1024 * 1024, + input: body === undefined ? undefined : JSON.stringify(body), + }, + ) || "null", + ); +} + +export async function collectSources(repository, tips, base, api = github) { + const sources = new Map(); + async function visit(number, path = new Set()) { + if (path.has(number) || path.size >= 20) + throw new Error("Cyclic or overdeep stack"); + if (sources.has(number)) return sources.get(number); + const pull = await api(`/repos/${repository}/pulls/${number}`); + if ( + pull.state !== "open" || + pull.draft || + pull.head?.repo?.full_name !== repository || + pull.base?.repo?.full_name !== repository || + !/^[0-9a-f]{40}$/.test(pull.head?.sha ?? "") || + pull.head.ref.startsWith("rollup/") || + pull.head.ref.startsWith("mergify/") + ) + throw new Error( + `Source #${number} must be an open, non-draft PR in this repository`, + ); + if (pull.base.ref !== base) { + const below = stackDependency(repository, pull.body); + if (!pull.base.ref.startsWith("stack/") || !below) + throw new Error( + `Source #${number} does not target ${base} or a recognized stack`, + ); + const parent = await visit(below, new Set([...path, number])); + if (parent.head !== pull.base.ref) + throw new Error(`Source #${number} has a mismatched dependency branch`); + } + const source = { + number, + sha: pull.head.sha, + head: pull.head.ref, + title: pull.title, + heldBefore: pull.labels.some((l) => l.name === "release:hold"), + }; + sources.set(number, source); + if (sources.size > 100) throw new Error("Rollup exceeds 100 sources"); + return source; + } + for (const tip of tips) await visit(tip); + return [...sources.values()]; +} + +// Only git is run in this disposable checkout. Source hooks, build scripts and +// workflow files are never executed with the app's write token. +export function gitRunner(cwd) { + const git = (...args) => + execFileSync("git", ["-c", "core.hooksPath=/dev/null", ...args], { + cwd, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + stdio: ["pipe", "pipe", "pipe"], + env: { + ...process.env, + GIT_TERMINAL_PROMPT: "0", + GIT_MERGE_AUTOEDIT: "no", + }, + }).trim(); + git.ancestor = (a, b) => { + const result = spawnSync("git", ["merge-base", "--is-ancestor", a, b], { + cwd, + }); + if (result.status === 0) return true; + if (result.status === 1) return false; + throw new Error(`Cannot compare git ancestry: ${result.stderr}`); + }; + git.merge = (sha, message) => { + if (git.ancestor(sha, "HEAD")) return true; + try { + git("merge", "--no-ff", "--no-edit", "-m", message, sha); + return true; + } catch (error) { + if (!git("diff", "--name-only", "--diff-filter=U")) throw error; + git("merge", "--abort"); + return false; + } + }; + return git; +} + +export function assemble( + plan, + git, + { currentHead, baseSha, resolution = () => null }, +) { + git("checkout", "--detach", currentHead ?? plan.sources[0].sha); + if (!git.merge(baseSha, "chore(rollup): incorporate destination branch")) + return { head: git("rev-parse", "HEAD"), conflict: "base" }; + for (const source of plan.sources) { + if (git.ancestor(source.sha, "HEAD")) continue; + const head = git("rev-parse", "HEAD"); + const resolved = resolution(source, head); + // A resolution must include both pinned source and this exact accumulator. + // A stale helper branch cannot undo a later source or base update. + const candidate = + resolved && + git.ancestor(head, resolved) && + git.ancestor(source.sha, resolved) + ? resolved + : source.sha; + if (!git.merge(candidate, `chore(rollup): incorporate #${source.number}`)) + return { head, conflict: source.number }; + } + return { head: git("rev-parse", "HEAD"), conflict: null }; +} + +function hasLabel(pull, label) { + return pull.labels.some((l) => l.name === label); +} + +export async function manageRollup( + input, + { api = github, cwd, gitFactory = gitRunner, summarize = console.log } = {}, +) { + const { repository } = input; + if (!/^[\w.-]+\/[\w.-]+$/.test(repository)) + throw new Error("Invalid repository"); + if (!["create", "resume", "refresh", "cancel"].includes(input.operation)) + throw new Error("Invalid rollup operation"); + if (input.operation === "create" && input.number) + throw new Error("Leave the rollup PR number blank when creating a rollup"); + const prefix = `/repos/${repository}`; + const pulls = []; + for (let page = 1; ; page++) { + const batch = await api( + `${prefix}/pulls?state=open&per_page=100&page=${page}`, + ); + pulls.push(...batch); + if (batch.length < 100) break; + } + const rerun = + input.operation === "create" && + pulls.find( + (p) => + p.head.ref === `rollup/${input.id}` && + p.head.repo.full_name === repository, + ); + let pull = input.number + ? await api(`${prefix}/pulls/${input.number}`) + : (rerun ?? null); + if (rerun) input = { ...input, operation: "resume" }; + let plan = pull ? readPlan(pull.body, repository) : null; + if ( + pull && + (!plan || + pull.head.repo.full_name !== repository || + pull.head.ref !== rollupBranch(plan) || + pull.base.ref !== plan.base) + ) + throw new Error("Not a managed rollup PR"); + + const label = async (number, name, add) => { + if (add) + await api(`${prefix}/issues/${number}/labels`, "POST", { + labels: [name], + }); + else { + const current = await api(`${prefix}/pulls/${number}`); + if (hasLabel(current, name)) + await api( + `${prefix}/issues/${number}/labels/${encodeURIComponent(name)}`, + "DELETE", + ); + } + }; + const draft = async (value) => { + if (pull.draft === value) return; + const mutation = value + ? "convertPullRequestToDraft" + : "markPullRequestReadyForReview"; + const response = await api("graphql", "POST", { + query: `mutation { ${mutation}(input:{pullRequestId:${JSON.stringify(pull.node_id)}}) { pullRequest { id } } }`, + }); + if (response.errors?.length) + throw new Error("Cannot change rollup draft state"); + pull.draft = value; + }; + const cleanup = async () => { + // Only holds this workflow added are released. Pre-existing holds survive. + for (const source of plan.sources) { + await label(source.number, sourceLabel, false); + if (!source.heldBefore) await label(source.number, "release:hold", false); + } + for (const helper of pulls.filter( + (p) => + p.base.ref === rollupBranch(plan) && + p.head.ref.startsWith(`rollup/resolve-${plan.id}/`), + )) + await api(`${prefix}/pulls/${helper.number}`, "PATCH", { + state: "closed", + }); + }; + if (input.operation === "cancel" || pull?.state === "closed") { + if (!plan) throw new Error("A rollup PR number is required"); + await label(pull.number, "merge-ready", false); + if (pull.state === "open") + await api(`${prefix}/pulls/${pull.number}`, "PATCH", { state: "closed" }); + await cleanup(); + summarize(`Rollup #${pull.number} finished; source holds restored.`); + return; + } + if (!plan && input.operation !== "create") + throw new Error("A rollup PR number is required"); + if (plan && input.operation === "create") + throw new Error("Use resume or refresh for an existing rollup"); + + const oldPlan = plan; + const queueRequested = plan?.queue || (pull && hasLabel(pull, "merge-ready")); + if (!plan || input.operation === "refresh") { + const tips = plan?.tips ?? pullNumbers(input.tips); + const base = plan?.base ?? input.base; + if (!["master", "develop"].includes(base)) + throw new Error("Invalid rollup base"); + const sources = await collectSources(repository, tips, base, api); + for (const source of sources) { + const original = oldPlan?.sources.find((s) => s.number === source.number); + if (original) source.heldBefore = original.heldBefore; + const current = await api(`${prefix}/pulls/${source.number}`); + if (hasLabel(current, sourceLabel) && !original) + throw new Error(`Source #${source.number} already belongs to a rollup`); + for (const other of pulls) { + if ( + !/^rollup\/[1-9]\d*$/.test(other.head.ref) || + other.number === pull?.number || + other.head.repo?.full_name !== repository + ) + continue; + const otherPlan = readPlan(other.body, repository); + if (otherPlan?.sources.some((s) => s.number === source.number)) + throw new Error( + `Source #${source.number} already belongs to rollup #${other.number}`, + ); + } + } + // A refresh cannot silently remove an old dependency and strand its hold. + if ( + oldPlan?.sources.some((s) => !sources.some((v) => v.number === s.number)) + ) + throw new Error( + "Stack membership changed; cancel this rollup and create a new one", + ); + plan = validatePlan( + { + repository, + id: oldPlan?.id ?? input.id, + base, + baseSha: (await api(`${prefix}/git/ref/heads/${base}`)).object.sha, + tips, + sources, + queue: oldPlan?.queue ?? input.queue, + }, + repository, + ); + } + + const checkSources = async () => { + for (const source of plan.sources) { + const current = await api(`${prefix}/pulls/${source.number}`); + if ( + current.draft || + current.head?.sha !== source.sha || + current.head.repo.full_name !== repository || + (current.state !== "open" && !current.merged) + ) + throw new Error(`Source #${source.number} changed; run refresh`); + } + }; + // Stop an already queued rollup before refreshing or handling stale sources. + if (pull) { + await label(pull.number, "merge-ready", false); + await draft(true); + } + await checkSources(); + const directory = cwd ?? mkdtempSync(join(tmpdir(), "celox-rollup-")); + try { + const git = gitFactory(directory); + git("init", "--quiet"); + git("config", "user.name", "celox-rollup[bot]"); + git("config", "user.email", "celox-rollup[bot]@users.noreply.github.com"); + git("config", "commit.gpgsign", "false"); + git("remote", "add", "origin", `https://github.com/${repository}.git`); + const fetch = (sha) => { + git("fetch", "--quiet", "--no-tags", "origin", sha); + return git("rev-parse", "FETCH_HEAD"); + }; + const baseSha = (await api(`${prefix}/git/ref/heads/${plan.base}`)).object + .sha; + fetch(baseSha); + for (const source of plan.sources) fetch(source.sha); + const currentHead = + pull && input.operation !== "refresh" ? fetch(pull.head.sha) : null; + const helpers = pulls.filter( + (p) => + p.base.ref === rollupBranch(plan) && + p.head.repo.full_name === repository, + ); + const result = assemble(plan, git, { + currentHead, + baseSha, + resolution: (source, head) => { + const branch = `${resolutionBranch(plan, source.number)}-${head.slice(0, 12)}`; + const helper = helpers.find((p) => p.head.ref === branch); + return helper ? fetch(helper.head.sha) : null; + }, + }); + if (git.ancestor(result.head, baseSha)) + throw new Error( + "All selected changes are already on the destination branch", + ); + const messages = git( + "log", + "--format=%B%x00", + `${baseSha}..${result.head}`, + ).split("\0"); + // All source commits, including any not yet integrated, determine the title. + for (const source of plan.sources) + messages.push( + source.title ?? "", + ...git("log", "--format=%B%x00", `${baseSha}..${source.sha}`).split( + "\0", + ), + ); + const impact = Math.max( + 0, + ...messages.map((m) => + commitReleaseImpact(m.trim(), { + preMajor: false, + bumpPatchForMinorPreMajor: false, + }), + ), + ); + if (impact > 3) + throw new Error("Rollups cannot include forced Release-As commits"); + const type = ["chore", "fix", "feat", "feat"][impact]; + const title = `${type}(rollup)${impact === 3 ? "!" : ""}: roll up stacks ${plan.tips.map((n) => `#${n}`).join(", ")}`; + await checkSources(); + if (!pull) { + // Serialization is repository-wide. This label is an ownership marker, + // separate from release:hold, which a source may already have. + await api(`${prefix}/labels`, "POST", { + name: sourceLabel, + color: "5319E7", + description: "Owned by a GitHub rollup", + }).catch(async () => { + // Existing labels are normal; other API failures must remain failures. + await api(`${prefix}/labels/${encodeURIComponent(sourceLabel)}`); + }); + } + if (pull && input.operation === "refresh") + await api(`${prefix}/pulls/${pull.number}`, "PATCH", { + title, + body: renderBody( + plan, + "Refreshing snapshots. Use resume if this operation is interrupted.", + ), + }); + const branch = rollupBranch(plan); + const unpublished = !pull + ? git("ls-remote", "origin", `refs/heads/${branch}`).split(/\s/)[0] + : ""; + git( + "push", + "--quiet", + `--force-with-lease=refs/heads/${branch}:${pull?.head.sha ?? unpublished}`, + "origin", + `${result.head}:refs/heads/${branch}`, + ); + if (!pull) + pull = await api(`${prefix}/pulls`, "POST", { + head: branch, + base: plan.base, + title, + body: renderBody( + plan, + "Preparing rollup. Re-run this workflow if preparation is interrupted.", + ), + draft: true, + }); + // Publish the draft recovery record before claiming any source. Even a + // runner cancellation between label writes can then be resumed/cancelled + // from GitHub without leaving unowned holds behind. + for (const source of plan.sources) { + await label(source.number, sourceLabel, true); + await label(source.number, "release:hold", true); + } + let status; + if (result.conflict === "base") { + status = + "**Resolve conflicts on this draft rollup PR in GitHub.** The workflow resumes after the resolution is committed."; + } else if (result.conflict) { + const helperBranch = `${resolutionBranch(plan, result.conflict)}-${result.head.slice(0, 12)}`; + let helper = helpers.find((p) => p.head.ref === helperBranch); + if (!helper) { + const source = plan.sources.find((s) => s.number === result.conflict); + const existing = git( + "ls-remote", + "origin", + `refs/heads/${helperBranch}`, + ).split(/\s/)[0]; + // An orphan branch from an interrupted run is reusable only if it is + // still the exact source copy; never discard a user's resolution. + if (existing && existing !== source.sha) + throw new Error( + "Unpublished resolution branch changed; inspect it before retrying", + ); + git( + "push", + "--quiet", + `--force-with-lease=refs/heads/${helperBranch}:${existing}`, + "origin", + `${source.sha}:refs/heads/${helperBranch}`, + ); + helper = await api(`${prefix}/pulls`, "POST", { + head: helperBranch, + base: branch, + draft: true, + title: `chore(rollup): resolve #${source.number} into rollup ${plan.id}`, + body: `Resolve this PR's conflicts using GitHub's **Resolve conflicts** button, then commit the resolution. The rollup workflow resumes automatically. This branch is a copy of #${source.number} at ${source.sha}; the original stack is untouched.`, + }); + } + status = `**Waiting for conflict resolution in #${helper.number}.** Use its GitHub **Resolve conflicts** button and commit the resolution; this rollup resumes automatically.`; + } else + status = + "All pinned sources are integrated. Review the rollup and add `merge-ready` to request queue validation."; + const body = renderBody(plan, status); + await api(`${prefix}/pulls/${pull.number}`, "PATCH", { title, body }); + await checkSources(); + if (!result.conflict) { + await draft(false); + if (plan.queue || queueRequested) + await label(pull.number, "merge-ready", true); + } + summarize(`${pull.html_url}\n\n${status}`); + return { pull, plan, conflict: result.conflict }; + } finally { + if (!cwd) rmSync(directory, { recursive: true, force: true }); + } +} + +export async function eventTargets(repository, event, api = github) { + const number = event.pull_request?.number; + const ref = event.pull_request?.head?.ref ?? ""; + if (!number || event.pull_request.head.repo?.full_name !== repository) + return []; + if (/^rollup\/[1-9]\d*$/.test(ref)) + return event.action === "converted_to_draft" ? [] : [number]; + const helper = /^rollup\/resolve-([1-9]\d*)\//.exec(ref); + if (!helper && !hasLabel(event.pull_request, sourceLabel)) return []; + const result = []; + for (let page = 1; ; page++) { + const pulls = await api( + `/repos/${repository}/pulls?state=open&per_page=100&page=${page}`, + ); + for (const pull of pulls) { + if ( + !/^rollup\/[1-9]\d*$/.test(pull.head.ref) || + pull.head.repo.full_name !== repository + ) + continue; + const plan = readPlan(pull.body, repository); + if ( + plan && + (helper + ? plan.id === helper[1] + : plan.sources.some((s) => s.number === number)) + ) + result.push(pull.number); + } + if (pulls.length < 100) return result; + } +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(resolve(process.argv[1])).href +) { + const repository = process.env.GITHUB_REPOSITORY; + const summarize = (text) => { + console.log(text); + if (process.env.GITHUB_STEP_SUMMARY) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n`); + }; + try { + if (process.env.GITHUB_EVENT_NAME === "workflow_dispatch") { + const numbers = process.env.ROLLUP_NUMBER + ? pullNumbers(process.env.ROLLUP_NUMBER) + : []; + if (numbers.length > 1) + throw new Error("Specify exactly one rollup PR number"); + await manageRollup( + { + repository, + operation: process.env.ROLLUP_OPERATION, + tips: process.env.ROLLUP_TIPS ?? "", + base: process.env.ROLLUP_BASE, + number: numbers[0] ?? null, + id: process.env.GITHUB_RUN_ID, + queue: process.env.ROLLUP_QUEUE === "true", + }, + { summarize }, + ); + } else { + const event = JSON.parse( + readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"), + ); + for (const number of await eventTargets(repository, event)) + await manageRollup( + { repository, number, operation: "resume" }, + { summarize }, + ); + } + } catch (error) { + summarize(`Rollup stopped: ${error.message}`); + process.exitCode = 1; + } +} diff --git a/scripts/github-rollup.test.mjs b/scripts/github-rollup.test.mjs new file mode 100644 index 00000000000..53812a36ee1 --- /dev/null +++ b/scripts/github-rollup.test.mjs @@ -0,0 +1,412 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { execFileSync } from "node:child_process"; +import { + mkdtempSync, + mkdirSync, + readFileSync, + writeFileSync, + rmSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + collectSources, + manageRollup, + eventTargets, + gitRunner, +} from "./github-rollup.mjs"; +import { readPlan, validateRollupSources } from "./rollup-plan.mjs"; + +function pull(number, head, base = "master", body = "") { + return { + number, + node_id: `PR_${number}`, + state: "open", + merged: false, + draft: false, + title: "fix: source", + labels: [], + body, + head: { + ref: head, + sha: String(number).repeat(40), + repo: { full_name: "o/r" }, + }, + base: { ref: base, repo: { full_name: "o/r" } }, + }; +} + +test("stack expansion deduplicates shared predecessors and verifies branch ownership", async () => { + const pulls = [ + pull(1, "stack/a"), + pull(2, "stack/b", "stack/a", "Depends-On: https://github.com/o/r/pull/1"), + pull(3, "stack/c", "stack/a", "Depends-On: #1"), + ]; + const api = async (path) => + structuredClone(pulls.find((p) => path.endsWith(`/pulls/${p.number}`))); + assert.deepEqual( + (await collectSources("o/r", [2, 3], "master", api)).map((s) => s.number), + [1, 2, 3], + ); + for (const modify of [ + (p) => (p[1].body = "Depends-On: https://github.com/other/r/pull/1"), + (p) => (p[0].head.ref = "different"), + (p) => (p[0].head.repo.full_name = "fork/r"), + (p) => (p[0].draft = true), + (p) => (p[0].state = "closed"), + (p) => { + p[0].base.ref = "stack/b"; + p[0].body = "Depends-On: #2"; + }, + ]) { + const changed = structuredClone(pulls); + modify(changed); + await assert.rejects( + collectSources("o/r", [2], "master", async (path) => + changed.find((p) => path.endsWith(`/pulls/${p.number}`)), + ), + ); + } +}); + +// Exercise actual git merges, conflicts, resolution commits, refreshes and +// leases against a tiny local bare remote. Only GitHub's HTTP API is replaced. +test("GitHub rollup lifecycle preserves sources, resumes web resolutions, rejects stale heads and restores holds", async () => { + const root = mkdtempSync(join(tmpdir(), "celox-rollup-test-")); + const remote = join(root, "remote.git"); + const seed = join(root, "seed"); + mkdirSync(seed); + const git = gitRunner(seed); + const bare = (...args) => + execFileSync("git", ["--git-dir", remote, ...args], { + encoding: "utf8", + }).trim(); + try { + execFileSync("git", ["init", "--bare", "--quiet", remote]); + git("init", "--quiet"); + git("config", "user.name", "test"); + git("config", "user.email", "test@example.com"); + git("config", "commit.gpgsign", "false"); + writeFileSync(join(seed, "value"), "base\n"); + git("add", "."); + git("commit", "-qm", "chore: base"); + const base = git("rev-parse", "HEAD"); + git("remote", "add", "origin", remote); + git("push", "--quiet", "origin", "HEAD:refs/heads/master"); + const rows = new Map(); + for (const [number, content, message] of [ + [1, "first", "fix: first"], + [2, "second", "feat!: second"], + ]) { + git("checkout", "--detach", base); + writeFileSync(join(seed, "value"), `${content}\n`); + git("add", "."); + git("commit", "-qm", message); + git("push", "--quiet", "origin", `HEAD:refs/heads/source-${number}`); + const p = pull(number, `source-${number}`); + p.head.sha = git("rev-parse", "HEAD"); + rows.set(number, p); + } + rows.get(2).labels.push({ name: "release:hold" }); + let next = 50; + const api = async (path, method = "GET", body) => { + if (path === "graphql") { + const number = Number(/PR_(\d+)/.exec(body.query)[1]); + rows.get(number).draft = body.query.includes( + "convertPullRequestToDraft", + ); + return {}; + } + const route = path.replace("/repos/o/r", ""); + const snapshot = (p) => { + const result = structuredClone(p); + result.head.sha = bare("rev-parse", `refs/heads/${p.head.ref}`); + return result; + }; + if (route.startsWith("/pulls?")) + return [...rows.values()] + .filter((p) => p.state === "open") + .map(snapshot); + if (route.startsWith("/git/ref/heads/")) + return { + object: { sha: bare("rev-parse", `refs/heads/${route.slice(15)}`) }, + }; + if (route === "/labels") return body; + if (route.startsWith("/compare/")) { + const [a, b] = route.slice(9).split("..."); + const valid = + execFileSync("git", ["--git-dir", remote, "merge-base", a, b], { + encoding: "utf8", + }).trim() === a; + return { status: valid ? "ahead" : "diverged" }; + } + const issue = /^\/issues\/(\d+)\/labels(?:\/(.+))?$/.exec(route); + if (issue) { + const p = rows.get(Number(issue[1])); + if (method === "POST") + for (const name of body.labels) { + if (!p.labels.some((l) => l.name === name)) p.labels.push({ name }); + } + else if (method === "DELETE") + p.labels = p.labels.filter( + (l) => l.name !== decodeURIComponent(issue[2]), + ); + return null; + } + if (route === "/pulls" && method === "POST") { + const p = pull(next++, body.head, body.base, body.body); + Object.assign(p, { + title: body.title, + draft: body.draft, + html_url: `https://github.com/o/r/pull/${p.number}`, + }); + rows.set(p.number, p); + return snapshot(p); + } + const match = /^\/pulls\/(\d+)$/.exec(route); + if (match) { + const p = rows.get(Number(match[1])); + if (method === "PATCH") Object.assign(p, body); + return snapshot(p); + } + throw new Error(`Unexpected ${method} ${path}`); + }; + let attempts = 0; + const dependencies = () => { + const cwd = join(root, `attempt-${attempts++}`); + mkdirSync(cwd); + return { + cwd, + api, + summarize: () => {}, + gitFactory: (dir) => { + const run = gitRunner(dir); + return Object.assign( + (...args) => + run( + ...(args[0] === "remote" + ? ["remote", "add", "origin", remote] + : args), + ), + run, + ); + }, + }; + }; + const originalHeads = [rows.get(1).head.sha, rows.get(2).head.sha]; + // Simulate a runner/API interruption halfway through claiming sources. + // The draft plan must already exist and prevent a second rollup claiming + // sources even if the first ownership-label write never completed. + const interrupted = dependencies(); + interrupted.api = async (path, method, body) => { + if ( + path === "/repos/o/r/issues/1/labels" && + body?.labels?.includes("release:hold") + ) + throw new Error("Interrupted label write"); + return api(path, method, body); + }; + await assert.rejects( + manageRollup( + { + repository: "o/r", + operation: "create", + tips: "1,2", + base: "master", + id: "123", + queue: true, + }, + interrupted, + ), + /Interrupted/, + ); + assert.equal(rows.get(50).draft, true); + assert.equal( + readPlan(rows.get(50).body, "o/r").sources[0].heldBefore, + false, + ); + rows.get(1).labels = []; + await assert.rejects( + manageRollup( + { + repository: "o/r", + operation: "create", + tips: "1", + base: "master", + id: "124", + queue: false, + }, + dependencies(), + ), + /already belongs to rollup #50/, + ); + const first = await manageRollup( + { + repository: "o/r", + operation: "create", + tips: "1,2", + base: "master", + id: "123", + queue: true, + }, + dependencies(), + ); + assert.equal(first.conflict, 2); + assert.equal(rows.get(50).draft, true); + assert.equal(rows.get(50).title, "feat(rollup)!: roll up stacks #1, #2"); + assert.match(rows.get(50).body, /#51/); + assert.ok(rows.get(1).labels.some((l) => l.name === "release:hold")); + // Retrying a dispatch recovers the same PR and helper, and another rollup + // cannot claim already-held sources. + const retry = await manageRollup( + { + repository: "o/r", + operation: "create", + tips: "1,2", + base: "master", + id: "123", + queue: true, + }, + dependencies(), + ); + assert.equal(retry.pull.number, 50); + assert.equal(rows.size, 4); + await assert.rejects( + manageRollup( + { + repository: "o/r", + operation: "create", + tips: "1", + base: "master", + id: "124", + queue: false, + }, + dependencies(), + ), + /already belongs/, + ); + + // Model GitHub's Resolve conflicts commit on the copied source branch. + const helper = rows.get(51); + git("fetch", "--quiet", "origin", `refs/heads/${helper.head.ref}`); + git("checkout", "--detach", "FETCH_HEAD"); + git("fetch", "--quiet", "origin", "refs/heads/rollup/123"); + assert.equal(git.merge("FETCH_HEAD", "chore: attempt resolution"), false); + assert.throws(() => git("merge", "--no-ff", "--no-commit", "FETCH_HEAD")); + writeFileSync(join(seed, "value"), "first and second\n"); + git("add", "."); + git("commit", "-qm", "fix: resolve both changes"); + git("push", "--quiet", "origin", `HEAD:refs/heads/${helper.head.ref}`); + const targets = await eventTargets( + "o/r", + { action: "synchronize", pull_request: helper }, + api, + ); + assert.deepEqual(targets, [50]); + const resumed = await manageRollup( + { repository: "o/r", operation: "resume", number: 50 }, + dependencies(), + ); + assert.equal(resumed.conflict, null); + assert.equal(rows.get(50).draft, false); + assert.ok(rows.get(50).labels.some((l) => l.name === "merge-ready")); + assert.equal( + bare("show", "refs/heads/rollup/123:value"), + "first and second", + ); + for (const [i, n] of [1, 2].entries()) + assert.equal( + bare("rev-parse", `refs/heads/source-${n}`), + originalHeads[i], + ); + await validateRollupSources("o/r", await api("/repos/o/r/pulls/50"), api); + + git("checkout", "--detach", originalHeads[1]); + writeFileSync(join(seed, "new"), "updated\n"); + git("add", "."); + git("commit", "-qm", "fix: update source"); + git("push", "--quiet", "origin", "HEAD:refs/heads/source-2"); + await assert.rejects( + validateRollupSources("o/r", await api("/repos/o/r/pulls/50"), api), + /changed/, + ); + await assert.rejects( + manageRollup( + { repository: "o/r", operation: "resume", number: 50 }, + dependencies(), + ), + /changed/, + ); + assert.equal(rows.get(50).draft, true); + assert.ok(!rows.get(50).labels.some((l) => l.name === "merge-ready")); + const refreshed = await manageRollup( + { repository: "o/r", operation: "refresh", number: 50 }, + dependencies(), + ); + assert.equal(refreshed.conflict, 2); + assert.equal( + readPlan(rows.get(50).body, "o/r").sources[1].sha, + git("rev-parse", "HEAD"), + ); + assert.notEqual(rows.get(52).head.ref, helper.head.ref); + + // A destination update can conflict with the accumulator itself. In that + // case the main draft PR is the GitHub conflict editor, not a source PR. + git("checkout", "--detach", base); + writeFileSync(join(seed, "value"), "destination changed\n"); + git("add", "."); + git("commit", "-qm", "fix: change destination"); + git("push", "--quiet", "origin", "HEAD:refs/heads/master"); + const baseConflict = await manageRollup( + { repository: "o/r", operation: "resume", number: 50 }, + dependencies(), + ); + assert.equal(baseConflict.conflict, "base"); + assert.match( + rows.get(50).body, + /Resolve conflicts on this draft rollup PR/, + ); + assert.equal(rows.get(50).draft, true); + assert.deepEqual( + await eventTargets( + "o/r", + { + action: "converted_to_draft", + pull_request: await api("/repos/o/r/pulls/50"), + }, + api, + ), + [], + ); + await manageRollup( + { repository: "o/r", operation: "cancel", number: 50 }, + dependencies(), + ); + assert.equal(rows.get(50).state, "closed"); + assert.equal(rows.get(51).state, "closed"); + assert.equal(rows.get(52).state, "closed"); + assert.deepEqual(rows.get(1).labels, []); + assert.deepEqual(rows.get(2).labels, [{ name: "release:hold" }]); + assert.equal(rows.get(1).state, "open"); + assert.equal(rows.get(2).state, "open"); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("workflow uses trusted code and app credentials and does not evaluate dispatch text as shell", () => { + const workflow = readFileSync( + new URL("../.github/workflows/rollup.yml", import.meta.url), + "utf8", + ); + assert.match( + workflow, + /ref: \$\{\{ github.event.repository.default_branch \}\}/, + ); + assert.match(workflow, /persist-credentials: false/); + assert.match(workflow, /permission-workflows: write/); + assert.match(workflow, /cancel-in-progress: false/); + assert.match(workflow, /ROLLUP_TIPS: \$\{\{ inputs.pull_requests \}\}/); + assert.doesNotMatch(workflow, /run:.*\$\{\{/); +}); diff --git a/scripts/rollup-plan.mjs b/scripts/rollup-plan.mjs new file mode 100644 index 00000000000..802d52b0506 --- /dev/null +++ b/scripts/rollup-plan.mjs @@ -0,0 +1,133 @@ +import { createHash } from "node:crypto"; + +const marker = "", start); + if (end < 0 || body.indexOf(marker, start + marker.length) >= 0) + throw new Error("Invalid rollup metadata"); + return validatePlan( + JSON.parse( + Buffer.from(body.slice(start + marker.length, end), "base64").toString( + "utf8", + ), + ), + repository, + ); +} + +export function rollupBranch(plan) { + return `rollup/${plan.id}`; +} +export function resolutionBranch(plan, number) { + return `rollup/resolve-${plan.id}/${number}-${generation(plan)}`; +} + +export function renderBody(plan, status) { + return ( + `${marker}${Buffer.from(JSON.stringify(plan)).toString("base64")}\n-->\n\n` + + `Roll up stacks ${plan.tips.map((n) => `#${n}`).join(", ")} into \`${plan.base}\`.\n\n` + + `${status}\n\n` + + "Source PRs are held while this rollup is active. Their original commits are preserved. " + + "Use **Actions → Roll up stacks → Run workflow** to refresh or cancel this rollup. " + + "Cancellation restores holds added by the workflow.\n\n" + + "| Source PR | Pinned head |\n| --- | --- |\n" + + plan.sources.map((s) => `| #${s.number} | \`${s.sha}\` |`).join("\n") + + "\n\n" + + plan.sources.map((s) => `Closes #${s.number}`).join("\n") + ); +} + +// The queue calls this on trusted code before certifying the combined tree. +// A source update cannot silently make a rollup's pinned snapshot current. +export async function validateRollupSources(repository, pull, api) { + const plan = readPlan(pull.body, repository); + const managed = /^rollup\/[1-9]\d*$/.test(pull.head?.ref ?? ""); + if (!plan && !managed) return; + if ( + !plan || + pull.head?.ref !== rollupBranch(plan) || + pull.head?.repo?.full_name !== repository || + pull.base?.ref !== plan.base + ) + throw new Error("Rollup branch or base does not match its plan"); + for (const source of plan.sources) { + if (source.number === pull.number) + throw new Error("Rollup cannot contain itself"); + const current = await api(`/repos/${repository}/pulls/${source.number}`); + if ( + current.draft || + current.head?.sha !== source.sha || + current.head?.repo?.full_name !== repository || + (current.state !== "open" && !current.merged) + ) + throw new Error( + `Rollup source #${source.number} changed; refresh the rollup`, + ); + const comparison = await api( + `/repos/${repository}/compare/${source.sha}...${pull.head.sha}`, + ); + if (!["ahead", "identical"].includes(comparison.status)) + throw new Error(`Rollup is missing source #${source.number}`); + } +} diff --git a/scripts/rollup-plan.test.mjs b/scripts/rollup-plan.test.mjs new file mode 100644 index 00000000000..7d23189a92b --- /dev/null +++ b/scripts/rollup-plan.test.mjs @@ -0,0 +1,106 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + pullNumbers, + validatePlan, + readPlan, + renderBody, + generation, + validateRollupSources, +} from "./rollup-plan.mjs"; + +export function fixturePlan() { + return { + repository: "o/r", + id: "123", + base: "master", + baseSha: "a".repeat(40), + tips: [1, 2], + queue: false, + sources: [ + { number: 1, sha: "b".repeat(40), heldBefore: false }, + { number: 2, sha: "c".repeat(40), heldBefore: true }, + ], + }; +} + +test("rollup input and metadata reject ambiguous sources and invalid identity", () => { + assert.deepEqual(pullNumbers("#1, 2\n3"), [1, 2, 3]); + for (const value of [ + "", + "1,1", + "0", + "1,garbage", + "9007199254740992", + "1; echo bad", + ]) + assert.throws(() => pullNumbers(value)); + const plan = fixturePlan(); + const body = renderBody(plan, "Ready"); + assert.deepEqual(readPlan(body, "o/r"), plan); + assert.equal(readPlan("ordinary PR", "o/r"), null); + assert.throws(() => readPlan(body, "different/repo")); + assert.throws(() => readPlan(body + body, "o/r")); + for (const change of [ + (p) => p.sources.push(p.sources[0]), + (p) => (p.sources[0].sha = "main"), + (p) => (p.base = "feature/x"), + (p) => (p.tips = [9]), + (p) => (p.id = "../master"), + (p) => (p.sources[0].heldBefore = "false"), + ]) { + const invalid = fixturePlan(); + change(invalid); + assert.throws(() => validatePlan(invalid, "o/r")); + } + const updated = fixturePlan(); + updated.sources[1].sha = "d".repeat(40); + assert.notEqual(generation(updated), generation(plan)); +}); + +test("queue validation requires current source heads contained in the rollup", async () => { + const plan = fixturePlan(); + const pull = { + number: 50, + head: { + ref: "rollup/123", + repo: { full_name: "o/r" }, + sha: "d".repeat(40), + }, + base: { ref: "master" }, + body: renderBody(plan, "Ready"), + }; + const api = async (path) => { + if (path.includes("/compare/")) return { status: "ahead" }; + const source = plan.sources.find((s) => + path.endsWith(`/pulls/${s.number}`), + ); + return { + state: "open", + head: { sha: source.sha, repo: { full_name: "o/r" } }, + }; + }; + await validateRollupSources("o/r", pull, api); + await validateRollupSources("o/r", { head: { ref: "normal" } }, api); + for (const change of [ + (p, result) => result.head && (result.head.sha = "e".repeat(40)), + (p, result) => result.status && (result.status = "diverged"), + (p, result) => result.head && (result.state = "closed"), + (p, result) => result.head && (result.draft = true), + ]) { + await assert.rejects( + validateRollupSources("o/r", pull, async (path) => { + const result = await api(path); + change(path, result); + return result; + }), + ); + } + for (const altered of [ + { ...pull, body: "metadata removed" }, + { ...pull, base: { ref: "develop" } }, + { ...pull, head: { ...pull.head, repo: { full_name: "fork/r" } } }, + { ...pull, number: 1 }, + ]) + await assert.rejects(validateRollupSources("o/r", altered, api)); +});