mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The repository includes `.github/workflows/docker-merge-group.yml` and `scripts/merge-group-image.mjs` to pre-build production images in the GitHub merge queue so `.github/workflows/docker.yml` can promote verified bytes on `master` instead of rebuilding from scratch > - Currently, `docker.yml` skips merge-queue promotion whenever `needs.runner_image.outputs.mode == 'published'`, and `docker-merge-group.yml` builds the Runner inline on 4-core `ubuntu-latest` while waiting up to 15 minutes during promotion lookup > - With `RUNNER_IMAGE_CONSUME_ENABLED=true`, that meant enabling the merge queue would never promote pre-built images on normal commits > - This pull request wires read-only attested Runner image consumption into `docker-merge-group.yml`, records and verifies `runnerInputsDigest` in `scripts/merge-group-image.mjs`, routes canonical `amd64` merge-group builds to `cloud-release-32`, parallelizes disk cleanup, caps promotion wait to 3 minutes, and allows `docker.yml` to promote verified merge-queue images when `runner_image` resolves to `published` > - The benefit is enabling fast pre-merge image promotion for merge-queue commits without weakening attestation, Runner-digest matching, or credential isolation ## Linked Issues or Issue Description **What existing behavior does this improve?** Pre-merge Docker image building and promotion across `.github/workflows/docker-merge-group.yml`, `scripts/merge-group-image.mjs`, and `.github/workflows/docker.yml`. **Subsystem affected** Cross-cutting (multiple of the above) **Current behavior** `docker-merge-group.yml` builds the Runner inline on `ubuntu-latest` with serial disk cleanup, and `docker.yml` disables merge-queue promotion whenever `needs.runner_image.outputs.mode == 'published'`. `scripts/merge-group-image.mjs` also waits up to 15 minutes for an in-flight merge-group run. **Proposed behavior** `docker-merge-group.yml` resolves an already-published Runner image (non-blocking lookup, read-only permissions, `gh attestation verify`), runs `amd64` on `vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32'`, skips unnecessary disk cleanup / runs cleanup in parallel, and records `runnerInputsDigest` in `record.json`. `docker.yml` attempts merge-queue promotion regardless of whether `runner_image` resolved `published` or `inline`, passing `RUNNER_INPUTS_DIGEST` to `merge-group-image.mjs verify` so promotion only succeeds when the merge-group image used the exact same Runner inputs digest. Promotion wait is capped at 3 minutes so `docker.yml` falls back quickly to building from source if a merge-group build is still running. **Reason and benefit** Makes merge-queue pre-built image promotion work with published Runner images so queued commits can promote verified bytes to GHCR instead of rebuilding after merge. **Breaking changes** None. ## What Changed - Added a read-only `runner_image` resolution and attestation verification job to `.github/workflows/docker-merge-group.yml` (non-blocking lookup, `persist-credentials: false`, SHA-pinned actions, no secrets or registry writes). - Routed canonical `amd64` merge-group builds in `docker-merge-group.yml` to `vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32'`, skipped lockfile refresh when using a published Runner, parallelized `Free runner disk` with a `>= 50 GiB` skip, and passed `build-contexts`, `build-args`, and `labels` into `Build image archive`. - Updated `scripts/merge-group-image.mjs` to record and verify `runnerInputsDigest`, include `scripts/runner-image-resolve.mjs` in `pipelineFiles`, and cap `findWaitMs` at 3 minutes. - Updated `.github/workflows/docker.yml` to output `inputs_digest` from `runner_image`, run `Find the merge-queue build of this commit` even when `mode == 'published'`, and verify `--runner-inputs-digest` before promoting. - Updated `scripts/merge-group-image.test.mjs`, `server/src/__tests__/docker-build-stamp.test.ts`, and `server/src/__tests__/docker-runner-workflows.test.ts`. ## Verification - `node --test scripts/merge-group-image.test.mjs scripts/__tests__/docker-cache-export-policy.test.mjs scripts/__tests__/release-verify-workflow.test.mjs scripts/macos-runner-runtime-workflow.test.mjs` (all passed) - Vitest: `server/src/__tests__/docker-build-stamp.test.ts` (18/18 passed), `server/src/__tests__/docker-runner-workflows.test.ts` (11/11 passed) ## Risks - Low risk. Promotion remains strictly fail-closed: `docker.yml` runs `$BEFORE:scripts/merge-group-image.mjs`, refuses promotion on any pipeline file change, verifies commit SHA, tree SHA, architecture, archive blob digests, and exact `runnerInputsDigest`, and falls back to building from source on any mismatch or timeout. ## Model Used - Gemini 3 Pro (Antigravity agent with tool use, shell execution, and local test verification) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
245 lines
13 KiB
JavaScript
245 lines
13 KiB
JavaScript
// Build-before-merge image handoff between the merge queue and master.
|
|
//
|
|
// A `merge_group` run of docker-merge-group.yml builds the production image for
|
|
// the exact merge-group commit with no registry credentials, probes it, and
|
|
// uploads an OCI archive plus a record of what it built. When the merge queue
|
|
// then fast-forwards master to that commit, docker.yml may push those exact
|
|
// bytes instead of rebuilding them. Anything that does not prove the match
|
|
// returns no promotion, and docker.yml falls back to its normal build.
|
|
import assert from "node:assert/strict";
|
|
import { execFileSync } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
import { appendFile, readFile, writeFile } from "node:fs/promises";
|
|
import { pathToFileURL } from "node:url";
|
|
|
|
export const repository = "paperclipai/paperclip";
|
|
export const repositoryId = 1170821064;
|
|
export const workflowPath = ".github/workflows/docker-merge-group.yml";
|
|
export const recordSchema = "paperclip/merge-group-image/v1";
|
|
export const artifactName = arch => `merge-group-image-${arch}`;
|
|
|
|
const architectures = ["amd64", "arm64"];
|
|
const indexTypes = ["application/vnd.oci.image.index.v1+json", "application/vnd.docker.distribution.manifest.list.v2+json"];
|
|
const manifestTypes = ["application/vnd.oci.image.manifest.v1+json", "application/vnd.docker.distribution.manifest.v2+json"];
|
|
// How long a master push waits for a merge-queue build that is still running.
|
|
// Capped at 3 minutes so a master push on a fast AWS runner falls back to
|
|
// building from source instead of stalling behind a slower merge-group leg.
|
|
const findWaitMs = 3 * 60_000;
|
|
const findPollMs = 15_000;
|
|
const fullSha = /^[a-f0-9]{40}$/;
|
|
const hex64 = /^[a-f0-9]{64}$/;
|
|
const digestPattern = /^sha256:[a-f0-9]{64}$/;
|
|
const sha256 = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
|
|
|
|
/**
|
|
* Choose the merge-queue build a master push may promote. Only a completed,
|
|
* successful run of this repository's merge-group workflow, on a merge-queue
|
|
* branch for master, for exactly this commit, qualifies.
|
|
*
|
|
* The commit must match, not only the tree: the image stamps the commit SHA
|
|
* (PAPERCLIP_BUILD_COMMIT, build-info.json, the provider pack revision). The
|
|
* merge queue lands the commit it tested for every merge method, squash
|
|
* included, by fast-forwarding master to it; a push that did not come through
|
|
* the queue has no matching run and builds from source.
|
|
*/
|
|
export function selectVerifiedRun({ sha, runs }) {
|
|
assert.match(sha ?? "", fullSha);
|
|
const eligible = runs.filter(run => run.head_sha === sha && run.event === "merge_group" && run.path === workflowPath &&
|
|
run.repository?.id === repositoryId && run.head_repository?.id === repositoryId &&
|
|
typeof run.head_branch === "string" && run.head_branch.startsWith("gh-readonly-queue/master/"));
|
|
if (eligible.length === 0) return { reason: "no merge-queue image build exists for this commit" };
|
|
const passed = eligible.filter(run => run.status === "completed" && run.conclusion === "success").sort((a, b) => b.id - a.id);
|
|
// The queue can land a commit while its image is still building. `pending`
|
|
// tells the caller that waiting can still produce a usable run.
|
|
if (passed.length === 0 && eligible.some(run => run.status !== "completed")) {
|
|
return { pending: true, reason: "the merge-queue image build for this commit did not finish in time" };
|
|
}
|
|
if (passed.length === 0) return { reason: "the merge-queue image build for this commit did not succeed" };
|
|
return { runId: passed[0].id };
|
|
}
|
|
|
|
/** The run's unexpired image artifact for one architecture, if there is exactly one. */
|
|
export function selectArtifact({ artifacts, arch }) {
|
|
assert.ok(architectures.includes(arch));
|
|
const matches = artifacts.filter(item => item.name === artifactName(arch) && !item.expired);
|
|
return matches.length === 1 ? { artifactId: matches[0].id } : { reason: `expected one unexpired ${artifactName(arch)} artifact, found ${matches.length}` };
|
|
}
|
|
|
|
/**
|
|
* The digest of the image an OCI archive holds, checked against the archive's
|
|
* own content-addressed blobs. `readEntry` returns the bytes of a tar entry.
|
|
*/
|
|
export function archiveImageDigest({ readEntry, arch }) {
|
|
assert.ok(architectures.includes(arch));
|
|
const layout = JSON.parse(readEntry("index.json").toString("utf8"));
|
|
assert.equal(layout.manifests?.length, 1, "The OCI archive must hold exactly one image");
|
|
const top = layout.manifests[0];
|
|
assert.match(top.digest ?? "", digestPattern);
|
|
const blob = name => {
|
|
const bytes = readEntry(`blobs/sha256/${name.slice("sha256:".length)}`);
|
|
assert.equal(sha256(bytes), name, `Archive blob ${name} does not match its digest`);
|
|
return JSON.parse(bytes.toString("utf8"));
|
|
};
|
|
const image = blob(top.digest);
|
|
const platformImages = indexTypes.includes(image.mediaType)
|
|
? (image.manifests ?? []).filter(item => item.platform?.os === "linux")
|
|
: [{ digest: top.digest, platform: undefined }];
|
|
assert.equal(platformImages.length, 1, "The OCI archive must hold exactly one Linux image");
|
|
const manifest = platformImages[0].digest === top.digest ? image : blob(platformImages[0].digest);
|
|
assert.ok(manifestTypes.includes(manifest.mediaType), "The OCI archive does not hold an image manifest");
|
|
const config = blob(manifest.config.digest);
|
|
assert.equal(config.os, "linux");
|
|
assert.equal(config.architecture, arch, `The OCI archive holds a ${config.architecture} image, not ${arch}`);
|
|
return top.digest;
|
|
}
|
|
|
|
/** What the merge-group build attests about the archive it uploads. */
|
|
export function createRecord({ sha, tree, arch, digest, runnerInputsDigest = "" }) {
|
|
assert.match(sha ?? "", fullSha);
|
|
assert.match(tree ?? "", fullSha);
|
|
assert.ok(architectures.includes(arch));
|
|
assert.match(digest ?? "", digestPattern);
|
|
assert.ok(runnerInputsDigest === "" || hex64.test(runnerInputsDigest), "runnerInputsDigest must be empty or 64 lowercase hex characters");
|
|
return {
|
|
schema: recordSchema,
|
|
repository,
|
|
sha,
|
|
tree,
|
|
arch,
|
|
digest,
|
|
...(runnerInputsDigest ? { runnerInputsDigest } : {}),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Prove the archive is the build of the tree this master push publishes. The
|
|
* commit SHA covers its tree; the tree is compared too, so a record can never
|
|
* vouch for different content under a reused name. When master resolved a
|
|
* published Runner image, the merge-group record must name the exact same
|
|
* Runner inputs digest (and vice versa for inline builds).
|
|
*/
|
|
export function verifyRecord({ record, sha, tree, arch, archiveDigest, runnerInputsDigest = "" }) {
|
|
assert.equal(record?.schema, recordSchema, "Unknown merge-group image record");
|
|
assert.equal(record.repository, repository);
|
|
assert.equal(record.sha, sha, "The merge-group build is for a different commit");
|
|
assert.equal(record.tree, tree, "The merge-group build is for a different tree");
|
|
assert.equal(record.arch, arch, "The merge-group build is for a different architecture");
|
|
assert.match(record.digest ?? "", digestPattern);
|
|
assert.equal(archiveDigest, record.digest, "The archive is not the image the merge-group build recorded");
|
|
assert.ok(runnerInputsDigest === "" || hex64.test(runnerInputsDigest), "runnerInputsDigest must be empty or 64 lowercase hex characters");
|
|
assert.equal(
|
|
record.runnerInputsDigest ?? "",
|
|
runnerInputsDigest,
|
|
"The merge-group build used a different Runner image than master resolved",
|
|
);
|
|
return record.digest;
|
|
}
|
|
|
|
/**
|
|
* Files that produce, promote or vouch for a merge-group image. The merge-group
|
|
* run uses the queued commits' own copies, so a push that changes any of them
|
|
* is built from source on master instead: promotion then trusts only a
|
|
* pipeline that master already ran before this push. docker.yml runs this
|
|
* check from the copy of this script in the push's `before` commit, so a push
|
|
* cannot remove the check it is subject to.
|
|
*/
|
|
export const pipelineFiles = [
|
|
workflowPath,
|
|
".github/workflows/docker.yml",
|
|
".github/workflows/macos-runner-runtime.yml",
|
|
"scripts/macos-runner-runtime.mjs",
|
|
"scripts/macos-runner-runtime-cache.mjs",
|
|
"scripts/runner-image-resolve.mjs",
|
|
"scripts/runner-image-publish.mjs",
|
|
"scripts/runner-image-identity.mjs",
|
|
"scripts/runner-image-layout.mjs",
|
|
"scripts/runner-image-oci.mjs",
|
|
"scripts/standard-image-contract.mjs",
|
|
"scripts/merge-group-image.mjs",
|
|
"scripts/assert-orphan-reaping.sh",
|
|
];
|
|
|
|
export function assertPipelineUnchanged(changedFiles) {
|
|
const changed = changedFiles.filter(file => pipelineFiles.includes(file));
|
|
assert.equal(changed.length, 0, `This push changes the merge-group image pipeline (${changed.join(", ")})`);
|
|
}
|
|
|
|
/** Pipeline files changed by everything this push landed: `since` (the push's `before`) to HEAD. */
|
|
export function changedSince(since, cwd = process.cwd()) {
|
|
assert.match(since ?? "", fullSha, "--since must be the push's full `before` SHA");
|
|
// Throws unless `since` is an ancestor: a push is a fast-forward of master.
|
|
execFileSync("git", ["merge-base", "--is-ancestor", since, "HEAD"], { cwd, stdio: "ignore" });
|
|
return execFileSync("git", ["diff", "--name-only", since, "HEAD", "--", ...pipelineFiles], { cwd, encoding: "utf8" }).split("\n").filter(Boolean);
|
|
}
|
|
const tarReader = archive => entry => execFileSync("tar", ["-xOf", archive, entry], { maxBuffer: 16 * 1024 * 1024 });
|
|
const gitTree = () => execFileSync("git", ["rev-parse", "HEAD^{tree}"], { encoding: "utf8" }).trim();
|
|
const option = name => {
|
|
const index = process.argv.indexOf(`--${name}`);
|
|
const value = index > 0 ? process.argv[index + 1] : undefined;
|
|
assert.ok(value, `--${name} is required`);
|
|
return value;
|
|
};
|
|
const optionalOption = name => {
|
|
const index = process.argv.indexOf(`--${name}`);
|
|
if (index <= 0) return "";
|
|
const value = process.argv[index + 1];
|
|
return value === undefined || value.startsWith("--") ? "" : value;
|
|
};
|
|
const output = async (key, value) => {
|
|
if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `${key}=${value}\n`);
|
|
console.log(`${key}=${value}`);
|
|
};
|
|
|
|
async function main(command) {
|
|
const sha = process.env.GITHUB_SHA;
|
|
const arch = option("arch");
|
|
if (command === "record") {
|
|
// Runs in the credential-free merge-group build.
|
|
assert.equal(process.env.GITHUB_EVENT_NAME, "merge_group", "Records are written only by merge-group builds");
|
|
const digest = archiveImageDigest({ readEntry: tarReader(option("archive")), arch });
|
|
const runnerInputsDigest = optionalOption("runner-inputs-digest");
|
|
await writeFile(option("out"), `${JSON.stringify(createRecord({ sha, tree: gitTree(), arch, digest, runnerInputsDigest }), null, 2)}\n`);
|
|
return output("digest", digest);
|
|
}
|
|
assert.ok(process.env.GITHUB_REPOSITORY === repository && process.env.GITHUB_REF === "refs/heads/master" &&
|
|
process.env.GITHUB_EVENT_NAME === "push", "Promotion runs only for canonical master pushes");
|
|
if (command === "find") {
|
|
const token = process.env.GITHUB_TOKEN;
|
|
assert.ok(token, "GITHUB_TOKEN is required");
|
|
const api = async path => {
|
|
const response = await fetch(`https://api.github.com/repos/${repository}${path}`, { redirect: "error",
|
|
headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(30_000) });
|
|
assert.ok(response.ok, `GitHub API ${path}: HTTP ${response.status}`);
|
|
return response.json();
|
|
};
|
|
// Publication waits for the exact-source gate in any case, so waiting here
|
|
// briefly for an almost-finished build costs nothing; past the deadline the
|
|
// push builds from source.
|
|
const deadline = Date.now() + findWaitMs;
|
|
let run;
|
|
for (;;) {
|
|
const { workflow_runs: runs } = await api(`/actions/workflows/docker-merge-group.yml/runs?event=merge_group&head_sha=${sha}&per_page=20`);
|
|
run = selectVerifiedRun({ sha, runs });
|
|
if (!run.pending || Date.now() >= deadline) break;
|
|
console.log("The merge-queue image build for this commit is still running. Waiting.");
|
|
await new Promise(resolve => setTimeout(resolve, findPollMs));
|
|
}
|
|
if (!run.runId) { console.log(`No promotion: ${run.reason}. Building from source.`); return; }
|
|
const { artifacts } = await api(`/actions/runs/${run.runId}/artifacts?per_page=100`);
|
|
const artifact = selectArtifact({ artifacts, arch });
|
|
if (!artifact.artifactId) { console.log(`No promotion: ${artifact.reason}. Building from source.`); return; }
|
|
return output("run_id", run.runId);
|
|
}
|
|
if (command === "verify") {
|
|
const directory = option("dir");
|
|
assertPipelineUnchanged(changedSince(option("since")));
|
|
const record = JSON.parse(await readFile(`${directory}/record.json`, "utf8"));
|
|
const archiveDigest = archiveImageDigest({ readEntry: tarReader(`${directory}/image.tar`), arch });
|
|
const runnerInputsDigest = optionalOption("runner-inputs-digest");
|
|
return output("digest", verifyRecord({ record, sha, tree: gitTree(), arch, archiveDigest, runnerInputsDigest }));
|
|
}
|
|
throw new Error(`Unknown command: ${command}`);
|
|
}
|
|
|
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main(process.argv[2]);
|