Files
PaperClipAI/scripts/create-provider-pack-archive.mjs
T
DottaandPaperclip e18fe61c8f perf(runner-image): parallelize pack archiving and use cloud-release-32 on master amd64 (#22992)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner image workflow (`.github/workflows/runner-image.yml`)
builds `ghcr.io/paperclipai/paperclip-runner` for `amd64` and `arm64`
whenever Runner inputs change
> - Profiling recent builds showed `Build and check (amd64)` taking ~12
minutes versus ~4m 38s on `arm64`, driven by 4-core CPU saturation
during `create-provider-pack-archive.mjs` (which compressed every large
provider-pack binary serially on a single core) and during OCI tar/gzip
export on `ubuntu-latest`
> - Because `docker.yml` waits for the Runner image whenever Runner
inputs change, slow `amd64` Runner builds sit directly on the release
critical path
> - This pull request parallelizes zstd layer archive creation in
`scripts/create-provider-pack-archive.mjs` with bounded concurrency
while preserving byte-for-byte deterministic output, and routes
canonical `master` `amd64` runs of `.github/workflows/runner-image.yml`
to the larger GitHub-hosted runner (`cloud-release-32`)
> - The benefit is cutting `amd64` Runner image build time substantially
on `master` (and speeding up provider-pack archiving on every PR and
architecture) without weakening the PR/fork security boundary or
changing output bytes

## Linked Issues or Issue Description

**What existing behavior does this improve?**
`scripts/create-provider-pack-archive.mjs` layer compression throughput
and `.github/workflows/runner-image.yml` `amd64` runner sizing on
canonical `master` pushes.

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

**Current behavior**
`createProviderPackLayers` compresses `overlay.tar.zst` and each large
provider-pack file (`0.tar.zst..N.tar.zst`) sequentially on one CPU
core. In `.github/workflows/runner-image.yml`, canonical `master`
`amd64` builds run on 4-core `ubuntu-latest` (~12 minutes total vs ~4m
38s on `arm64`).

**Proposed behavior**
`createProviderPackLayers` compresses `overlay.tar.zst` and the indexed
large-file archives through a bounded worker pool
(`min(availableParallelism(), 8)`), preserving exact file ordering,
archive numbering, and byte-for-byte deterministic zstd frames. In
`.github/workflows/runner-image.yml`, canonical `master` `amd64` pushes
(`paperclipai/paperclip`, `push` to `refs/heads/master`) use
`vars.CORE_PUBLICATION_RUNNER || 'cloud-release-32'`, while all PRs,
forks, schedules, and `arm64` jobs stay on standard GitHub-hosted
runners.

**Reason and benefit**
Eliminates single-core archiving bottlenecks across all environments and
removes the 4-core `amd64` CPU bottleneck on `master` Runner image
publications.

**Breaking changes**
None.

## What Changed

- Updated `scripts/create-provider-pack-archive.mjs` to compress
`overlay.tar.zst` and large-file archives via a bounded worker pool
while preserving exact archive indices, receipt ordering, and
byte-for-byte deterministic output.
- Added `scripts/__tests__/create-provider-pack-archive.test.mjs`
verifying serial (`concurrency: 1`) and parallel (`concurrency: 4`) runs
produce identical receipts and archive bytes.
- Updated `.github/workflows/runner-image.yml` to route canonical
`master` `amd64` pushes to `vars.CORE_PUBLICATION_RUNNER ||
'cloud-release-32'` while keeping PRs, forks, schedules, and `arm64` on
`matrix.runner`.
- Added a workflow guard in
`server/src/__tests__/runner-image-workflow.test.ts` verifying only
canonical `master` `amd64` pushes use the larger GitHub-hosted runner
and never touch self-hosted AWS release fleets.

## Verification

- `node --test scripts/__tests__/create-provider-pack-archive.test.mjs`
(passed)
- Vitest: `server/src/__tests__/runner-image-identity.test.ts` (42/42
passed)
- Vitest: `server/src/__tests__/runner-image-workflow.test.ts` (18/18
passed)
- PR CI also executes the live `Runner image` workflow end-to-end
because both `scripts/create-provider-pack-archive.mjs` and
`.github/workflows/runner-image.yml` are in its PR path filter.

## Risks

- Low risk. Archive bytes and receipt structure are verified identical
between serial and parallel runs. PRs, forks, and schedules remain on
`ubuntu-latest` / `ubuntu-24.04-arm`, and `cloud-release-32` is the same
GitHub-hosted larger runner already used on `master` by `docker.yml` and
`cloud-migrator-artifacts.yml`.

## 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 16:03:05 -06:00

147 lines
7.2 KiB
JavaScript

import { createHash } from 'node:crypto';
import { createReadStream, createWriteStream } from 'node:fs';
import { lstat, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
import { availableParallelism } from 'node:os';
import { spawn } from 'node:child_process';
import { pipeline } from 'node:stream/promises';
import { constants, createZstdCompress } from 'node:zlib';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
export async function createProviderPackArchive(root) {
const manifest = JSON.parse(await readFile(resolve(root, 'provider-pack.json'), 'utf8'));
if (manifest.schema !== 'paperclip-runner/remote-provider-pack/v1'
|| !/^sha256:[a-f0-9]{64}$/.test(manifest.digest ?? '')) throw Error('Invalid provider pack identity');
const archive = `${root}.tar.zst`;
const tar = spawn('tar', ['--no-xattrs', '-cf', '-', '-C', root, '.'], {
env: { ...process.env, COPYFILE_DISABLE: '1' }, stdio: ['ignore', 'pipe', 'inherit'],
});
const completed = new Promise((resolve, reject) => {
tar.on('error', reject);
tar.on('close', code => code === 0 ? resolve() : reject(Error('Provider pack archive creation failed')));
});
try {
await Promise.all([completed, pipeline(tar.stdout,
createZstdCompress({ params: { [constants.ZSTD_c_compressionLevel]: 3 } }), createWriteStream(archive))]);
} catch (error) {
tar.kill();
throw error;
}
const hash = createHash('sha256');
for await (const chunk of createReadStream(archive)) hash.update(chunk);
const receipt = {
schema: 'paperclip-runner/provider-pack-archive/v1',
encoding: 'tar+zstd',
providerPackDigest: manifest.digest,
sha256: hash.digest('hex'),
bytes: (await stat(archive)).size,
};
await writeFile(`${root}.archive.json`, JSON.stringify(receipt) + '\n');
return receipt;
}
async function runBoundedPool(tasks, concurrency) {
if (tasks.length === 0) return [];
const results = new Array(tasks.length);
const workerCount = Math.max(1, Math.min(concurrency, tasks.length));
let nextIndex = 0;
let failed = false;
const worker = async () => {
while (!failed) {
const index = nextIndex;
nextIndex += 1;
if (index >= tasks.length) return;
try {
results[index] = await tasks[index]();
} catch (error) {
failed = true;
throw error;
}
}
};
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
// Keep large immutable files separate so a fresh sandbox can reuse identical
// image bytes without trusting that image's older provider-pack identity.
export async function createProviderPackLayers(root, options = {}) {
const manifest = JSON.parse(await readFile(resolve(root, 'provider-pack.json'), 'utf8'));
if (manifest.schema !== 'paperclip-runner/remote-provider-pack/v1'
|| !/^sha256:[a-f0-9]{64}$/.test(manifest.digest ?? '')) throw Error('Invalid provider pack identity');
const directory = `${root}.archives`;
await mkdir(directory, { recursive: true });
const small = [], files = [];
const visit = async (relative = '') => {
for (const name of (await readdir(resolve(root, relative))).sort()) {
const path = relative ? `${relative}/${name}` : name;
const metadata = await lstat(resolve(root, path));
if (metadata.isDirectory()) { small.push(path); await visit(path); }
else if (metadata.isFile() && metadata.size >= 1024 * 1024) {
const hash = createHash('sha256');
for await (const chunk of createReadStream(resolve(root, path))) hash.update(chunk);
files.push({ path, bytes: metadata.size, mode: metadata.mode & 0o777, sha256: hash.digest('hex') });
} else if (metadata.isFile() || metadata.isSymbolicLink()) small.push(path);
else throw Error('Unsupported provider pack entry');
}
};
await visit();
// Archive N holds file N, so a file's archive name is its place in this
// list. The pack's `dist` is the Runner's own build output; every other
// large file is a dependency. The dependencies come first, so that their
// archive names do not change when the Runner's build gains or loses a
// large file. `dist` sorts before `node_modules`: in path order alone, one
// more large file under it renamed every dependency archive.
const own = file => file.path.startsWith('dist/');
files.splice(0, files.length, ...files.filter(file => !own(file)), ...files.filter(own));
const archive = async (name, paths) => {
const target = resolve(directory, name);
// Explicit NUL-separated names and no recursion avoid options, duplicate
// traversal, and hardlinks from an archive to files in a different layer.
const tar = spawn('tar', ['--no-xattrs', '--no-recursion', '-cf', '-', '-C', root,
'--null', '-T', '-'], { env: { ...process.env, COPYFILE_DISABLE: '1' }, stdio: ['pipe', 'pipe', 'inherit'] });
const completed = new Promise((resolve, reject) => {
tar.on('error', reject);
tar.on('close', code => code === 0 ? resolve() : reject(Error('Provider pack layer creation failed')));
});
tar.stdin.on('error', () => {}); // The child/pipeline supplies the causal failure.
tar.stdin.end(paths.map(path => `./${path}\0`).join(''));
// The compressor is ended only after it has taken every chunk. When end()
// arrives while the last chunk is still queued, Node finishes the zstd
// stream twice and the archive gets an empty frame at its end. Piping
// leaves that to timing, so the same files gave two different archives.
const compress = createZstdCompress({ params: { [constants.ZSTD_c_compressionLevel]: 3 } });
const feed = async () => {
for await (const chunk of tar.stdout) {
await new Promise((resolve, reject) => compress.write(chunk, error => error ? reject(error) : resolve()));
}
compress.end();
};
try {
await Promise.all([completed, feed(), pipeline(compress, createWriteStream(target))]);
} catch (error) { tar.kill(); compress.destroy(); throw error; }
const hash = createHash('sha256');
for await (const chunk of createReadStream(target)) hash.update(chunk);
return { sha256: hash.digest('hex'), bytes: (await stat(target)).size };
};
const requestedConcurrency = Number(options.concurrency);
const concurrency = Number.isInteger(requestedConcurrency) && requestedConcurrency >= 1
? requestedConcurrency
: Math.max(1, Math.min(availableParallelism(), 8));
const tasks = [
() => archive('overlay.tar.zst', small),
...files.map((file, index) => () => archive(`${index}.tar.zst`, [file.path])),
];
const [overlay, ...fileArchives] = await runBoundedPool(tasks, concurrency);
for (const [index, file] of files.entries()) file.archive = fileArchives[index];
const receipt = { schema: 'paperclip-runner/provider-pack-archive/v2', encoding: 'tar+zstd',
providerPackDigest: manifest.digest, overlay, files };
await writeFile(`${root}.archive.json`, JSON.stringify(receipt) + '\n');
return receipt;
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
if (!process.argv[2] || process.argv[3]) throw Error('Usage: create-provider-pack-archive.mjs PACK_ROOT');
await createProviderPackLayers(resolve(process.argv[2]));
}