mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 11:54:35 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Runner is the part that executes agent work: a daemon (`paperclip-runnerd`) and a provider pack of agent tools > - Part 2 of this stack builds the Runner alone as the image `runner-artifacts`, in one layer of about 850 MB > - Most of those bytes are provider binaries and Node. They change only with a provider version or the Node pin, but one layer means that every Runner source change makes all 850 MB new > - About half of the image is the pack's transport archives. A consumer that copies the pack as files does not need them > - This pull request splits the image into layers by how often their content changes, and adds a slim variant without the transport archives > - The benefit is that a new image shares about 93% of its bytes with the one before it, and a consumer that needs no transport archives pulls half as much ## Linked Issues or Issue Description Refs #21204 (part 2 of this stack) and #21167 (provider pack layers). No issue exists for this change. **Problem or motivation** The image from part 2 is one layer. A registry and a builder store and move layers, not files. A change to one Runner source file therefore makes a new 850 MB layer, although 790 MB of its content is the same as before. The image also holds the provider pack two times: as files, and as transport archives of those files. Some consumers need only the files. **Proposed solution** Write the image as four layers: the pack's large dependency files, everything else, the transport archives of those large files, and the other transport content. Make the two large layers byte-identical from build to build. Add the target `runner-artifacts-slim`, which is the first two layers. The full image is the slim image plus the two transport layers, as the same layer blobs. Check all of this on the built images. **Alternatives considered** - Two unrelated images. Then the registry stores the shared content two times unless the layers happen to match, and nothing ties the two together. - Split by path only, with all files of 1 MiB or more in the first layer. Six of those files are the Runner's own bundles under `dist`. They change with the Runner's source, so the first layer would change with it too. - Leave the transport archives as they were written. Their bytes then depended on timing (see "What Changed"), and the archive layer never repeated. **Roadmap alignment** This is build infrastructure. It adds no product feature and does not overlap an item in `ROADMAP.md`. This is part 3 of 4. Each part is on top of the one before it: 1. #21228 (merged): an optional field in the provider pack manifest 2. #21204: build and check the Runner image, with no publication 3. #21229: layers by change rate, and the slim variant (this pull request) 4. #21230: publish both variants from `master` ## What Changed - `Dockerfile`: two final stages. `runner-artifacts-slim` is two `COPY --link` layers. `runner-artifacts` starts from it and adds two more. The build stage sorts its output into the four layers. Every path is where it was in part 2: consumers copy by path and see no difference. | Layer | Content | Changes with | | --- | --- | --- | | 1 | The pack's dependency files of 1 MiB or more: provider binaries and Node | A provider version or the Node pin | | 2 | Everything else, with `runner-image.json` | Every Runner source change | | 3 (full only) | The transport archive of each file in layer 1 | The same as layer 1 | | 4 (full only) | The other transport archives, the overlay archive and the receipt | The same as layer 2 | - Stable bytes. The files of layers 1 and 3 get timestamp 0, and the large dependency files get it before their transport archives are written. A file under the pack's `dist` is the Runner's own output, so it and its archive are in layers 2 and 4. - `scripts/create-provider-pack-archive.mjs`, two separate commits. **This script also writes the application image's archives.** - The same file now gives the same archive every time. The script piped tar into Node's zstd compressor. When the pipe ended while the compressor still had its last chunk queued, Node finished the zstd stream two times, and the archive got an empty frame of nine bytes at its end. That depended on timing. In the pinned Linux base, 37 of 60 runs of the old code had the frame. The compressor is now ended only after it has taken every chunk. - Archive N holds file N of the receipt, and the receipt listed the files in path order. `dist` sorts before `node_modules`, so one more large file in the Runner's own output gave every dependency file another archive name, and layer 3 became a new blob with the same contents. The receipt now lists the files outside `dist` first. The readers (`provider-pack-layers.ts`, `retained-provider-pack-source.ts`) pair file N with `N.tar.zst` and do not use the path order, so they need no change. For the application image, the archive numbers change one time, and the bytes of each archive do not change. - `runner-image.json` is the same file in both variants. Its new field `fullImageOnly` names the two paths that only the full image has. `paths` did not change. - `scripts/runner-image-layout.mjs check` takes `--variant slim|full`. It is required and has no default. A slim tree that holds a transport path fails. A full tree without them fails. - `scripts/runner-image-oci.mjs` (new, 585 lines). It is not an input of the image, because the image build does not run it. - `unpack <oci archive> --out <tree>` writes the tree of an image from the layers of its archive, in order. It checks every blob against its digest. It refuses a whiteout, an absolute path, a path with `..`, a path that is written two times, an entry behind a link, and every entry that is not a file, a directory or a link. - `check-layers --slim <oci archive> --full <oci archive>` checks the table above on the built images. It reads the receipt to decide which archive belongs in which layer. It fails when the full image does not start with the slim image's layer blobs in the same order, when a path that is not a directory is in two layers, and when a shared layer holds transport content under any name or directory. - The script reads the archive and its layers itself. It does not use the system's `tar`, so every platform reads them the same way. It finds a member only under the name that buildx gives it. - `.github/workflows/runner-image.yml`: each leg builds each variant one time, as an OCI archive and nothing else. It unpacks both archives, runs `check` on each tree with its variant, runs `check-layers`, and runs the smoke matrix on the slim tree. The tree that is checked is therefore the bytes of the image, not a second export of the same build. Every step that builds has a time limit. The workflow still has no registry access. - Why one export: in the first runs of this pull request, the slim build stalled on all four legs. Each build command had two exports, a tree and an archive. The slim command, with every stage from the cache, wrote its archive and then made no progress on the tree for 50 minutes. A test now holds the rule of one export and a time limit for each build command. - The smoke matrix runs on the slim tree. The daemon is in a layer that both variants share, so one run covers both. - `server/src/__tests__/runner-image-identity.test.ts`: the test that holds the rules for the Runner stages now finds a stage wherever BuildKit starts one. It fails for `FROM x as name`, a flag on `FROM`, a lowercase or indented `COPY`, an `ADD` or `ONBUILD`, a `COPY` with another flag, and a `COPY` that continues on the next line. Nine samples show each case. - Two comments are corrected. The comment on `PAPERCLIP_RUNNER_INPUTS_DIGEST` in `build-provider-pack.mjs` said that no check reads the field. The `Dockerfile` comment on the publication argument named a workflow "that builds the image for publication". - `doc/runner-image-contract.md` (159 lines): the two variants, the section "Layers", how the checks get their tree, and the new checks. `doc/DOCKER.md` names the slim target. Script sizes: `runner-image-layout.mjs` 969 lines, `runner-image-oci.mjs` 585, `runner-image-identity.mjs` 166, `create-provider-pack-archive.mjs` 114. ## Verification Image identity at this commit: `a544fc9dde780963419ede0f34252f3a57de43a760d41d3eb8fcd4f577504f6a`. Linux (the pinned `node:24.22.3-bookworm` base with GNU tar 1.34 and zstd, the worktree mounted read-only): - `runner-image-identity.test.ts` (41), `runner-image-layout.test.ts` (100), `runner-image-oci.test.ts` (50), `runner-image-workflow.test.ts` (8), `provider-pack-archive.test.ts` (47, none skipped), `retained-provider-pack-source.test.ts` (19), `remote-provider-pack-verification.test.ts`, `docker-image-layer-reuse.test.ts`, `docker-build-stamp.test.ts`: 293 tests pass in 9 files. - The same files pass on macOS. The tests of `check-layers` failed on Linux in the first runs of this pull request: their fixtures named the archive members `./index.json`, which bsdtar finds and GNU tar does not. The fixtures now name the members as buildx does. `linux/arm64`, on a local Docker host, with the new export path: - Each variant builds as an OCI archive only: the full target in 156 seconds without a cache, the slim target in 5 seconds from the cache. - `unpack` writes the full image (10,519 entries that are not directories) in 4 seconds, and the slim image in 4 seconds. - `check <tree> --variant <variant> --expect-inputs-digest <digest> --expect-source-revision <sha> --expect-architecture arm64` passes on each unpacked tree. `runner-image.json` is the same file in both. - `check-layers --slim <slim> --full <full>` passes. - The smoke matrix passes on all five base images, from the unpacked slim tree. | Layer | Digest | Bytes | In | | --- | --- | --- | --- | | 1 | `sha256:3f21b15b3a99…70ac1c` | 379,609,589 | slim and full | | 2 | `sha256:d5567acc977f…b4f12a` | 43,906,956 | slim and full | | 3 | `sha256:6a340088ca2c…6ba5b5` | 410,938,259 | full | | 4 | `sha256:789e97f5db88…3eab44` | 15,656,249 | full | - The slim image is 423,516,545 bytes in two layers. The full image is 850,111,053 bytes in four. Stability, with three builds that share no cache for the build step: | Build | Source revision | Runner build output | Layer 1 | Layer 2 | Layer 3 | Layer 4 | | --- | --- | --- | --- | --- | --- | --- | | A | `aaaa…` | this commit: 6 files of 1 MiB or more under `dist` | `3f21b15b…` | `d5567acc…` | `6a340088…` | `789e97f5…` | | B | `bbbb…` | this commit | `3f21b15b…` | `a2f8a4fe…` | `6a340088…` | `4e6c492d…` | | D | `dddd…` | one new source file that adds two large files under `dist` | `3f21b15b…` | `33b0bdaf…` | `6a340088…` | `0ea322bf…` | - Layers 1 and 3 are byte-identical in all three: 790,547,848 of 850,111,053 bytes, 93%. Build D has two more large files under `dist`, eight in place of six, and another image identity. Its dependency files keep the archive numbers 0 to 20. With the earlier numbering, those numbers moved by two, and layer 3 was a new blob with the same contents. - Layer 1 has the same digest as before this round. Layer 3 has a new digest one time, because the archives have new numbers. Other checks: - `tests/runner-e2e` workflow tests: 39 pass. `node --test .github/scripts/tests/*.test.mjs`: 799 pass. `node --test` on the image contract scripts: 33 pass. `check-docker-deps-stage.mjs`, `check-node-version-policy.mjs` and `docker buildx build --check` report nothing. GitHub, at this head: - The `Runner image` workflow passes on both architectures with the new export path: `Build and check (amd64)` in 14m41s and `Build and check (arm64)` in 8m41s. Each leg builds both variants, checks both layouts and the layer rule, and runs the smoke matrix. The first runs of this pull request stalled in the slim export before any check. Never run: - `native-session-executor.test.ts`. It does not load on this host, with or without this change, because `@paperclipai/plugin-sdk` is not built here. It imports the reader of the retained pack and no archive number. - The full test suite and the full typecheck. CI must supply them. ## Risks - The two changes to `create-provider-pack-archive.mjs` change the application image's transport archives: about half of them lose nine bytes, and all of them get new numbers one time. An archive's content does not change. A reader pairs file N of a receipt with archive N of the same build. - The large dependency files in the pack, and in their transport archives, now have the modification time 0 (1970). Before, they had the build time. Nothing in this repository reads those times. - `unpack` is a reader of tar and gzip that this repository owns. It reads the layers that BuildKit, GNU tar and bsdtar write (tested with each), and it fails for a header it does not know. - The check on the built images, not the recipe, is what proves the layer rule; it runs in each leg of the workflow. - `check` now needs `--variant`. A caller that does not pass it fails with a clear message. No caller exists outside this repository yet. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`), Anthropic, used through Claude Code with tool use (shell, file edits, local Docker builds). ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
419 lines
26 KiB
TypeScript
419 lines
26 KiB
TypeScript
import { execFile, spawnSync } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
import { promises as fs } from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { promisify } from "node:util";
|
|
import { afterEach, expect, it, vi } from "vitest";
|
|
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
|
import { readProviderPackArchive, stageProviderPackArchive } from "./provider-pack-archive.js";
|
|
import { uploadVerifiedProviderPack } from "./provider-pack-upload.js";
|
|
// @ts-expect-error Build-time script has no TypeScript declaration.
|
|
import { createProviderPackArchive, createProviderPackLayers } from "../../../../scripts/create-provider-pack-archive.mjs";
|
|
|
|
const exec = promisify(execFile);
|
|
const hasZstd = spawnSync("zstd", ["--version"]).status === 0;
|
|
const roots: string[] = [];
|
|
const digest = `sha256:${"a".repeat(64)}`;
|
|
afterEach(async () => { await Promise.all(roots.splice(0).map(root => fs.rm(root, { recursive: true, force: true }))); });
|
|
|
|
async function fixture() {
|
|
const root = await fs.mkdtemp(path.join(os.tmpdir(), "provider-archive-"));
|
|
roots.push(root);
|
|
const pack = path.join(root, "pack");
|
|
await fs.mkdir(path.join(pack, "bin"), { recursive: true });
|
|
await fs.writeFile(path.join(pack, "provider-pack.json"), JSON.stringify({ schema: "paperclip-runner/remote-provider-pack/v1", digest }));
|
|
await fs.writeFile(path.join(pack, "bin", "tool"), "#!/bin/sh\necho fixture\n", { mode: 0o755 });
|
|
await fs.symlink("bin/tool", path.join(pack, "tool"));
|
|
await createProviderPackArchive(pack);
|
|
const archive = (await readProviderPackArchive(pack, digest))!;
|
|
if ("kind" in archive) throw Error("Expected historical single archive");
|
|
return { root, pack, archive };
|
|
}
|
|
|
|
const tar = await Promise.all(["gtar", "tar"].map(async name => {
|
|
try { const { stdout } = await exec(name, ["--version"]); return stdout.includes("GNU tar") ? name : null; }
|
|
catch { return null; }
|
|
})).then(names => names.find(Boolean));
|
|
|
|
async function runner(root: string, corrupt = false, toolPath?: string) {
|
|
const bin = path.join(root, "commands");
|
|
await fs.mkdir(bin);
|
|
const resolved = (await exec("sh", ["-c", 'command -v "$1"', "sh", tar!])).stdout.trim();
|
|
await fs.symlink(resolved, path.join(bin, "tar"));
|
|
const syncIn = vi.fn<NonNullable<CommandManagedRuntimeRunner["syncIn"]>>(async operations => {
|
|
for (const operation of operations) for (const file of operation.files) {
|
|
expect(file.kind).toBe("file");
|
|
await fs.mkdir(path.dirname(file.targetPath), { recursive: true });
|
|
await fs.copyFile(file.sourcePath, file.targetPath);
|
|
if (corrupt) await fs.appendFile(file.targetPath, "corrupted in transit");
|
|
}
|
|
return { operations: await Promise.all(operations.map(async operation => ({ operationId: operation.operationId, filesTransferred: operation.files.length,
|
|
bytesTransferred: (await Promise.all(operation.files.map(async file => (await fs.stat(file.sourcePath)).size))).reduce((sum, size) => sum + size, 0) }))) };
|
|
});
|
|
const execute = vi.fn<CommandManagedRuntimeRunner["execute"]>(async input => {
|
|
try {
|
|
const result = await exec(input.command, input.args ?? [], { env: { ...process.env, PATH: toolPath ?? `${bin}:${process.env.PATH}` } });
|
|
return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stdout: result.stdout, stderr: result.stderr };
|
|
} catch (error) {
|
|
return { exitCode: 1, signal: null, pid: null, startedAt: null, timedOut: false, stdout: "", stderr: String(error) };
|
|
}
|
|
});
|
|
return { syncIn, execute };
|
|
}
|
|
|
|
it("keeps historical/source packs without an archive on the existing path", async () => {
|
|
expect(await readProviderPackArchive("/does-not-exist/provider-pack", digest)).toBeNull();
|
|
});
|
|
|
|
it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk", async version => {
|
|
const { pack } = version === "v2" ? await layeredFixture() : await fixture();
|
|
const archivePath = version === "v2" ? `${pack}.archives/overlay.tar.zst` : `${pack}.tar.zst`;
|
|
const controller = new AbortController();
|
|
const handle = await fs.open(archivePath, "r");
|
|
const prototype = Object.getPrototypeOf(handle) as typeof handle;
|
|
await handle.close();
|
|
const originalStream = prototype.createReadStream;
|
|
const streaming = vi.spyOn(prototype, "createReadStream").mockImplementation(function(this: typeof handle, options) {
|
|
const stream = originalStream.call(this, options);
|
|
stream.once("data", () => controller.abort(new Error("owned archive read stopped")));
|
|
return stream;
|
|
});
|
|
try {
|
|
await expect(readProviderPackArchive(pack, digest, controller.signal)).rejects.toThrow(/abort|owned archive read stopped/i);
|
|
expect(controller.signal.aborted).toBe(true);
|
|
} finally { streaming.mockRestore(); }
|
|
});
|
|
|
|
async function layeredFixture() {
|
|
const { root, pack } = await fixture();
|
|
await fs.writeFile(path.join(pack, "bin", "large"), Buffer.alloc(1024 * 1024, 42), { mode: 0o755 });
|
|
const receipt = await createProviderPackLayers(pack);
|
|
const archive = (await readProviderPackArchive(pack, digest))!;
|
|
if (!("kind" in archive)) throw Error("Expected layered archive");
|
|
return { root, pack, receipt, archive };
|
|
}
|
|
|
|
it("writes the same archive for the same file every time, with nothing after the frame", async () => {
|
|
// Ending the compressor while its last chunk was still queued made Node
|
|
// finish the zstd stream twice, and about half the archives got an empty
|
|
// frame at their end. An image layer of these archives then never repeated.
|
|
const emptyFrame = Buffer.from("28b52ffd2000010000", "hex");
|
|
const seen = new Set<string>();
|
|
for (let trial = 0; trial < 12; trial += 1) {
|
|
const { pack } = await fixture();
|
|
const large = path.join(pack, "bin", "large");
|
|
await fs.writeFile(large, Buffer.alloc(1024 * 1024, 42), { mode: 0o755 });
|
|
await fs.utimes(large, 0, 0);
|
|
const receipt = await createProviderPackLayers(pack);
|
|
seen.add(receipt.files[0].archive.sha256);
|
|
for (const name of ["0.tar.zst", "overlay.tar.zst"]) {
|
|
const bytes = await fs.readFile(path.join(`${pack}.archives`, name));
|
|
expect(bytes.subarray(-emptyFrame.length).equals(emptyFrame), name).toBe(false);
|
|
}
|
|
}
|
|
expect([...seen]).toHaveLength(1);
|
|
});
|
|
|
|
it("names the archives of dependency files without regard to the Runner's own large files", async () => {
|
|
// Archive N holds file N of the receipt. `dist` sorts before `node_modules`,
|
|
// so in path order one more large file in the Runner's build output renamed
|
|
// the archive of every dependency file.
|
|
const large = Buffer.alloc(1024 * 1024, 42);
|
|
const receiptOf = async (own: string[]) => {
|
|
const { pack } = await fixture();
|
|
for (const file of ["node_modules/dependency/tool", "bin/large", ...own]) {
|
|
await fs.mkdir(path.dirname(path.join(pack, file)), { recursive: true });
|
|
await fs.writeFile(path.join(pack, file), large, { mode: 0o755 });
|
|
await fs.utimes(path.join(pack, file), 0, 0);
|
|
}
|
|
const receipt = await createProviderPackLayers(pack);
|
|
const archive = (await readProviderPackArchive(pack, digest))!;
|
|
if (!("kind" in archive)) throw Error("Expected layered archive");
|
|
// What a reader pairs: file N of the receipt with N.tar.zst.
|
|
const paired = await Promise.all(archive.files.map(async (file: { path: string; archive: { sha256: string } }, index: number) =>
|
|
[file.path, `${index}.tar.zst`, createHash("sha256").update(await fs.readFile(path.join(`${pack}.archives`, `${index}.tar.zst`))).digest("hex") === file.archive.sha256]));
|
|
return { paths: receipt.files.map((file: { path: string }) => file.path), paired };
|
|
};
|
|
const before = await receiptOf(["dist/cli/one.js"]);
|
|
const after = await receiptOf(["dist/cli/one.js", "dist/a-new-large-file.js", "dist/cli/two.js"]);
|
|
expect(before.paths).toEqual(["bin/large", "node_modules/dependency/tool", "dist/cli/one.js"]);
|
|
expect(after.paths).toEqual(["bin/large", "node_modules/dependency/tool", "dist/a-new-large-file.js", "dist/cli/one.js", "dist/cli/two.js"]);
|
|
// The dependency files keep their archive names, and every pairing a reader makes still holds.
|
|
expect(after.paired.slice(0, 2)).toEqual(before.paired.slice(0, 2));
|
|
expect(after.paired.every(([, , matches]) => matches)).toBe(true);
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("reuses only byte-matched image files, keeps modes, and never shares writable hardlinks", async () => {
|
|
const { root, pack, archive } = await layeredFixture();
|
|
const remote = await runner(root);
|
|
const targetPath = path.join(root, "fresh");
|
|
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [pack] })).toBe(true);
|
|
expect(remote.syncIn.mock.calls[0]![0][0]!.files).toHaveLength(1);
|
|
expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes);
|
|
const original = path.join(pack, "bin/large"), copied = path.join(targetPath, "bin/large");
|
|
expect(await fs.readFile(copied)).toEqual(await fs.readFile(original));
|
|
expect((await fs.stat(copied)).mode & 0o777).toBe(0o755);
|
|
expect((await fs.stat(copied)).ino).not.toBe((await fs.stat(original)).ino);
|
|
await fs.writeFile(copied, "changed");
|
|
expect((await fs.stat(original)).size).toBe(1024 * 1024);
|
|
expect(await fs.readlink(path.join(targetPath, "tool"))).toBe("bin/tool");
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("stages a complete layered pack into a fresh nested runtime directory", async () => {
|
|
const { root, pack, archive } = await layeredFixture();
|
|
const remote = await runner(root);
|
|
const workspace = path.join(root, "workspace");
|
|
await fs.mkdir(workspace);
|
|
const targetPath = path.join(workspace, ".paperclip-runtime", "paperclip-runner", "provider-pack");
|
|
await expect(fs.lstat(path.dirname(targetPath))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [pack] })).toBe(true);
|
|
expect(await fs.readFile(path.join(targetPath, "bin/large"))).toEqual(await fs.readFile(path.join(pack, "bin/large")));
|
|
expect(await fs.readFile(path.join(targetPath, "provider-pack.json"))).toEqual(await fs.readFile(path.join(pack, "provider-pack.json")));
|
|
expect(await fs.readlink(path.join(targetPath, "tool"))).toBe("bin/tool");
|
|
for (const directory of [targetPath, path.dirname(targetPath), path.dirname(path.dirname(targetPath))]) {
|
|
expect((await fs.stat(directory)).mode & 0o777).toBe(0o700);
|
|
}
|
|
expect((await fs.stat(path.join(targetPath, "bin/large"))).ino).not.toBe((await fs.stat(path.join(pack, "bin/large"))).ino);
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd).each(["missing", "wrong-digest", "symlink", "ancestor-symlink"])("transfers a large layer when the image file is %s", async reason => {
|
|
const { root, pack, archive } = await layeredFixture();
|
|
const remote = await runner(root);
|
|
const old = path.join(root, "old");
|
|
await fs.cp(pack, old, { recursive: true });
|
|
const large = path.join(old, "bin/large");
|
|
if (reason === "missing") await fs.unlink(large);
|
|
if (reason === "wrong-digest") await fs.writeFile(large, Buffer.alloc(1024 * 1024, 43));
|
|
if (reason === "symlink") { await fs.unlink(large); await fs.symlink(path.join(pack, "bin/large"), large); }
|
|
if (reason === "ancestor-symlink") { await fs.rm(path.join(old, "bin"), { recursive: true }); await fs.symlink(path.join(pack, "bin"), path.join(old, "bin")); }
|
|
const targetPath = path.join(root, "fresh");
|
|
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [old] })).toBe(true);
|
|
expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes + archive.files[0]!.archive.bytes);
|
|
expect(await fs.readFile(path.join(targetPath, "bin/large"))).toEqual(await fs.readFile(path.join(pack, "bin/large")));
|
|
});
|
|
|
|
it.each(["traversal", "duplicate", "ancestor", "mode", "digest", "layer-symlink"])("rejects invalid layer metadata or bytes: %s", async reason => {
|
|
const { pack, receipt } = await layeredFixture();
|
|
if (reason === "traversal") receipt.files[0].path = "../outside";
|
|
if (reason === "duplicate") receipt.files.push(receipt.files[0]);
|
|
if (reason === "ancestor") receipt.files.push({ ...receipt.files[0], path: "bin" });
|
|
if (reason === "mode") receipt.files[0].mode = 0o4755;
|
|
if (reason === "digest") receipt.overlay.sha256 = "0".repeat(64);
|
|
if (reason === "layer-symlink") {
|
|
const overlay = `${pack}.archives/overlay.tar.zst`;
|
|
await fs.rename(overlay, `${overlay}.original`); await fs.symlink(`${overlay}.original`, overlay);
|
|
}
|
|
await fs.writeFile(`${pack}.archive.json`, JSON.stringify(receipt));
|
|
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow();
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("rejects a corrupt missing layer before transfer and a corrupt upload before extraction", async () => {
|
|
const { root, pack, archive } = await layeredFixture();
|
|
const remote = await runner(root, true);
|
|
const targetPath = path.join(root, "fresh");
|
|
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath })).rejects.toThrow("runner_remote_provider_archive_extract_failed");
|
|
expect(await fs.readdir(targetPath)).toEqual([]);
|
|
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
|
|
await fs.appendFile(`${pack}.archives/0.tar.zst`, "corrupt");
|
|
remote.syncIn.mockClear();
|
|
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath: `${targetPath}-2` })).rejects.toThrow("runner_remote_provider_archive_invalid: size_mismatch");
|
|
await fs.unlink(`${pack}.archives/0.tar.zst`);
|
|
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath: `${targetPath}-3` })).rejects.toThrow("runner_remote_provider_archive_invalid: archive_unreadable");
|
|
expect(remote.syncIn).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd).each(["directory", "file", "symlink"])("rejects an existing layered target %s or invalid reuse receipts", async kind => {
|
|
const { root, archive } = await layeredFixture();
|
|
const remote = await runner(root);
|
|
const targetPath = path.join(root, "target"), other = path.join(root, "other");
|
|
await fs.mkdir(other);
|
|
if (kind === "directory") await fs.mkdir(targetPath);
|
|
else if (kind === "file") await fs.writeFile(targetPath, "untouched");
|
|
else await fs.symlink(other, targetPath);
|
|
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath })).rejects.toThrow("runner_remote_provider_archive_reuse_failed");
|
|
expect(await fs.readdir(other)).toEqual([]);
|
|
if (kind === "directory") expect(await fs.readdir(targetPath)).toEqual([]);
|
|
if (kind === "file") expect(await fs.readFile(targetPath, "utf8")).toBe("untouched");
|
|
remote.execute.mockResolvedValue({ exitCode: 0, timedOut: false, stdout: "[999999]", stderr: "", signal: null, pid: null, startedAt: null });
|
|
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath: `${targetPath}-2` })).rejects.toThrow("runner_remote_provider_archive_reuse_failed");
|
|
expect(remote.syncIn).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["identity", "bytes", "sha256", "json", "symlink"])("rejects invalid archive %s", async failure => {
|
|
const { pack } = await fixture();
|
|
const receiptPath = `${pack}.archive.json`;
|
|
const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
|
|
if (failure === "identity") receipt.providerPackDigest = `sha256:${"b".repeat(64)}`;
|
|
if (failure === "bytes") receipt.bytes++;
|
|
if (failure === "sha256") receipt.sha256 = "c".repeat(64);
|
|
await fs.writeFile(receiptPath, failure === "json" ? "{" : JSON.stringify(receipt));
|
|
if (failure === "symlink") {
|
|
await fs.rename(`${pack}.tar.zst`, `${pack}.original`);
|
|
await fs.symlink(`${pack}.original`, `${pack}.tar.zst`);
|
|
}
|
|
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow();
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("uploads build-time bytes to fresh targets, preserving files, modes and symlinks", async () => {
|
|
const { root, archive } = await fixture();
|
|
const remote = await runner(root);
|
|
for (const name of ["first ' ; #", "follow-up"]) {
|
|
const targetPath = path.join(root, name);
|
|
await stageProviderPackArchive({ archive, runner: remote, targetPath });
|
|
expect(await fs.readFile(path.join(targetPath, "bin/tool"), "utf8")).toBe("#!/bin/sh\necho fixture\n");
|
|
expect((await fs.stat(path.join(targetPath, "bin/tool"))).mode & 0o777).toBe(0o755);
|
|
expect((await fs.stat(targetPath)).mode & 0o777).toBe(0o700);
|
|
expect(await fs.readlink(path.join(targetPath, "tool"))).toBe("bin/tool");
|
|
}
|
|
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
|
|
expect(remote.syncIn).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("rejects corrupt transferred bytes before extracting and cleans scratch", async () => {
|
|
const { root, archive } = await fixture();
|
|
const targetPath = path.join(root, "target");
|
|
await expect(stageProviderPackArchive({ archive, runner: await runner(root, true), targetPath }))
|
|
.rejects.toThrow("runner_remote_provider_archive_extract_failed");
|
|
expect(await fs.readdir(root)).not.toContain("target");
|
|
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("does not follow a remote target symlink", async () => {
|
|
const { root, archive } = await fixture();
|
|
const targetPath = path.join(root, "target");
|
|
const other = path.join(root, "other");
|
|
await fs.mkdir(other); await fs.symlink(other, targetPath);
|
|
await expect(stageProviderPackArchive({ archive, runner: await runner(root), targetPath }))
|
|
.rejects.toThrow("runner_remote_provider_archive_extract_failed");
|
|
expect(await fs.readdir(other)).toEqual([]);
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("rejects malformed tar even with a matching transport digest", async () => {
|
|
const { root, archive } = await fixture();
|
|
await fs.writeFile(archive.sourcePath, "invalid tar");
|
|
archive.sha256 = createHash("sha256").update("invalid tar").digest("hex");
|
|
await expect(stageProviderPackArchive({ archive, runner: await runner(root), targetPath: path.join(root, "target") }))
|
|
.rejects.toThrow("runner_remote_provider_archive_extract_failed");
|
|
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
|
|
});
|
|
|
|
it("keeps the directory fallback when the remote has no zstd", async () => {
|
|
const { archive } = await fixture();
|
|
const remote = { syncIn: vi.fn(), execute: vi.fn().mockResolvedValue({ exitCode: 127, timedOut: false }) };
|
|
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath: "/unused" })).toBe(false);
|
|
expect(remote.syncIn).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd).each(["v1", "v2"])("installs verified %s archive bytes without reading the unused expanded pack", async version => {
|
|
const { root, pack } = version === "v1" ? await fixture() : await layeredFixture();
|
|
const remote = await runner(root);
|
|
const targetPath = path.join(root, "uploaded");
|
|
const expected = await fs.readFile(path.join(pack, "bin/tool"));
|
|
// Only the archive is uploaded. The expanded tree is a different source,
|
|
// and deliberately no longer matches the bytes sealed in that archive.
|
|
await fs.writeFile(path.join(pack, "bin/tool"), "unused expanded bytes");
|
|
const verifyDirectory = vi.fn(() => { throw Error("expanded_directory_was_read"); });
|
|
const stageDirectory = vi.fn(async () => { throw Error("directory_was_uploaded"); });
|
|
const verifyUploaded = vi.fn(async () => {
|
|
expect(await fs.readFile(path.join(targetPath, "bin/tool"))).toEqual(expected);
|
|
expect(JSON.parse(await fs.readFile(path.join(targetPath, "provider-pack.json"), "utf8")).digest).toBe(digest);
|
|
});
|
|
await uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: digest, runner: remote, cwd: root,
|
|
targetPath, reuseRoots: [], verifyDirectory, stageDirectory, verifyUploaded });
|
|
expect(verifyDirectory).not.toHaveBeenCalled();
|
|
expect(stageDirectory).not.toHaveBeenCalled();
|
|
expect(verifyUploaded).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it.each(["absent", "unsupported"])("verifies directory bytes before fallback when the archive is %s", async mode => {
|
|
const { root, pack } = await fixture();
|
|
if (mode === "absent") await fs.unlink(`${pack}.archive.json`);
|
|
const remote = { syncIn: vi.fn(), execute: vi.fn().mockResolvedValue({ exitCode: 0, timedOut: false, stdout: "", stderr: "" }) };
|
|
// The capability probe fails; clearing the old pack succeeds.
|
|
remote.execute.mockResolvedValueOnce({ exitCode: 0, timedOut: false });
|
|
remote.execute.mockResolvedValue({ exitCode: 127, timedOut: false });
|
|
const stageDirectory = vi.fn(), verifyUploaded = vi.fn();
|
|
await expect(uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: digest, runner: remote, cwd: root,
|
|
targetPath: path.join(root, "uploaded"), reuseRoots: [], verifyDirectory: () => { throw Error("directory_digest_mismatch"); },
|
|
stageDirectory, verifyUploaded })).rejects.toThrow("directory_digest_mismatch");
|
|
expect(remote.syncIn).not.toHaveBeenCalled();
|
|
expect(stageDirectory).not.toHaveBeenCalled();
|
|
expect(verifyUploaded).not.toHaveBeenCalled();
|
|
});
|
|
|
|
// A retained continuation can select a pack from an earlier release. The
|
|
// controller's build-time archives then carry a different identity. That is an
|
|
// artifact incompatibility, not archive corruption, and it must not clear the
|
|
// remote pack or upload the controller's different pack.
|
|
it.each(["v1", "v2", "directory"])("refuses a selected pack this controller does not ship (%s source)", async source => {
|
|
const { root, pack } = source === "v2" ? await layeredFixture() : await fixture();
|
|
if (source === "directory") await fs.unlink(`${pack}.archive.json`);
|
|
const retained = `sha256:${"b".repeat(64)}`;
|
|
const remote = { syncIn: vi.fn(), execute: vi.fn().mockResolvedValue({ exitCode: 0, timedOut: false, stdout: "", stderr: "" }) };
|
|
const verifyDirectory = vi.fn(), stageDirectory = vi.fn(), verifyUploaded = vi.fn();
|
|
const upload = uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: retained, runner: remote, cwd: root,
|
|
targetPath: path.join(root, "uploaded"), reuseRoots: [], verifyDirectory, stageDirectory, verifyUploaded });
|
|
await expect(upload).rejects.toThrow(
|
|
`runner_remote_provider_artifact_incompatible: selected provider pack ${"b".repeat(12)} is not the controller's pack ${"a".repeat(12)}`);
|
|
expect(remote.execute).not.toHaveBeenCalled();
|
|
expect(remote.syncIn).not.toHaveBeenCalled();
|
|
for (const step of [verifyDirectory, stageDirectory, verifyUploaded]) expect(step).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd).each(["v1", "v2"])("names the failed %s archive check in the run-visible error", async version => {
|
|
const { pack } = version === "v1" ? await fixture() : await layeredFixture();
|
|
const archive = version === "v1" ? `${pack}.tar.zst` : `${pack}.archives/overlay.tar.zst`;
|
|
const bytes = await fs.readFile(archive);
|
|
await fs.appendFile(archive, "x");
|
|
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: size_mismatch");
|
|
bytes[bytes.length - 1] ^= 1;
|
|
await fs.writeFile(archive, bytes);
|
|
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: sha256_mismatch");
|
|
const receipt = JSON.parse(await fs.readFile(`${pack}.archive.json`, "utf8"));
|
|
await fs.writeFile(`${pack}.archive.json`, JSON.stringify({ ...receipt, providerPackDigest: `sha256:${"c".repeat(64)}` }));
|
|
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: receipt_identity_mismatch");
|
|
await fs.writeFile(`${pack}.archive.json`, "{");
|
|
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: receipt_unreadable");
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd)("rejects an installed pack that fails final verification", async () => {
|
|
const { root, pack } = await fixture();
|
|
const remote = await runner(root), targetPath = path.join(root, "uploaded");
|
|
const verifyUploaded = vi.fn(async () => { throw Error("installed_digest_mismatch"); });
|
|
await expect(uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: digest, runner: remote, cwd: root,
|
|
targetPath, reuseRoots: [], verifyDirectory: () => {}, stageDirectory: async () => {}, verifyUploaded }))
|
|
.rejects.toThrow("installed_digest_mismatch");
|
|
expect(remote.syncIn).toHaveBeenCalledOnce();
|
|
expect(verifyUploaded).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it.skipIf(!tar || !hasZstd).each([
|
|
["v1", "bsd-tar"], ["v2", "bsd-tar"],
|
|
["v1", "older-gnu-tar"], ["v2", "older-gnu-tar"],
|
|
["v1", "missing-sha256sum"], ["v2", "missing-sha256sum"],
|
|
])("keeps %s on directory staging with %s before creating a target or uploading", async (version, unsupported) => {
|
|
const { root, archive } = version === "v1" ? await fixture() : await layeredFixture();
|
|
const tools = path.join(root, "tools");
|
|
await fs.mkdir(tools);
|
|
await fs.symlink(process.execPath, path.join(tools, "node"));
|
|
for (const name of ["sh", "zstd", "cut", ...(unsupported === "missing-sha256sum" ? [] : ["sha256sum"])]) {
|
|
const resolved = (await exec("sh", ["-c", 'command -v "$1"', "sh", name])).stdout.trim();
|
|
await fs.symlink(resolved, path.join(tools, name));
|
|
}
|
|
if (unsupported === "bsd-tar") {
|
|
await fs.writeFile(path.join(tools, "tar"), "#!/bin/sh\nprintf 'bsdtar 3.8.2\\n'\n", { mode: 0o755 });
|
|
} else if (unsupported === "older-gnu-tar") {
|
|
await fs.writeFile(path.join(tools, "tar"), '#!/bin/sh\nif [ "$1" = "--version" ]; then printf "tar (GNU tar) 1.30\\n"; else exit 64; fi\n', { mode: 0o755 });
|
|
} else {
|
|
const resolved = (await exec("sh", ["-c", 'command -v "$1"', "sh", tar!])).stdout.trim();
|
|
await fs.symlink(resolved, path.join(tools, "tar"));
|
|
}
|
|
const remote = await runner(root, false, tools);
|
|
const targetPath = path.join(root, "fresh");
|
|
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath })).toBe(false);
|
|
expect(remote.execute).toHaveBeenCalledOnce();
|
|
expect(remote.syncIn).not.toHaveBeenCalled();
|
|
await expect(fs.lstat(targetPath)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|