perf(docker): skip redundant registry cache export and link deps layer (#22986)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Docker publishing workflow (`.github/workflows/docker.yml`)
builds and pushes multi-arch production images from `Dockerfile` on
every `master` push and release tag
> - Profiling recent `master` builds showed two large overheads on every
normal commit: `exporting cache to registry` (`cache-to: ...,mode=max`)
took ~2m 42s *after* the image push had already finished, and `COPY
--chown=node:node --from=deps /app/node_modules /app/node_modules` took
~55s without `--link`
> - On ordinary application commits (server, UI, docs, tests), all
cross-commit cacheable layers (`base`, `tailscale-client`,
`runner-lockfile`, `deps`, and the weekly CLI-tools + entrypoint layers)
are already warm in `:buildcache-<arch>`; re-exporting the ~4 GB
per-commit `build` stage wastes ~2.5–3 minutes on every build
> - This pull request adds a fail-open cache-export policy
(`scripts/docker-cache-export-policy.mjs`), adds `--link` to the `deps`
`node_modules` copy in `Dockerfile`, and parallelizes `Free runner disk`
(with a `>= 50 GiB` skip) in `docker.yml`
> - The benefit is saving ~3.5 minutes on every normal `master` Docker
image build while preserving full `mode=max` cache refreshes whenever
any cacheable input changes, the weekly CLI-tools epoch rolls over, or
cache freshness cannot be verified

## Linked Issues or Issue Description

**What existing behavior does this improve?**
BuildKit cache export, `deps` layer linking, and runner disk cleanup in
`.github/workflows/docker.yml` and `Dockerfile`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
Every `docker.yml` build runs `cache-to:
type=registry,ref=...:buildcache-<arch>,mode=max`, which uploads the
per-commit `build` stage (~4 GB) for ~2m 42s after the production image
is already pushed. In `Dockerfile`, `COPY --chown=node:node --from=deps
/app/node_modules /app/node_modules` copies ~2.9 GB without `--link`
(~55s). On hosted runners, `Free runner disk` deletes nine tool
directories serially.

**Proposed behavior**
Before `Build and push by digest`,
`scripts/docker-cache-export-policy.mjs` checks whether this build is a
`master` push using a published Runner image whose `:buildcache-<arch>`
ref exists and whose cacheable inputs and weekly `CLI_TOOLS_CACHE_EPOCH`
have not changed since the most recent published `sha-<commit>` master
ancestor (within the last 10 commits). When unchanged, `cache_to` is
left empty (skipping the post-push cache export while keeping
`cache-from` active). Whenever any check fails or is inconclusive, it
fails open to `mode=max`. `Dockerfile` uses `COPY --link
--chown=node:node --from=deps /app/node_modules /app/node_modules`, and
`Free runner disk` skips when `/` already has `>= 50 GiB` free or
deletes directories in parallel.

**Reason and benefit**
Cuts ~3.5 minutes from the critical path of normal `master` image builds
without weakening cache freshness on lockfile, Dockerfile, patch,
entrypoint, inline-Runner, tag, manual, or weekly tool-epoch builds.

**Breaking changes**
None.

## What Changed

- Added `scripts/docker-cache-export-policy.mjs` with fail-open BuildKit
cache-export policy logic (checking event/ref, published Runner mode,
clean lockfile, remote cache existence, most recent published master
ancestor in the last 10 commits, cacheable path diff, and UTC ISO week
epoch).
- Wired `Compute BuildKit cache export policy` into
`.github/workflows/docker.yml` before `Build and push by digest`,
passing workflow values through `env:` and keeping `cache-from`
unconditional.
- Added `--link` to `COPY --link --chown=node:node --from=deps
/app/node_modules /app/node_modules` in `Dockerfile`.
- Parallelized `Free runner disk` in `.github/workflows/docker.yml` and
added a `>= 50 GiB` free-space fast-path skip.
- Added `scripts/__tests__/docker-cache-export-policy.test.mjs` (unit
tests for path matching, ISO week boundaries, every fail-open branch, a
Dockerfile audit asserting every pre-app context `COPY` is covered, and
workflow wiring checks).
- Updated `server/src/__tests__/docker-image-layer-reuse.test.ts` and
`scripts/__tests__/release-verify-workflow.test.mjs` to match the linked
copy and cache export policy wiring.

## Verification

- `node --test scripts/__tests__/docker-cache-export-policy.test.mjs
scripts/__tests__/release-verify-workflow.test.mjs
.github/scripts/tests/docker-pid1-prewarm.test.mjs
.github/scripts/tests/docker-canary-promotion.test.mjs
.github/scripts/tests/post-merge-runner-routing.test.mjs
.github/scripts/tests/cloud-readiness.test.mjs
scripts/docker-deps-postinstall.test.mjs
scripts/merge-group-image.test.mjs` (all passed)
- Vitest contract tests:
`server/src/__tests__/docker-build-stamp.test.ts` (18/18 passed),
`server/src/__tests__/docker-image-layer-reuse.test.ts` (2/2 passed),
`server/src/__tests__/runner-image-identity.test.ts` (passed)

## Risks

- Low risk. The cache-export policy is strictly fail-open: any
non-master push, inline Runner build, refreshed lockfile, missing remote
cache, missing ancestor in the last 10 commits, git/registry lookup
error, week rollover, or change to any pre-app Dockerfile input exports
`mode=max` as before. A Dockerfile contract test prevents new pre-app
`COPY` inputs from drifting out of `CACHEABLE_INPUT_EXACT_PATHS`.

## 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-25 14:35:18 -06:00
1 parent 304854ee99
commit 9cfc80b340
7 files changed
+697 -15

No files matched your search

+36 -6
View File
@@ -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-<arch> 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.
+5 -4
View File
@@ -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
@@ -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 \}\}/);
});
@@ -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/);
+391
View File
@@ -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-<arch>`. Tag builds
// (`refs/tags/*`) still read `cache-from: ...:buildcache-<arch>` 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=<sha256>` on the
// published per-arch image config, where `<sha256>` 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-<arch>` 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-<arch>`).
//
// 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 <ref> --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();
}
@@ -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.
@@ -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", () => {