diff --git a/.github/workflows/runner-image.yml b/.github/workflows/runner-image.yml index c98a189724e..633d63b5032 100644 --- a/.github/workflows/runner-image.yml +++ b/.github/workflows/runner-image.yml @@ -50,9 +50,11 @@ on: - scripts/standard-image-contract.mjs - docker/runner-image/** workflow_dispatch: + schedule: + - cron: "23 6 * * 3" # Least privilege: nothing at the workflow level. Only the publish job, which -# runs no build, can write to the registry or sign. +# runs no build, can write images to the registry or sign. permissions: {} # A newer push to a pull request replaces its older run. A master run has a @@ -64,13 +66,14 @@ concurrency: env: IMAGE: ghcr.io/paperclipai/paperclip-runner + BUILD_CACHE: ghcr.io/paperclipai/paperclip-runner-buildcache jobs: identity: name: Resolve the Runner image identity # A fork's own pushes do not run this workflow. Pull requests and manual # runs are not affected. - if: github.event_name != 'push' || (github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064') + if: (github.event_name != 'push' && github.event_name != 'schedule') || (github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064') runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -92,7 +95,7 @@ jobs: version: 9.15.4 run_install: false - # No dependency cache: a restored cache must not reach a published image. + # No dependency cache: the Actions cache must not reach a published image. - name: Setup Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 with: @@ -209,7 +212,7 @@ jobs: # Multi-arch by native runner, not QEMU, as in docker.yml. GitHub-hosted # runners: the protected release fleets admit only docker.yml on master. # - # These legs cannot write to the registry on any event, and they read and + # These legs cannot write to the registry on any event, and they # write no registry build cache. The install runs dependency lifecycle # scripts; the only token in the job can read packages, and only the lookup # step receives it. @@ -317,6 +320,8 @@ jobs: timeout-minutes: 30 run: | set -euo pipefail + cache=(--cache-from "type=registry,ref=$BUILD_CACHE:$ARCH") + if [ "$GITHUB_EVENT_NAME" = schedule ]; then cache=(--no-cache); fi for variant in full slim; do target=runner-artifacts if [ "$variant" = slim ]; then target=runner-artifacts-slim; fi @@ -328,7 +333,9 @@ jobs: --provenance=false --sbom=false \ --output "type=oci,dest=$RUNNER_TEMP/runner-image/$variant.oci.tar" \ --metadata-file "$RUNNER_TEMP/runner-image/$variant.metadata.json" \ + "${cache[@]}" \ . + cache=() done # The trees the checks below read are the layers of those archives, @@ -665,3 +672,59 @@ jobs: - name: Report images another run published first if: steps.early.outputs.exists == 'true' || steps.prepush.outputs.exists == 'true' || steps.gate.outputs.state == 'published' run: echo "\`$IMAGE:inputs-$DIGEST\` and its slim variant already exist. Another run published first; this run published nothing." >> "$GITHUB_STEP_SUMMARY" + + cache: + name: Write the build cache (${{ matrix.arch }}) + needs: [identity, publish] + if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs/heads/master' && needs.identity.outputs.lock == 'current' && needs.identity.outputs.exists != 'true' + strategy: + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + permissions: + contents: read + packages: write + concurrency: + group: runner-image-buildcache-${{ matrix.arch }} + cancel-in-progress: false + env: + ARCH: ${{ matrix.arch }} + PLATFORM: ${{ matrix.platform }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Login to GitHub Container Registry + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + with: + buildkitd-config-inline: | + [registry."docker.io"] + mirrors = ["mirror.gcr.io"] + + - name: Build the cached stages and write the cache + timeout-minutes: 20 + run: | + docker buildx build \ + --target runner-artifacts-runnerd \ + --platform "$PLATFORM" \ + --cache-from "type=registry,ref=$BUILD_CACHE:$ARCH" \ + --cache-to "type=registry,ref=$BUILD_CACHE:$ARCH,mode=max" \ + --output type=cacheonly \ + . diff --git a/doc/runner-image-contract.md b/doc/runner-image-contract.md index f744e5102d6..fe81f28ce36 100644 --- a/doc/runner-image-contract.md +++ b/doc/runner-image-contract.md @@ -216,6 +216,54 @@ repository and nowhere else. Other runs build and check, and publish nothing. - **First publication.** GitHub creates the package private. A maintainer must make it public once. +## Build cache + +The build legs read a registry build cache, +`ghcr.io/paperclipai/paperclip-runner-buildcache:`. It is a package of +its own and holds no image, so the image package holds only attested images. +It covers the stages that do not take the commit: the Rust toolchain and the +compiled daemon. The last stage takes the source revision as a build +argument, so every build runs it: the frozen install, the Runner's build and +the provider pack. Of the two build commands of a leg, only the first reads +the registry cache; the second reads what the first left in the job's builder. + +- **Effect.** BuildKit reuses a cached step only when the step and the + content of every file it reads are the same. The cache changes how long a + build takes, not what it builds, and the identity does not cover it. +- **Writer.** Only the `cache` job of the workflow writes it: on a `master` + push in this repository, after the publish job, for inputs that had no + image. When the image exists, nothing was built, and the run that published + it wrote the cache for those inputs. That job cannot sign, builds no further + than the daemon and never runs the install. Its token reaches the registry + login and no other step. It reads the cache it writes and keeps every step + of the cached stages (`mode=max`). Every other run reads the cache without + a credential and cannot write it. +- **Not on the way to an image.** No job waits for the `cache` job. When it + fails, the image is published and the next build is slower. +- **One write at a time.** The job holds one concurrency slot for each + architecture. GitHub keeps one waiting job in a group and cancels the one + that waited before it, so the newest write waits. A write from an older + commit that lands last costs time and nothing else. +- **No Actions cache.** The workflow never uses it: workflows that handle + pull requests can write it, and what they write must not reach a published + image. +- **Trust.** The daemon in a published image can come from a cached step + that an earlier `master` run compiled. Whoever can write the cache package + can decide what a later build reuses, so write access to it must stay as + narrow as write access to the image package. +- **Fetches.** A cached step does not run again. A download inside one (the + toolchain installer, the toolchain, the crates) is not repeated until the + inputs of that step change. +- **Weekly cold build.** A scheduled run builds both variants once a week + with no cache: it passes `--no-cache` and reads no registry cache. Like a + manual run, it resolves the lockfile, always builds, runs every check and + publishes nothing. A fork's schedule runs nothing. It fails when a download + is gone or when a step only works from the cache. +- **Missing cache.** A cache that does not exist or cannot be read is a + line in the build log, not a failure. The build then runs every step. +- **First write.** GitHub creates the cache package private. A maintainer + must make it public once. Until then every build runs cold. + ## Reading the transport archives alone The server needs the transport form of an older pack when a retained session diff --git a/server/src/__tests__/runner-image-workflow.test.ts b/server/src/__tests__/runner-image-workflow.test.ts index fba9724ad60..5cae746205d 100644 --- a/server/src/__tests__/runner-image-workflow.test.ts +++ b/server/src/__tests__/runner-image-workflow.test.ts @@ -1,4 +1,6 @@ -import { readFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; @@ -32,18 +34,84 @@ describe("Runner image workflow", () => { const steps = (job: string) => job.slice(job.indexOf("\n steps:\n")).split(/\n(?= {6}- )/).slice(1); const credential = /github\.token|secrets\.|GITHUB_TOKEN|REGISTRY_PASSWORD/; - it("lets only the publish job write to the registry or sign", () => { + it("lets only the publish job write images or sign, and only the cache job write the build cache, never the Actions cache", () => { expect(workflow).toMatch(/^permissions: \{\}$/m); - expect(Object.keys(jobs)).toEqual(["identity", "build", "publish"]); + expect(Object.keys(jobs)).toEqual(["identity", "build", "publish", "cache"]); expect(permissions(jobs.identity)).toEqual(["contents: read", "packages: read"]); expect(permissions(jobs.build)).toEqual(["contents: read", "packages: read"]); expect(permissions(jobs.publish)).toEqual(["contents: read", "packages: write", "id-token: write", "attestations: write"]); + expect(permissions(jobs.cache)).toEqual(["contents: read", "packages: write"]); for (const job of [jobs.identity, jobs.build]) { - expect(job).not.toMatch(/docker\/login-action|skopeo|imagetools create|actions\/attest|secrets\.|--push|push=true/); + expect(job).not.toMatch(/docker\/login-action|skopeo|imagetools create|actions\/attest|secrets\.|--push|push=true|cache-to/); } + expect(Object.keys(jobs).filter((name) => jobs[name].includes("cache-to"))).toEqual(["cache"]); + expect(jobs.cache).not.toMatch(/skopeo|imagetools|actions\/attest|--push|push=true|type=image|type=oci|upload-artifact/); + expect(workflow).not.toMatch(/type=gha|actions\/cache/); expect(workflow).not.toMatch(/pull_request_target|workflow_run/); }); + it("writes the build cache only for a master push in the canonical repository, never on the way to publication, with the token in the login step alone and no stage past the daemon", () => { + for (const job of [jobs.publish, jobs.cache]) { + expect(jobCondition(job).startsWith(`${canonical} && `)).toBe(true); + expect(jobCondition(job)).not.toContain("||"); + } + expect(jobCondition(jobs.cache)).toContain("needs.identity.outputs.lock == 'current'"); + for (const job of Object.values(jobs)) expect(/^ {4}needs: (.+)$/m.exec(job)?.[1] ?? "").not.toMatch(/\bcache\b/); + const withCredential = steps(jobs.cache).filter((step) => credential.test(step)); + expect(withCredential).toHaveLength(1); + expect(withCredential[0]).toContain("docker/login-action@"); + const building = steps(jobs.cache).filter((step) => step.includes("docker buildx build")); + expect(building).toHaveLength(1); + expect([...building[0].matchAll(/--target (\S+)/g)].map((match) => match[1])).toEqual(["runner-artifacts-runnerd"]); + expect(jobs.cache).not.toMatch(/pnpm|setup-node|node scripts/); + }); + + it("neither publishes nor writes the cache from a scheduled run, and runs nothing on a fork's schedule", () => { + expect(workflow).toMatch(/^ {2}schedule:\n {4}- cron: /m); + expect(canonical).toContain("github.event_name == 'push'"); + expect(jobs.build).toContain(`KEEP_IMAGE: \${{ ${canonical} }}`); + expect(jobCondition(jobs.identity)).toBe(`(github.event_name != 'push' && github.event_name != 'schedule') || (${repository})`); + }); + + const imageBuild = scripts.find((script) => script.includes('--target "$target"'))!; + const bashExpandsEmptyArrays = spawnSync("bash", ["-uc", 'empty=(); : "${empty[@]}"']).status === 0; + function imageBuildCommands(event: string) { + const directory = mkdtempSync(path.join(os.tmpdir(), "runner-image-build-")); + try { + writeFileSync(path.join(directory, "docker"), `#!/bin/sh\nprintf '%s\\n' "$*" >> "$RUNNER_TEMP/docker.log"\n`, { mode: 0o755 }); + const run = spawnSync("bash", ["--noprofile", "--norc", "-eo", "pipefail", "-c", imageBuild], { + cwd: directory, + encoding: "utf8", + env: { PATH: `${directory}${path.delimiter}${process.env.PATH}`, RUNNER_TEMP: directory, GITHUB_EVENT_NAME: event, GITHUB_SHA: "a".repeat(40), + BUILD_CACHE: "registry.invalid/buildcache", ARCH: "amd64", PLATFORM: "linux/amd64" }, + }); + expect(run.status, run.stderr).toBe(0); + return readFileSync(path.join(directory, "docker.log"), "utf8").trimEnd().split("\n"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + } + + it("replaces the cache read of the image build with --no-cache when the event is a schedule", () => { + expect(imageBuild).toContain('cache=(--cache-from "type=registry,ref=$BUILD_CACHE:$ARCH")\n if [ "$GITHUB_EVENT_NAME" = schedule ]; then cache=(--no-cache); fi\n'); + expect(imageBuild).toContain('"${cache[@]}"'); + }); + + it.skipIf(!bashExpandsEmptyArrays)("runs the image build step: a scheduled run builds with --no-cache and no cache read, any other run reads the cache (needs bash 4.4)", () => { + const cacheRead = "--cache-from type=registry,ref=registry.invalid/buildcache:amd64"; + const scheduled = imageBuildCommands("schedule"); + expect(scheduled.map((command) => /--target (\S+)/.exec(command)?.[1])).toEqual(["runner-artifacts", "runner-artifacts-slim"]); + expect(scheduled[0]).toContain(" --no-cache "); + for (const command of scheduled) expect(command).not.toContain("--cache-from"); + for (const event of ["pull_request", "push", "workflow_dispatch"]) { + const commands = imageBuildCommands(event); + expect(commands).toHaveLength(2); + expect(commands[0]).toContain(` ${cacheRead} `); + expect(commands[1]).not.toContain("--cache-from"); + for (const command of commands) expect(command).not.toContain("--no-cache"); + } + }); + it("publishes, and keeps the images for publication, only for a master push in the canonical repository", () => { expect(jobCondition(jobs.publish).startsWith(`${canonical} && `)).toBe(true); expect(jobs.publish).toContain(" needs: [identity, build]\n"); @@ -58,11 +126,11 @@ describe("Runner image workflow", () => { expect(recording[0]).not.toMatch(/KEEP_IMAGE/); expect(recording[0]).not.toMatch(credential); // A fork's own pushes run nothing; no job overrides a skipped or failed dependency. - expect(jobCondition(jobs.identity)).toBe(`github.event_name != 'push' || (${repository})`); + expect(jobCondition(jobs.identity)).toContain(`github.event_name != 'push' && `); expect(workflow).not.toMatch(/always\(\)|!cancelled\(\)|failure\(\)|continue-on-error/); }); - it("keeps the build legs free of credentials and of any registry build cache", () => { + it("keeps the build legs free of credentials, and lets them read the build cache but not write it", () => { // No job-level token: the block before the steps holds none, in any job. for (const job of Object.values(jobs)) expect(job.slice(0, job.indexOf("\n steps:\n"))).not.toMatch(credential); // The steps that build, check and smoke the image never receive one. @@ -74,7 +142,8 @@ describe("Runner image workflow", () => { expect(step).toContain("runner-image-publish.mjs publication-state"); expect(step).not.toContain("--strict"); } - expect(workflow).not.toMatch(/cache-to|cache-from|type=registry|type=gha/); + expect(jobs.build).toContain('--cache-from "type=registry,ref=$BUILD_CACHE:$ARCH"'); + expect(jobs.build).not.toMatch(/cache-to|docker login|docker\/login-action/); }); it("writes the full tag last, after a strict lookup and after both images are attested", () => {