diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 1db18860a89..c78abd73b47 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -316,10 +316,17 @@ jobs: set -euo pipefail echo "Disk before cleanup:" df -h + avail_kb="$(df -Pk / | awk 'NR==2 {print $4}')" + if [ "${avail_kb:-0}" -ge 52428800 ]; then + echo "Root filesystem already has >= 50 GiB free; skipping cleanup." + exit 0 + fi - pnpm store prune || true - sudo apt-get clean || true - sudo rm -rf \ + pids=() + (pnpm store prune || true) & pids+=("$!") + (sudo apt-get clean || true) & pids+=("$!") + (docker system prune -af || true) & pids+=("$!") + for dir in \ /usr/share/dotnet \ /usr/share/swift \ /usr/local/lib/android \ @@ -328,8 +335,12 @@ jobs: /opt/ghc \ /opt/hostedtoolcache/CodeQL \ /opt/hostedtoolcache/PyPy \ - /opt/hostedtoolcache/Ruby || true - docker system prune -af || true + /opt/hostedtoolcache/Ruby; do + (sudo rm -rf "$dir" || true) & pids+=("$!") + done + for pid in "${pids[@]}"; do + wait "$pid" || true + done echo "Disk after cleanup:" df -h @@ -447,6 +458,24 @@ jobs: MIGRATION_COUNT: ${{ steps.schema.outputs.count }} run: node scripts/docker-image-metadata.mjs + # Skip exporting mode=max registry cache (~2.5-3m after image push) on + # master commits when the content-addressed cache key (cacheable inputs + + # weekly CLI-tool epoch) matches the last published master image and no + # intermediate commit edited cacheable inputs. Tag builds stay read-only + # against :buildcache- so older release builds never clobber master. + - name: Compute BuildKit cache export policy + id: cache-policy + if: steps.promote.outputs.digest == '' + env: + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + IMAGE_NAME: ghcr.io/${{ github.repository }} + CACHE_REF: ghcr.io/${{ github.repository }}:buildcache-${{ matrix.arch }} + PLATFORM: ${{ matrix.platform }} + RUNNER_IMAGE_MODE: ${{ needs.runner_image.outputs.mode }} + TOOLS_EPOCH: ${{ steps.tools-epoch.outputs.epoch }} + run: node scripts/docker-cache-export-policy.mjs + # Pre-warm the local Docker daemon with the most recent published master # image's layers while Buildx builds and pushes, so the post-push PID 1 # orphan-reaping probe (`docker run --pull always`) only downloads and @@ -493,9 +522,10 @@ jobs: # Per-arch refs now the legs are separate runners: a shared ref would # have each leg overwrite the other's cache on every build. cache-from: type=registry,ref=ghcr.io/${{ github.repository }}:buildcache-${{ matrix.arch }} - cache-to: type=registry,ref=ghcr.io/${{ github.repository }}:buildcache-${{ matrix.arch }},mode=max + cache-to: ${{ steps.cache-policy.outputs.cache_to }} labels: | ${{ steps.meta.outputs.labels }} + ${{ steps.cache-policy.outputs.cache_label }} ${{ needs.runner_image.outputs.labels }} # Exactly one of the two paths produced this leg's digest. diff --git a/Dockerfile b/Dockerfile index 3cd1ad0ecd6..f3b7f04d013 100644 --- a/Dockerfile +++ b/Dockerfile @@ -396,10 +396,11 @@ COPY scripts/docker-entrypoint.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/docker-entrypoint.sh # Installed dependencies are ~2.9 GB of /app and change only with the lockfile. -# Copied from the deps stage as their own layer, a commit that leaves the -# lockfile alone does not push or pull them again. The build stage writes -# nothing under the root node_modules, so the rest of /app is copied without it. -COPY --chown=node:node --from=deps /app/node_modules /app/node_modules +# Copied from the deps stage as their own linked layer so a commit that leaves +# the lockfile alone neither re-copies 2.9 GB onto the parent layer nor pushes +# or pulls them again. The build stage writes nothing under the root +# node_modules, so the rest of /app is copied without it. +COPY --link --chown=node:node --from=deps /app/node_modules /app/node_modules COPY --chown=node:node --exclude=node_modules --from=build /app /app # Large provider binaries first, linked so the layer does not depend on the diff --git a/scripts/__tests__/docker-cache-export-policy.test.mjs b/scripts/__tests__/docker-cache-export-policy.test.mjs new file mode 100644 index 00000000000..c98b0fe461d --- /dev/null +++ b/scripts/__tests__/docker-cache-export-policy.test.mjs @@ -0,0 +1,254 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +import { + BUILDCACHE_KEY_LABEL, + CACHEABLE_INPUT_EXACT_PATHS, + computeBuildcacheKey, + decideDockerCacheExport, + extractBuildcacheKeyFromInspectJson, + isCacheableInputPath, +} from "../docker-cache-export-policy.mjs"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const CACHE_REF = "ghcr.io/paperclipai/paperclip:buildcache-amd64"; +const BASE_SHA = "a".repeat(40); +const KEY_A = "1".repeat(64); +const KEY_B = "2".repeat(64); + +test("isCacheableInputPath matches all Dockerfile cacheable inputs and ignores app source", () => { + for (const exactPath of CACHEABLE_INPUT_EXACT_PATHS) { + assert.equal(isCacheableInputPath(exactPath), true, exactPath); + assert.equal(isCacheableInputPath(`./${exactPath}`), true, `./${exactPath}`); + } + for (const cacheable of [ + "server/package.json", + "ui/package.json", + "packages/plugins/sandbox-providers/daytona/package.json", + "patches/some-dep@1.0.0.patch", + ]) { + assert.equal(isCacheableInputPath(cacheable), true, cacheable); + } + for (const appOnly of [ + "server/src/routes/issues.ts", + "ui/src/pages/Dashboard.tsx", + "packages/shared/src/types/issue.ts", + "doc/DEVELOPING.md", + "scripts/docker-cache-export-policy.mjs", + "server/src/package.json.bak", + "patches-notes.md", + "", + ]) { + assert.equal(isCacheableInputPath(appOnly), false, appOnly); + } +}); + +test("computeBuildcacheKey is deterministic, order-independent, and sensitive to epoch and file bytes", () => { + const k1 = computeBuildcacheKey({ + toolsEpoch: "2026-W48", + files: [ + { path: "pnpm-lock.yaml", content: "lock-v1" }, + { path: "Dockerfile", content: "FROM node:24" }, + ], + }); + const k2 = computeBuildcacheKey({ + toolsEpoch: "2026-W48", + files: [ + { path: "Dockerfile", content: "FROM node:24" }, + { path: "./pnpm-lock.yaml", content: "lock-v1" }, + ], + }); + const kWeekRollover = computeBuildcacheKey({ + toolsEpoch: "2026-W49", + files: [ + { path: "Dockerfile", content: "FROM node:24" }, + { path: "pnpm-lock.yaml", content: "lock-v1" }, + ], + }); + const kContentChanged = computeBuildcacheKey({ + toolsEpoch: "2026-W48", + files: [ + { path: "Dockerfile", content: "FROM node:24" }, + { path: "pnpm-lock.yaml", content: "lock-v2" }, + ], + }); + + assert.match(k1, /^[0-9a-f]{64}$/); + assert.equal(k1, k2); + assert.notEqual(k1, kWeekRollover); + assert.notEqual(k1, kContentChanged); + assert.equal(computeBuildcacheKey({ toolsEpoch: "invalid", files: [{ path: "Dockerfile", content: "x" }] }), null); + assert.equal(computeBuildcacheKey({ toolsEpoch: "2026-W48", files: [] }), null); +}); + +test("extractBuildcacheKeyFromInspectJson reads multi-arch and single-arch OCI labels safely", () => { + const multiArch = JSON.stringify({ + "linux/amd64": { config: { Labels: { [BUILDCACHE_KEY_LABEL]: KEY_A } } }, + "linux/arm64": { config: { Labels: { [BUILDCACHE_KEY_LABEL]: KEY_B } } }, + }); + assert.equal(extractBuildcacheKeyFromInspectJson(multiArch, "linux/amd64"), KEY_A); + assert.equal(extractBuildcacheKeyFromInspectJson(multiArch, "linux/arm64"), KEY_B); + + const singleArch = JSON.stringify({ config: { Labels: { [BUILDCACHE_KEY_LABEL]: KEY_A } } }); + assert.equal(extractBuildcacheKeyFromInspectJson(singleArch, "linux/amd64"), KEY_A); + + assert.equal(extractBuildcacheKeyFromInspectJson(JSON.stringify({ "linux/amd64": { config: { Labels: {} } } }), "linux/amd64"), null); + assert.equal(extractBuildcacheKeyFromInspectJson(JSON.stringify({ "linux/amd64": { config: { Labels: { [BUILDCACHE_KEY_LABEL]: "not-a-sha" } } } }), "linux/amd64"), null); + assert.equal(extractBuildcacheKeyFromInspectJson("not json", "linux/amd64"), null); + assert.equal(extractBuildcacheKeyFromInspectJson("", "linux/amd64"), null); +}); + +test("non-master refs (release tags) never overwrite shared master buildcache", () => { + for (const ref of ["refs/tags/v2026.1125.0", "refs/tags/nightly/v2026.1125.0", "refs/tags/beta/v2026.1125.0", "refs/heads/release"]) { + const decision = decideDockerCacheExport({ + eventName: "push", + ref, + cacheRef: CACHE_REF, + runnerImageMode: "published", + lockfileRefreshed: false, + remoteCacheExists: true, + currentKey: KEY_A, + baseSha: BASE_SHA, + lastExportedKey: KEY_B, + interveningChangedFiles: ["Dockerfile"], + }); + assert.deepEqual(decision, { + shouldExport: false, + cacheTo: "", + cacheLabel: "", + reason: "non-master-ref-read-only", + }, ref); + } +}); + +test("decideDockerCacheExport skips export on master when content-addressed cache key and history are clean", () => { + const decision = decideDockerCacheExport({ + eventName: "push", + ref: "refs/heads/master", + cacheRef: CACHE_REF, + runnerImageMode: "published", + lockfileRefreshed: false, + remoteCacheExists: true, + currentKey: KEY_A, + baseSha: BASE_SHA, + lastExportedKey: KEY_A, + interveningChangedFiles: [ + "server/src/services/heartbeat.ts", + "ui/src/pages/Agents.tsx", + "packages/db/src/schema/issues.ts", + ], + }); + + assert.deepEqual(decision, { + shouldExport: false, + cacheTo: "", + cacheLabel: `${BUILDCACHE_KEY_LABEL}=${KEY_A}`, + reason: "cache-key-unchanged", + }); +}); + +test("decideDockerCacheExport fails open to mode=max export on master whenever cache may be stale or missing", () => { + const baseInput = { + eventName: "push", + ref: "refs/heads/master", + cacheRef: CACHE_REF, + runnerImageMode: "published", + lockfileRefreshed: false, + remoteCacheExists: true, + currentKey: KEY_A, + baseSha: BASE_SHA, + lastExportedKey: KEY_A, + interveningChangedFiles: ["server/src/index.ts"], + }; + const expectedCacheTo = `type=registry,ref=${CACHE_REF},mode=max`; + const expectedLabel = `${BUILDCACHE_KEY_LABEL}=${KEY_A}`; + + const cases = [ + ["manual master dispatch", { ...baseInput, eventName: "workflow_dispatch" }, "manual-master-refresh", expectedLabel], + ["inline runner build", { ...baseInput, runnerImageMode: "inline" }, "runner-image-not-published", expectedLabel], + ["refreshed lockfile", { ...baseInput, lockfileRefreshed: true }, "lockfile-refreshed", ""], + ["missing current key", { ...baseInput, currentKey: null }, "cache-key-unavailable", ""], + ["missing remote cache", { ...baseInput, remoteCacheExists: false }, "remote-cache-missing", expectedLabel], + ["no published ancestor", { ...baseInput, baseSha: null }, "no-published-ancestor", expectedLabel], + ["ancestor missing cache key (e.g. merge-queue promotion)", { ...baseInput, lastExportedKey: null }, "ancestor-missing-cache-key", expectedLabel], + ["cache key changed (input edit or week rollover)", { ...baseInput, lastExportedKey: KEY_B }, "cache-key-changed", expectedLabel], + ["intervening history unavailable", { ...baseInput, interveningChangedFiles: null }, "intervening-history-unavailable", expectedLabel], + ["reverted cacheable edit in intervening commit", { ...baseInput, interveningChangedFiles: ["server/src/index.ts", "pnpm-lock.yaml"] }, "intervening-cacheable-edit:pnpm-lock.yaml", expectedLabel], + ]; + + for (const [label, input, expectedReason, expectedCacheLabel] of cases) { + const decision = decideDockerCacheExport(input); + assert.equal(decision.shouldExport, true, label); + assert.equal(decision.cacheTo, expectedCacheTo, label); + assert.equal(decision.cacheLabel, expectedCacheLabel, label); + assert.equal(decision.reason, expectedReason, label); + } +}); + +test("every pre-app context COPY in Dockerfile is covered by isCacheableInputPath", () => { + const dockerfile = readFileSync(path.join(repoRoot, "Dockerfile"), "utf8"); + const froms = [...dockerfile.matchAll(/^FROM .*$/gm)]; + const stageBody = (stageName) => { + const idx = froms.findIndex((m) => new RegExp(`\\bAS ${stageName}\\s*$`).test(m[0])); + assert.ok(idx >= 0, `missing stage ${stageName}`); + return dockerfile.slice(froms[idx].index, froms[idx + 1]?.index ?? dockerfile.length); + }; + + const productionStage = stageBody("production"); + const appCopyIdx = productionStage.indexOf("COPY --chown=node:node --exclude=node_modules --from=build /app /app"); + assert.ok(appCopyIdx > 0, "production stage must copy app files from build"); + const preAppProduction = productionStage.slice(0, appCopyIdx); + + const stagesToAudit = [ + ["tailscale-client", stageBody("tailscale-client")], + ["runner-lockfile", stageBody("runner-lockfile")], + ["deps", stageBody("deps")], + ["production (pre-app)", preAppProduction], + ]; + + for (const [stageName, body] of stagesToAudit) { + for (const match of body.matchAll(/^COPY\s+(.+)$/gm)) { + const tokens = match[1].trim().split(/\s+/); + if (tokens.some((token) => token.startsWith("--from="))) continue; + const paths = tokens.filter((token) => !token.startsWith("--")).slice(0, -1); + for (const rawSource of paths) { + const samplePath = rawSource + .replace("/./", "/") + .replaceAll("*", "example") + .replace(/\/$/, ""); + assert.equal( + isCacheableInputPath(samplePath), + true, + `Dockerfile ${stageName} COPY source '${rawSource}' (sample '${samplePath}') must be covered by isCacheableInputPath`, + ); + } + } + } +}); + +test("docker.yml wires cache export policy and cache key label into Build and push by digest", () => { + const workflow = readFileSync(path.join(repoRoot, ".github/workflows/docker.yml"), "utf8"); + const buildJob = workflow.split(" build-and-push:\n")[1].split("\n merge-and-push:")[0]; + const steps = buildJob.split(/\n(?= - )/); + + const policyIdx = steps.findIndex((step) => step.includes("node scripts/docker-cache-export-policy.mjs")); + const buildIdx = steps.findIndex((step) => step.includes("uses: docker/build-push-action@")); + assert.ok(policyIdx >= 0, "docker.yml must invoke scripts/docker-cache-export-policy.mjs"); + assert.ok(buildIdx > policyIdx, "cache export policy must run before docker/build-push-action"); + + const policyStep = steps[policyIdx]; + assert.match(policyStep, /id: cache-policy/); + assert.match(policyStep, /CACHE_REF: ghcr\.io\/\$\{\{ github\.repository \}\}:buildcache-\$\{\{ matrix\.arch \}\}/); + assert.match(policyStep, /PLATFORM: \$\{\{ matrix\.platform \}\}/); + assert.match(policyStep, /RUNNER_IMAGE_MODE: \$\{\{ needs\.runner_image\.outputs\.mode \}\}/); + assert.match(policyStep, /TOOLS_EPOCH: \$\{\{ steps\.tools-epoch\.outputs\.epoch \}\}/); + const runBlock = policyStep.slice(policyStep.indexOf("run:")); + assert.doesNotMatch(runBlock, /\$\{\{/, "pass workflow expressions via env, not inline in run"); + + const buildStep = steps[buildIdx]; + assert.match(buildStep, /cache-from: type=registry,ref=ghcr\.io\/\$\{\{ github\.repository \}\}:buildcache-\$\{\{ matrix\.arch \}\}/); + assert.match(buildStep, /cache-to: \$\{\{ steps\.cache-policy\.outputs\.cache_to \}\}/); + assert.match(buildStep, /\$\{\{ steps\.cache-policy\.outputs\.cache_label \}\}/); +}); diff --git a/scripts/__tests__/release-verify-workflow.test.mjs b/scripts/__tests__/release-verify-workflow.test.mjs index a45d202e74e..f12d572baf3 100644 --- a/scripts/__tests__/release-verify-workflow.test.mjs +++ b/scripts/__tests__/release-verify-workflow.test.mjs @@ -51,7 +51,10 @@ test("Docker Hub mirrors apply to both image builders without widening publicati assert.match(docker, /platform: linux\/arm64/); assert.match(docker, /permissions:\n\s+contents: read\n\s+packages: write/); assert.match(docker, /outputs: type=image,name=ghcr\.io\/\$\{\{ github\.repository \}\},push-by-digest=true,name-canonical=true,push=true/); - assert.match(docker, /cache-to: type=registry,ref=ghcr\.io\/\$\{\{ github\.repository \}\}:buildcache-\$\{\{ matrix\.arch \}\},mode=max/); + assert.match(docker, /cache-from: type=registry,ref=ghcr\.io\/\$\{\{ github\.repository \}\}:buildcache-\$\{\{ matrix\.arch \}\}/); + assert.match(docker, /CACHE_REF: ghcr\.io\/\$\{\{ github\.repository \}\}:buildcache-\$\{\{ matrix\.arch \}\}/); + assert.match(docker, /run: node scripts\/docker-cache-export-policy\.mjs/); + assert.match(docker, /cache-to: \$\{\{ steps\.cache-policy\.outputs\.cache_to \}\}/); assert.match(preview, /permissions:\n\s+contents: read\n\s+steps:/); assert.match(preview, /platforms: linux\/amd64\n\s+push: false/); assert.match(preview, /outputs: type=docker,dest=\$\{\{ runner\.temp \}\}\/preview-image\.tar/); diff --git a/scripts/docker-cache-export-policy.mjs b/scripts/docker-cache-export-policy.mjs new file mode 100644 index 00000000000..8118f30798c --- /dev/null +++ b/scripts/docker-cache-export-policy.mjs @@ -0,0 +1,391 @@ +#!/usr/bin/env node +// Decides whether `.github/workflows/docker.yml` should export its BuildKit +// registry cache (`cache-to: ...,mode=max`) for this build, and computes the +// content-addressed cache key stamped onto published `master` images. +// +// `mode=max` exports every intermediate stage, including the per-commit `build` +// stage (~4 GB), which adds ~2.5-3 minutes *after* the production image has +// already been pushed. +// +// Ownership and freshness invariants: +// 1. Only `refs/heads/master` writes `:buildcache-`. Tag builds +// (`refs/tags/*`) still read `cache-from: ...:buildcache-` for speed +// but never overwrite it, preventing older release branches from clobbering +// `master`'s shared cache. +// 2. Every `Build and push by digest` on `refs/heads/master` (with a clean +// lockfile) stamps `io.github.paperclipai.buildcache.key=` on the +// published per-arch image config, where `` hashes +// `CLI_TOOLS_CACHE_EPOCH` plus the exact bytes of every cross-commit +// cacheable Dockerfile input. +// 3. A `push` to `refs/heads/master` skips `cache-to` ONLY when: +// - the Runner image is published (not inline), +// - `pnpm-lock.yaml` was not mutated in the checkout, +// - `:buildcache-` currently exists in the registry, +// - the most recent published `master` ancestor (in the last 10 commits) +// carries a matching `io.github.paperclipai.buildcache.key` for this +// platform (automatically failing open if that ancestor was promoted from +// the merge queue without writing cache, or if any input or ISO week +// changed), AND +// - no commit in `baseSha..HEAD` touched a cacheable input (protecting +// against an unpublished failed-and-reverted intermediate commit that may +// have overwritten `:buildcache-`). +// +// Any uncertainty fails open to exporting `mode=max` on `refs/heads/master`. + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { appendFileSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const DEFAULT_LOOKBACK_COMMITS = 10; +const FULL_SHA_RE = /^[0-9a-f]{40}$/; +const HEX_64_RE = /^[0-9a-f]{64}$/; +const ISO_WEEK_EPOCH_RE = /^\d{4}-W\d{2}$/; + +export const BUILDCACHE_KEY_LABEL = "io.github.paperclipai.buildcache.key"; + +/** + * Exact repository-relative paths read by Dockerfile stages whose layers are + * meant to stay cached across master commits (`base`, `tailscale-client`, + * `runner-lockfile`, `deps`, and pre-app layers of `production`). + * + * Workspace `package.json` files and `patches/**` are matched separately in + * `isCacheableInputPath`. + */ +export const CACHEABLE_INPUT_EXACT_PATHS = Object.freeze(new Set([ + "Dockerfile", + ".dockerignore", + ".npmrc", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "package.json", + "docker/tailscale.LICENSE", + "scripts/docker-entrypoint.sh", + "scripts/link-plugin-dev-sdk.mjs", + "packages/paperclip-runner/scripts/install-copilot-assets.mjs", + "packages/paperclip-runner/scripts/materialize-copilot-binary.mjs", + "packages/paperclip-runner/scripts/copilot-inner-distribution.mjs", + "packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts", + "server/scripts/install-copilot-assets.mjs", + "server/src/services/copilot-connection-probe.ts", +])); + +export function isCacheableInputPath(filePath) { + if (typeof filePath !== "string" || filePath.length === 0) return false; + const normalized = filePath.replaceAll("\\", "/").replace(/^\.\//, ""); + if (CACHEABLE_INPUT_EXACT_PATHS.has(normalized)) return true; + if (normalized === "package.json" || normalized.endsWith("/package.json")) return true; + if (normalized === "patches" || normalized.startsWith("patches/")) return true; + return false; +} + +/** + * Computes a deterministic 64-char SHA-256 fingerprint for `CLI_TOOLS_CACHE_EPOCH` + * and every cross-commit cacheable input file. + * + * @param {{ toolsEpoch: string, files: Array<{ path: string, content: Buffer | string }> }} input + * @returns {string | null} + */ +export function computeBuildcacheKey({ toolsEpoch, files }) { + if (typeof toolsEpoch !== "string" || !ISO_WEEK_EPOCH_RE.test(toolsEpoch)) return null; + if (!Array.isArray(files) || files.length === 0) return null; + + const sorted = [...files] + .map((entry) => ({ + path: String(entry.path).replaceAll("\\", "/").replace(/^\.\//, ""), + content: entry.content, + })) + .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + + const hash = createHash("sha256"); + hash.update("paperclip-buildcache-key-v1\n"); + hash.update(`toolsEpoch=${toolsEpoch}\n`); + for (const entry of sorted) { + const fileDigest = createHash("sha256").update(entry.content).digest("hex"); + hash.update(`${entry.path}\0${fileDigest}\n`); + } + return hash.digest("hex"); +} + +/** + * Extracts `io.github.paperclipai.buildcache.key` from the JSON output of + * `docker buildx imagetools inspect --format '{{json .Image}}'`. + */ +export function extractBuildcacheKeyFromInspectJson(rawJson, platform) { + if (typeof rawJson !== "string" || rawJson.trim() === "") return null; + let parsed; + try { + parsed = JSON.parse(rawJson); + } catch { + return null; + } + if (!parsed || typeof parsed !== "object") return null; + + const entry = (platform && parsed[platform] && typeof parsed[platform] === "object") + ? parsed[platform] + : parsed; + const labels = entry?.config?.Labels ?? entry?.Config?.Labels; + const key = labels?.[BUILDCACHE_KEY_LABEL]; + return typeof key === "string" && HEX_64_RE.test(key) ? key : null; +} + +/** + * Pure decision function for BuildKit registry cache export. + * + * @param {{ + * eventName?: string, + * ref?: string, + * cacheRef: string, + * runnerImageMode?: string, + * lockfileRefreshed?: boolean, + * remoteCacheExists?: boolean, + * currentKey?: string | null, + * baseSha?: string | null, + * lastExportedKey?: string | null, + * interveningChangedFiles?: string[] | null, + * }} input + * @returns {{ shouldExport: boolean, cacheTo: string, cacheLabel: string, reason: string }} + */ +export function decideDockerCacheExport({ + eventName, + ref, + cacheRef, + runnerImageMode, + lockfileRefreshed = false, + remoteCacheExists = false, + currentKey = null, + baseSha = null, + lastExportedKey = null, + interveningChangedFiles = null, +}) { + if (typeof cacheRef !== "string" || cacheRef.trim() === "") { + throw new Error("cacheRef is required"); + } + const normalizedCacheRef = cacheRef.trim(); + const validCurrentKey = typeof currentKey === "string" && HEX_64_RE.test(currentKey) ? currentKey : null; + + // Release tags and non-master refs read the shared master cache via + // cache-from but must never overwrite it (concurrent older release builds + // would otherwise evict master's dependency/tool layers). + if (ref !== "refs/heads/master") { + return { + shouldExport: false, + cacheTo: "", + cacheLabel: "", + reason: "non-master-ref-read-only", + }; + } + + const labelForMaster = (!lockfileRefreshed && validCurrentKey) + ? `${BUILDCACHE_KEY_LABEL}=${validCurrentKey}` + : ""; + + const exportCache = (reason) => ({ + shouldExport: true, + cacheTo: `type=registry,ref=${normalizedCacheRef},mode=max`, + cacheLabel: labelForMaster, + reason, + }); + const skipCache = (reason) => ({ + shouldExport: false, + cacheTo: "", + cacheLabel: labelForMaster, + reason, + }); + + if (eventName === "workflow_dispatch") { + return exportCache("manual-master-refresh"); + } + if (eventName !== "push") { + return exportCache("non-push-master-event"); + } + if (runnerImageMode !== "published") { + return exportCache("runner-image-not-published"); + } + if (lockfileRefreshed) { + return exportCache("lockfile-refreshed"); + } + if (!validCurrentKey) { + return exportCache("cache-key-unavailable"); + } + if (remoteCacheExists !== true) { + return exportCache("remote-cache-missing"); + } + if (typeof baseSha !== "string" || !FULL_SHA_RE.test(baseSha)) { + return exportCache("no-published-ancestor"); + } + if (typeof lastExportedKey !== "string" || !HEX_64_RE.test(lastExportedKey)) { + return exportCache("ancestor-missing-cache-key"); + } + if (lastExportedKey !== validCurrentKey) { + return exportCache("cache-key-changed"); + } + if (!Array.isArray(interveningChangedFiles)) { + return exportCache("intervening-history-unavailable"); + } + const interveningCacheable = interveningChangedFiles.filter(isCacheableInputPath); + if (interveningCacheable.length > 0) { + return exportCache(`intervening-cacheable-edit:${interveningCacheable.slice(0, 3).join(",")}`); + } + + return skipCache("cache-key-unchanged"); +} + +function runCommand(command, args, timeoutMs = 20_000) { + return spawnSync(command, args, { + encoding: "utf8", + timeout: timeoutMs, + stdio: ["ignore", "pipe", "pipe"], + }); +} + +function isLockfileDirty() { + const result = runCommand("git", ["status", "--porcelain", "--", "pnpm-lock.yaml"], 10_000); + if (result.status !== 0) return true; + return result.stdout.trim().length > 0; +} + +function computeWorkspaceBuildcacheKey(repoRoot, toolsEpoch) { + if (!ISO_WEEK_EPOCH_RE.test(toolsEpoch)) return null; + const listed = runCommand("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], 15_000); + if (listed.status !== 0) return null; + const matchedPaths = listed.stdout + .split("\0") + .filter((filePath) => filePath.length > 0 && isCacheableInputPath(filePath)); + if (matchedPaths.length === 0) return null; + + const files = []; + for (const relPath of matchedPaths) { + try { + files.push({ path: relPath, content: readFileSync(path.join(repoRoot, relPath)) }); + } catch { + return null; + } + } + return computeBuildcacheKey({ toolsEpoch, files }); +} + +function checkRemoteCacheExists(cacheRef) { + const result = runCommand("docker", ["buildx", "imagetools", "inspect", cacheRef], 30_000); + return result.status === 0; +} + +function findRecentPublishedMasterAncestor(imageName, platform, lookbackCommits) { + const revList = runCommand( + "git", + ["rev-list", "--first-parent", "-n", String(lookbackCommits + 1), "HEAD"], + 10_000, + ); + if (revList.status !== 0) return { baseSha: null, lastExportedKey: null }; + const commits = revList.stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => FULL_SHA_RE.test(line)) + .slice(1); // skip HEAD itself + + for (const sha of commits) { + const inspect = runCommand( + "docker", + ["buildx", "imagetools", "inspect", `${imageName}:sha-${sha}`, "--format", "{{json .Image}}"], + 20_000, + ); + if (inspect.status === 0) { + return { + baseSha: sha, + lastExportedKey: extractBuildcacheKeyFromInspectJson(inspect.stdout, platform), + }; + } + } + return { baseSha: null, lastExportedKey: null }; +} + +function listInterveningChangedFiles(baseSha) { + const log = runCommand("git", ["log", "--format=", "--name-only", `${baseSha}..HEAD`], 15_000); + if (log.status !== 0) return null; + return [...new Set( + log.stdout + .split("\n") + .map((line) => line.trim()) + .filter(Boolean), + )]; +} + +function writeGitHubOutputs(outputPath, values) { + if (!outputPath) return; + const lines = Object.entries(values).map(([key, value]) => { + const clean = String(value).replaceAll("\r", "").replaceAll("\n", ""); + return `${key}=${clean}\n`; + }); + appendFileSync(outputPath, lines.join(""), "utf8"); +} + +function main() { + const eventName = process.env.EVENT_NAME ?? process.env.GITHUB_EVENT_NAME ?? ""; + const ref = process.env.REF ?? process.env.GITHUB_REF ?? ""; + const imageName = (process.env.IMAGE_NAME ?? "").trim(); + const cacheRef = (process.env.CACHE_REF ?? "").trim(); + const platform = (process.env.PLATFORM ?? "").trim(); + const runnerImageMode = (process.env.RUNNER_IMAGE_MODE ?? "").trim(); + const toolsEpoch = (process.env.TOOLS_EPOCH ?? "").trim(); + const parsedLookback = Number.parseInt(process.env.MAX_ANCESTOR_LOOKBACK ?? "", 10); + const lookbackCommits = Number.isInteger(parsedLookback) && parsedLookback > 0 + ? parsedLookback + : DEFAULT_LOOKBACK_COMMITS; + + const isMaster = ref === "refs/heads/master"; + const lockfileRefreshed = isMaster ? isLockfileDirty() : false; + const currentKey = isMaster ? computeWorkspaceBuildcacheKey(process.cwd(), toolsEpoch) : null; + + let remoteCacheExists = false; + let baseSha = null; + let lastExportedKey = null; + let interveningChangedFiles = null; + + const canSkipCandidate = + isMaster + && eventName === "push" + && runnerImageMode === "published" + && !lockfileRefreshed + && currentKey !== null + && imageName.length > 0; + + if (canSkipCandidate) { + remoteCacheExists = checkRemoteCacheExists(cacheRef); + if (remoteCacheExists) { + ({ baseSha, lastExportedKey } = findRecentPublishedMasterAncestor(imageName, platform, lookbackCommits)); + if (baseSha && lastExportedKey === currentKey) { + interveningChangedFiles = listInterveningChangedFiles(baseSha); + } + } + } + + const decision = decideDockerCacheExport({ + eventName, + ref, + cacheRef, + runnerImageMode, + lockfileRefreshed, + remoteCacheExists, + currentKey, + baseSha, + lastExportedKey, + interveningChangedFiles, + }); + + const action = decision.shouldExport ? "export" : "skip"; + console.log( + `Docker BuildKit cache export policy: ${action} (reason=${decision.reason}, base=${baseSha ? baseSha.slice(0, 12) : "none"}, key=${currentKey ? currentKey.slice(0, 12) : "none"})`, + ); + + writeGitHubOutputs(process.env.GITHUB_OUTPUT, { + cache_to: decision.cacheTo, + cache_label: decision.cacheLabel, + should_export: String(decision.shouldExport), + reason: decision.reason, + }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main(); +} diff --git a/server/src/__tests__/docker-image-layer-reuse.test.ts b/server/src/__tests__/docker-image-layer-reuse.test.ts index afd50612616..e64ae5f0d6b 100644 --- a/server/src/__tests__/docker-image-layer-reuse.test.ts +++ b/server/src/__tests__/docker-image-layer-reuse.test.ts @@ -23,11 +23,11 @@ function stageBody(stageName: string): string { return dockerfile.slice(froms[startIdx].index ?? 0, froms[startIdx + 1]?.index ?? dockerfile.length); } -it("copies installed dependencies as their own layer, before the per-commit app files", () => { +it("copies installed dependencies as their own linked layer, before the per-commit app files", () => { const production = stageBody("production"); - const dependencies = production.search(/^COPY --chown=node:node --from=deps \/app\/node_modules \/app\/node_modules$/m); + const dependencies = production.search(/^COPY --link --chown=node:node --from=deps \/app\/node_modules \/app\/node_modules$/m); const app = production.search(/^COPY --chown=node:node --exclude=node_modules --from=build \/app \/app$/m); - expect(dependencies, "dependencies must come from the deps stage").toBeGreaterThanOrEqual(0); + expect(dependencies, "dependencies must come from the deps stage with --link").toBeGreaterThanOrEqual(0); expect(app, "the app copy must leave out the root node_modules").toBeGreaterThan(dependencies); // A copy of all of /app from the build stage would put the dependencies // back into the per-commit layer. diff --git a/server/src/__tests__/docker-runner-workflows.test.ts b/server/src/__tests__/docker-runner-workflows.test.ts index eae1ec96ae3..3cee2b4aa7f 100644 --- a/server/src/__tests__/docker-runner-workflows.test.ts +++ b/server/src/__tests__/docker-runner-workflows.test.ts @@ -100,7 +100,10 @@ describe("the Runner image an application image build copies in docker.yml", () "CLI_TOOLS_CACHE_EPOCH=${{ steps.tools-epoch.outputs.epoch }}", ], buildContexts: [], - labels: ["${{ steps.meta.outputs.labels }}"], + labels: [ + "${{ steps.meta.outputs.labels }}", + "${{ steps.cache-policy.outputs.cache_label }}", + ], }; it("runs only when the repository variable has the enabling value, in the canonical repository, and not otherwise", () => {