From 3b3c6e4f5f6b8ea395c9dd17f46cc962aaaed5be Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:22:52 -0600 Subject: [PATCH] ci: pre-warm base image layers during docker build for PID 1 probe (#22945) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Master Docker image publication in `.github/workflows/docker.yml` verifies that PID 1 reaps orphaned processes on the exact pushed digest (`docker run --pull always "$IMAGE_NAME@$IMAGE_DIGEST"`) > - Because `Build and push by digest` runs inside BuildKit (`docker-container` driver) on a fresh runner, the local Docker daemon starts empty and the PID 1 probe spends ~2m 50s–3m 06s downloading and extracting unchanged base layers before running the 8-second probe > - Pre-warming the local Docker daemon in the background from the newest already-published ancestor master image while Buildx builds and pushes hides ~2+ minutes of layer download and extraction behind the 4–5 minute build > - This pull request adds `scripts/docker-pid1-prewarm.sh` (`start`/`stop`) and wires it into `build-and-push` on AWS master pushes without changing BuildKit, image digests, or the `--pull always` verification check > - The benefit is cutting ~2+ minutes off master image publication on both `amd64` and `arm64` legs while preserving every provenance and PID 1 safety check ## Linked Issues or Issue Description **What existing behavior does this improve?** The `Verify PID 1 reaps orphaned processes` step in `.github/workflows/docker.yml` (`build-and-push`). **Subsystem affected** Cross-cutting (multiple of the above) **Current behavior** After `Build and push by digest` pushes the new digest from BuildKit to GHCR, `Verify PID 1 reaps orphaned processes` runs `docker run --rm -i --pull always "$IMAGE_NAME@$IMAGE_DIGEST"` on an empty local Docker daemon, spending ~2m 50s–3m 06s downloading and extracting unchanged base layers before running the 8-second orphan-reaping script. **Proposed behavior** On canonical AWS master pushes (when not promoting a merge-queue image), `docker.yml` starts a non-blocking background `docker pull` of the newest published ancestor master image (checking `HEAD~1`..`HEAD~10` with `docker manifest inspect`) right before `Build and push by digest`. Before `docker run --pull always` (and in an `if: always()` cleanup step), `scripts/docker-pid1-prewarm.sh stop` waits briefly or stops the background `docker pull` process cleanly. **Reason and benefit** Hides ~2+ minutes of base-layer download and extraction behind `Build and push by digest` on both `amd64` and `arm64`, speeding up master Docker image publication while still verifying the exact pushed digest from GHCR. **Breaking changes** None. BuildKit inputs, image digests, and the `--pull always "$IMAGE_NAME@$IMAGE_DIGEST"` probe are unchanged. ## What Changed - Added `scripts/docker-pid1-prewarm.sh` with `start` (finds newest published `HEAD~1`..`HEAD~10` `:sha-` image via `docker manifest inspect` and starts a detached background `docker pull --quiet --platform "$PLATFORM"`) and `stop [wait_seconds]` (verifies the recorded PID is still a `docker pull` process via `ps -o args=`, waits up to `wait_seconds`, stops it if still running, and removes the pidfile). - Wired `Pre-warm base layers for PID 1 probe` (`timeout-minutes: 1`, `continue-on-error: true`, gated on `CORE_RELEASE_AWS_ENABLED == 'true'` canonical master pushes with `steps.promote.outputs.digest == ''`), `stop 15` before the PID 1 probe, and `stop 0` in an `if: always()` cleanup step in `.github/workflows/docker.yml`. - Added `.github/scripts/tests/docker-pid1-prewarm.test.mjs` testing workflow gating/ordering and executing `scripts/docker-pid1-prewarm.sh` with fake `git`/`docker` binaries across ancestor discovery, clean skip, non-docker PID protection, and active-process termination. ## Verification - `node --test .github/scripts/tests/docker-pid1-prewarm.test.mjs scripts/merge-group-image.test.mjs .github/scripts/tests/cloud-readiness.test.mjs .github/scripts/tests/docker-canary-promotion.test.mjs .github/scripts/tests/post-merge-runner-routing.test.mjs scripts/docker-image-metadata.test.mjs` — all tests passed (14/14 in `docker-pid1-prewarm` + `merge-group-image`; 361/361 across the full docker/readiness workflow suite). ## Risks - Low risk: pre-warm is gated to the spacious AWS release fleet (`CORE_RELEASE_AWS_ENABLED == 'true'`), bounded to 1 minute with `continue-on-error: true`, verifies process command arguments before signaling any PID, and never modifies BuildKit or weakens `docker run --pull always "$IMAGE_NAME@$IMAGE_DIGEST"`. ## Model Used - Google Gemini (Antigravity agent, high reasoning, with tool use and code execution). ## 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 --- .../tests/docker-pid1-prewarm.test.mjs | 213 ++++++++++++++++++ .github/workflows/docker.yml | 25 ++ scripts/docker-pid1-prewarm.sh | 67 ++++++ 3 files changed, 305 insertions(+) create mode 100644 .github/scripts/tests/docker-pid1-prewarm.test.mjs create mode 100755 scripts/docker-pid1-prewarm.sh diff --git a/.github/scripts/tests/docker-pid1-prewarm.test.mjs b/.github/scripts/tests/docker-pid1-prewarm.test.mjs new file mode 100644 index 00000000000..2af7edfa41d --- /dev/null +++ b/.github/scripts/tests/docker-pid1-prewarm.test.mjs @@ -0,0 +1,213 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { imageMetadata } from "../../../scripts/docker-image-metadata.mjs"; + +const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), "../../.."); +const workflow = readFileSync(path.join(root, ".github/workflows/docker.yml"), "utf8"); +const scriptPath = path.join(root, "scripts/docker-pid1-prewarm.sh"); + +function writeExecutable(file, content) { + writeFileSync(file, content, "utf8"); + chmodSync(file, 0o755); +} + +test("docker.yml gates base-layer pre-warm to AWS master builds and cleans up before and after the PID 1 probe", () => { + const leg = workflow.split("\n build-and-push:\n")[1].split("\n publication_verification:\n")[0]; + const steps = leg.split(/\n(?= - name: )/); + const step = (name) => { + const found = steps.find((item) => item.startsWith(` - name: ${name}\n`)); + assert.ok(found, `missing step: ${name}`); + return found; + }; + const order = (name) => steps.indexOf(step(name)); + + const prewarm = step("Pre-warm base layers for PID 1 probe"); + assert.match(prewarm, /if: steps\.promote\.outputs\.digest == '' && vars\.CORE_RELEASE_AWS_ENABLED == 'true' && github\.repository == 'paperclipai\/paperclip' && github\.repository_id == '1170821064' && github\.event_name == 'push' && github\.ref == 'refs\/heads\/master'/); + assert.match(prewarm, /continue-on-error: true/); + assert.match(prewarm, /run: bash scripts\/docker-pid1-prewarm\.sh start/); + assert.ok(order("Docker meta") < order("Pre-warm base layers for PID 1 probe")); + assert.ok(order("Pre-warm base layers for PID 1 probe") < order("Build and push by digest")); + + const probe = step("Verify PID 1 reaps orphaned processes"); + assert.match(probe, /bash scripts\/docker-pid1-prewarm\.sh stop 15/); + assert.match(probe, /docker run --rm -i --pull always --platform "\$PLATFORM" "\$IMAGE_NAME@\$IMAGE_DIGEST" sh -s < scripts\/assert-orphan-reaping\.sh/); + assert.ok(probe.indexOf("docker-pid1-prewarm.sh stop") < probe.indexOf("docker run --rm -i --pull always")); + + const cleanup = step("Stop background base-layer pre-warm if still running"); + assert.match(cleanup, /if: always\(\)/); + assert.match(cleanup, /continue-on-error: true/); + assert.match(cleanup, /run: bash scripts\/docker-pid1-prewarm\.sh stop 0/); + assert.ok(order("Upload digest") < order("Stop background base-layer pre-warm if still running")); +}); + +test("docker-pid1-prewarm.sh finds the newest published ancestor image, pulls in background, and stops cleanly", () => { + const tmp = mkdtempSync(path.join(os.tmpdir(), "docker-pid1-prewarm-")); + try { + const bin = path.join(tmp, "bin"); + const calls = path.join(tmp, "calls.log"); + const pidFile = path.join(tmp, "prewarm.pid"); + const logFile = path.join(tmp, "prewarm.log"); + spawnSync("mkdir", ["-p", bin]); + + const sha1 = "1".repeat(40); + const sha2 = "2".repeat(40); + const publishedMetadata = imageMetadata({ + repository: "paperclipai/paperclip", + sha: sha2, + ref: "refs/heads/master", + event: "push", + lastMigration: "0000_fixture.sql", + migrationCount: "1", + created: "2000-01-01T00:00:00.000Z", + }); + const expectedTag = `ghcr.io/paperclipai/paperclip:sha-${sha2}`; + assert.ok( + publishedMetadata.tags.includes(expectedTag), + `docker-image-metadata.mjs must publish ${expectedTag} for master pushes`, + ); + writeExecutable(path.join(bin, "git"), `#!/usr/bin/env bash +case "$3" in + HEAD~1^{commit}) echo "${sha1}" ;; + HEAD~2^{commit}) echo "${sha2}" ;; + *) exit 1 ;; +esac +`); + writeExecutable(path.join(bin, "docker"), `#!/usr/bin/env bash +echo "docker $*" >> "${calls}" +if [ "$1" = "manifest" ] && [ "$2" = "inspect" ]; then + if [ "$3" = "ghcr.io/paperclipai/paperclip:sha-${sha2}" ]; then + exit 0 + fi + exit 1 +fi +if [ "$1" = "pull" ]; then + sleep 0.2 + exit 0 +fi +exit 1 +`); + + const env = { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + IMAGE_NAME: "ghcr.io/paperclipai/paperclip", + PLATFORM: "linux/amd64", + PID_FILE: pidFile, + LOG_FILE: logFile, + }; + + const started = spawnSync("bash", [scriptPath, "start"], { env, encoding: "utf8" }); + assert.equal(started.status, 0, started.stderr); + assert.match(started.stdout, new RegExp(`Pre-warming linux/amd64 base layers in background from ghcr\\.io/paperclipai/paperclip:sha-${sha2}`)); + assert.ok(existsSync(pidFile), "pidfile must be written when a published ancestor exists"); + + const stopped = spawnSync("bash", [scriptPath, "stop", "5"], { env, encoding: "utf8" }); + assert.equal(stopped.status, 0, stopped.stderr); + assert.equal(existsSync(pidFile), false, "pidfile must be removed on stop"); + + const recorded = readFileSync(calls, "utf8"); + assert.match(recorded, new RegExp(`docker manifest inspect ghcr\\.io/paperclipai/paperclip:sha-${sha1}`)); + assert.match(recorded, new RegExp(`docker manifest inspect ghcr\\.io/paperclipai/paperclip:sha-${sha2}`)); + assert.match(recorded, new RegExp(`docker pull --quiet --platform linux/amd64 ghcr\\.io/paperclipai/paperclip:sha-${sha2}`)); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +}); + +test("docker-pid1-prewarm.sh skips cleanly when no recent ancestor image is published and never kills non-docker PIDs", () => { + const tmp = mkdtempSync(path.join(os.tmpdir(), "docker-pid1-prewarm-skip-")); + try { + const bin = path.join(tmp, "bin"); + const pidFile = path.join(tmp, "prewarm.pid"); + const logFile = path.join(tmp, "prewarm.log"); + spawnSync("mkdir", ["-p", bin]); + + writeExecutable(path.join(bin, "git"), `#!/usr/bin/env bash +exit 1 +`); + writeExecutable(path.join(bin, "docker"), `#!/usr/bin/env bash +exit 1 +`); + + const env = { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + IMAGE_NAME: "ghcr.io/paperclipai/paperclip", + PLATFORM: "linux/arm64", + PID_FILE: pidFile, + LOG_FILE: logFile, + }; + + const started = spawnSync("bash", [scriptPath, "start"], { env, encoding: "utf8" }); + assert.equal(started.status, 0, started.stderr); + assert.match(started.stdout, /skipping base-layer pre-warm/); + assert.equal(existsSync(pidFile), false); + + // Writing our own node PID into pidFile must NOT kill this process. + writeFileSync(pidFile, `${process.pid}\n`, "utf8"); + const stopped = spawnSync("bash", [scriptPath, "stop", "0"], { env, encoding: "utf8" }); + assert.equal(stopped.status, 0, stopped.stderr); + assert.equal(existsSync(pidFile), false); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +}); + +test("docker-pid1-prewarm.sh terminates a still-running docker pull when stop wait expires", () => { + const tmp = mkdtempSync(path.join(os.tmpdir(), "docker-pid1-prewarm-kill-")); + try { + const bin = path.join(tmp, "bin"); + const pidFile = path.join(tmp, "prewarm.pid"); + const logFile = path.join(tmp, "prewarm.log"); + spawnSync("mkdir", ["-p", bin]); + + const sha1 = "a".repeat(40); + writeExecutable(path.join(bin, "git"), `#!/usr/bin/env bash +echo "${sha1}" +`); + writeExecutable(path.join(bin, "docker"), `#!/usr/bin/env bash +if [ "$1" = "manifest" ]; then exit 0; fi +if [ "$1" = "pull" ]; then + trap 'exit 0' TERM + sleep 30 & + wait $! +fi +exit 1 +`); + + const env = { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + IMAGE_NAME: "ghcr.io/paperclipai/paperclip", + PLATFORM: "linux/amd64", + PID_FILE: pidFile, + LOG_FILE: logFile, + }; + + const started = spawnSync("bash", [scriptPath, "start"], { env, encoding: "utf8" }); + assert.equal(started.status, 0, started.stderr); + const pid = Number(readFileSync(pidFile, "utf8").trim()); + assert.ok(Number.isSafeInteger(pid) && pid > 1); + try { + const stopped = spawnSync("bash", [scriptPath, "stop", "0"], { env, encoding: "utf8" }); + assert.equal(stopped.status, 0, stopped.stderr); + assert.match(stopped.stdout, /Stopping still-running base-layer pre-warm/); + assert.equal(existsSync(pidFile), false); + // Give the trapped shell a moment to exit, then confirm it is gone. + let alive = true; + for (let i = 0; i < 20; i++) { + try { process.kill(pid, 0); } catch { alive = false; break; } + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50); + } + assert.equal(alive, false, "stop must terminate the background docker pull process"); + } finally { + try { process.kill(pid, "SIGKILL"); } catch {} + } + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +}); diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 9d20e0ca8ef..1db18860a89 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -446,6 +446,22 @@ jobs: LAST_MIGRATION: ${{ steps.schema.outputs.last }} MIGRATION_COUNT: ${{ steps.schema.outputs.count }} run: node scripts/docker-image-metadata.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 + # extracts the small changed top layers (~30s instead of ~3m). + - name: Pre-warm base layers for PID 1 probe + if: steps.promote.outputs.digest == '' && vars.CORE_RELEASE_AWS_ENABLED == 'true' && github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs/heads/master' + timeout-minutes: 1 + continue-on-error: true + env: + IMAGE_NAME: ghcr.io/${{ github.repository }} + PLATFORM: ${{ matrix.platform }} + PID_FILE: ${{ runner.temp }}/pid1-prewarm.pid + LOG_FILE: ${{ runner.temp }}/pid1-prewarm.log + run: bash scripts/docker-pid1-prewarm.sh start + - name: Build and push by digest id: build if: steps.promote.outputs.digest == '' @@ -511,9 +527,11 @@ jobs: IMAGE_DIGEST: ${{ steps.image.outputs.digest }} IMAGE_NAME: ghcr.io/${{ github.repository }} PLATFORM: ${{ matrix.platform }} + PID_FILE: ${{ runner.temp }}/pid1-prewarm.pid run: | set -euo pipefail test -n "$IMAGE_DIGEST" + bash scripts/docker-pid1-prewarm.sh stop 15 echo "Verifying orphan reaping in $IMAGE_NAME@$IMAGE_DIGEST ($PLATFORM)" docker run --rm -i --pull always --platform "$PLATFORM" "$IMAGE_NAME@$IMAGE_DIGEST" sh -s < scripts/assert-orphan-reaping.sh @@ -536,6 +554,13 @@ jobs: if-no-files-found: error retention-days: 1 + - name: Stop background base-layer pre-warm if still running + if: always() + continue-on-error: true + env: + PID_FILE: ${{ runner.temp }}/pid1-prewarm.pid + run: bash scripts/docker-pid1-prewarm.sh stop 0 + # Wait for proof on ephemeral verification capacity. Publication runners do # only registry/signing work. Each Spot observer stays below its 45m lifetime. publication_verification: diff --git a/scripts/docker-pid1-prewarm.sh b/scripts/docker-pid1-prewarm.sh new file mode 100755 index 00000000000..82c0a7c0255 --- /dev/null +++ b/scripts/docker-pid1-prewarm.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# 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 +# extracts the small changed top layers. +set -euo pipefail + +is_docker_pid() { + local pid="$1" + [ -n "$pid" ] || return 1 + kill -0 "$pid" 2>/dev/null || return 1 + local args + args="$(ps -p "$pid" -o args= 2>/dev/null || true)" + printf '%s\n' "$args" | grep -Eq '(^|[[:space:]/])docker[[:space:]]+pull([[:space:]]|$)' +} + +case "${1:-}" in + start) + : "${IMAGE_NAME:?IMAGE_NAME is required}" + : "${PLATFORM:?PLATFORM is required}" + : "${PID_FILE:?PID_FILE is required}" + : "${LOG_FILE:?LOG_FILE is required}" + ref="" + for depth in 1 2 3 4 5 6 7 8 9 10; do + sha="$(git rev-parse --verify "HEAD~${depth}^{commit}" 2>/dev/null || true)" + [ -n "$sha" ] || break + if docker manifest inspect "$IMAGE_NAME:sha-$sha" >/dev/null 2>&1; then + ref="$IMAGE_NAME:sha-$sha" + break + fi + done + if [ -z "$ref" ]; then + echo "No recent published master image found in the last 10 commits; skipping base-layer pre-warm." + exit 0 + fi + echo "Pre-warming $PLATFORM base layers in background from $ref" + nohup docker pull --quiet --platform "$PLATFORM" "$ref" >"$LOG_FILE" 2>&1 "$PID_FILE" + ;; + stop) + : "${PID_FILE:?PID_FILE is required}" + wait_seconds="${2:-0}" + [[ "$wait_seconds" =~ ^[0-9]+$ ]] || { echo "Invalid wait_seconds: $wait_seconds" >&2; exit 2; } + if [ -f "$PID_FILE" ]; then + pid="$(cat "$PID_FILE" 2>/dev/null || true)" + if is_docker_pid "$pid"; then + if [ "$wait_seconds" -gt 0 ]; then + echo "Waiting up to ${wait_seconds}s for background base-layer pre-warm (pid $pid)..." + elapsed=0 + while [ "$elapsed" -lt "$wait_seconds" ] && is_docker_pid "$pid"; do + sleep 1 + elapsed=$((elapsed + 1)) + done + fi + if is_docker_pid "$pid"; then + echo "Stopping still-running base-layer pre-warm (pid $pid)." + kill "$pid" 2>/dev/null || true + fi + fi + rm -f "$PID_FILE" + fi + ;; + *) + echo "Usage: $0 start | stop [wait_seconds]" >&2 + exit 2 + ;; +esac