Files
PaperClipAI/scripts/__tests__/docker-cache-export-policy.test.mjs
T
DottaandPaperclip 9cfc80b340 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>
2026-11-25 14:35:18 -06:00

255 lines
11 KiB
JavaScript

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 \}\}/);
});