diff --git a/server/src/services/native-runtime/provider-pack-archive.test.ts b/server/src/services/native-runtime/provider-pack-archive.test.ts index 70462a6d46a..ee772f2feda 100644 --- a/server/src/services/native-runtime/provider-pack-archive.test.ts +++ b/server/src/services/native-runtime/provider-pack-archive.test.ts @@ -8,6 +8,7 @@ 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"; +import { providerPackReusePlan } from "./provider-pack-layers.js"; // @ts-expect-error Build-time script has no TypeScript declaration. import { createProviderPackArchive, createProviderPackLayers } from "../../../../scripts/create-provider-pack-archive.mjs"; @@ -114,6 +115,93 @@ async function layeredFixture() { return { root, pack, receipt, archive }; } +const toolPath = "node_modules/.pnpm/tool@1.0.0/node_modules/tool/bin/tool"; +const twinPath = "node_modules/.pnpm/tool-baseline@1.0.0/node_modules/tool-baseline/bin/tool"; +const otherTwinPath = "provider-assets/kimi/linux-x64/runtime/node/bin/tool"; + +/** A pack that repeats one large binary under three paths, like the OpenCode + * binary in a release pack, with an older image that has it under one path. */ +async function repeatedBytesFixture(modes: Record = {}) { + const { root, pack } = await fixture(); + for (const relative of [toolPath, twinPath, otherTwinPath]) { + await fs.mkdir(path.dirname(path.join(pack, relative)), { recursive: true }); + await fs.writeFile(path.join(pack, relative), Buffer.alloc(2 * 1024 * 1024, 9)); + await fs.chmod(path.join(pack, relative), modes[relative] ?? 0o755); + } + await createProviderPackLayers(pack); + const archive = (await readProviderPackArchive(pack, digest))!; + if (!("kind" in archive)) throw Error("Expected layered archive"); + const image = path.join(root, "image"); + await fs.cp(pack, image, { recursive: true, verbatimSymlinks: true }); + for (const relative of [twinPath, otherTwinPath]) await fs.rm(path.join(image, relative)); + return { root, pack, image, archive }; +} + +it.skipIf(!tar || !hasZstd)("stores repeated bytes once, from an image file under another path, without transferring them", async () => { + const { root, pack, image, archive } = await repeatedBytesFixture(); + const remote = await runner(root); + const targetPath = path.join(root, "fresh"); + const before = (await fs.readdir(image, { recursive: true })).sort(); + expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [image] })).toBe(true); + const staged = await Promise.all([toolPath, twinPath, otherTwinPath].map(relative => fs.lstat(path.join(targetPath, relative)))); + // Physical files inside the pack, sharing one private inode that is not the image's. + for (const stat of staged) expect(stat.isFile()).toBe(true); + expect(new Set(staged.map(stat => stat.ino)).size).toBe(1); + expect(staged[0]!.ino).not.toBe((await fs.stat(path.join(image, toolPath))).ino); + expect(staged[0]!.nlink).toBe(3); + for (const relative of [toolPath, twinPath, otherTwinPath]) { + expect(await fs.readFile(path.join(targetPath, relative))).toEqual(await fs.readFile(path.join(pack, relative))); + expect((await fs.stat(path.join(targetPath, relative))).mode & 0o777).toBe(0o755); + } + // Only the small-file overlay crosses the network, and the image is unchanged. + expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes); + expect((await fs.readdir(image, { recursive: true })).sort()).toEqual(before); +}); + +it("plans one private copy per digest and mode, with same-bytes twins as copy sources", () => { + const a = "a".repeat(64), b = "b".repeat(64); + expect(providerPackReusePlan([ + { path: "one", sha256: a, mode: 0o755 }, + { path: "two", sha256: a, mode: 0o644 }, + { path: "three", sha256: a, mode: 0o755 }, + { path: "four", sha256: a, mode: 0o644 }, + { path: "other", sha256: b, mode: 0o755 }, + ])).toEqual([ + { sources: ["one", "two", "three", "four"], group: 0 }, + { sources: ["two", "one", "three", "four"], group: 1 }, + { sources: ["three", "one", "two", "four"], group: 0 }, + { sources: ["four", "one", "two", "three"], group: 1 }, + { sources: ["other"], group: 2 }, + ]); +}); + +it.skipIf(!tar || !hasZstd)("keeps one private copy per mode when the same bytes repeat with different modes", async () => { + const { root, pack, image, archive } = await repeatedBytesFixture({ [twinPath]: 0o644 }); + const remote = await runner(root); + const targetPath = path.join(root, "fresh"); + expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [image] })).toBe(true); + const [tool, twin, other] = await Promise.all([toolPath, twinPath, otherTwinPath].map(relative => fs.lstat(path.join(targetPath, relative)))); + expect(other!.ino).toBe(tool!.ino); + expect(twin!.ino).not.toBe(tool!.ino); + expect(twin!.mode & 0o777).toBe(0o644); + expect(tool!.mode & 0o777).toBe(0o755); + expect(await fs.readFile(path.join(targetPath, twinPath))).toEqual(await fs.readFile(path.join(pack, twinPath))); + expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes); +}); + +it.skipIf(!tar || !hasZstd)("transfers repeated bytes when no image has them, and does not reuse a changed twin", async () => { + const { root, pack, image, archive } = await repeatedBytesFixture(); + await fs.writeFile(path.join(image, toolPath), Buffer.alloc(2 * 1024 * 1024, 10)); + const remote = await runner(root); + const targetPath = path.join(root, "fresh"); + expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [image] })).toBe(true); + for (const relative of [toolPath, twinPath, otherTwinPath]) { + expect(await fs.readFile(path.join(targetPath, relative))).toEqual(await fs.readFile(path.join(pack, relative))); + } + const layers = archive.files.reduce((sum, file) => sum + file.archive.bytes, 0); + expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes + layers); +}); + 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 diff --git a/server/src/services/native-runtime/provider-pack-layers.ts b/server/src/services/native-runtime/provider-pack-layers.ts index 090181fdab2..cc353873433 100644 --- a/server/src/services/native-runtime/provider-pack-layers.ts +++ b/server/src/services/native-runtime/provider-pack-layers.ts @@ -84,15 +84,19 @@ export async function readProviderPackLayers(root: string, expectedDigest: strin return { kind: "layers", sourceRoot, overlay: receipt.overlay, files: receipt.files }; } -// Copy first, then hash the private copy: no shared hardlinks, no mutation of -// the older image, and no time-of-check/time-of-use trust in its contents. +// Copy first, then hash the private copy: no mutation of the older image, and +// no time-of-check/time-of-use trust in its contents. Image bytes are never +// linked, because the runner requires its pack to be physical files inside the +// pack. Only verified private copies inside the pack are hardlinked, and only +// to files with the same digest and mode. `providerPackReusePlan` decides how repeated bytes +// are stored once; this program only follows that plan. const reuseScript = ` (async()=>{ const fs=require('node:fs'),p=require('node:path'),c=require('node:crypto'); const spec=JSON.parse(Buffer.from(process.argv[1],'base64').toString('utf8')); const f=fs.promises;await f.mkdir(p.dirname(spec.target),{recursive:true,mode:448}); await f.mkdir(spec.target,{mode:448}); - const missing=[]; + const missing=[],anchors=new Map(); const regularPath=async(root,relative)=>{ let current=root;if(!(await f.lstat(current)).isDirectory())return false; const parts=relative.split('/'); @@ -102,9 +106,13 @@ const reuseScript = ` }; for(const [index,entry] of spec.files.entries()){ const target=p.join(spec.target,entry.path);let reused=false; - for(const root of spec.roots){try{ - if(!await regularPath(root,entry.path))continue; - const source=p.join(root,entry.path);if((await f.lstat(source)).size!==entry.bytes)continue; + const anchor=anchors.get(entry.group); + if(anchor!==undefined){try{ + await f.mkdir(p.dirname(target),{recursive:true,mode:448});await f.link(anchor,target);continue; + }catch{await f.unlink(target).catch(()=>{});}} + for(const root of spec.roots){for(const relative of entry.sources){try{ + if(!await regularPath(root,relative))continue; + const source=p.join(root,relative);if((await f.lstat(source)).size!==entry.bytes)continue; await f.mkdir(p.dirname(target),{recursive:true,mode:448}); await f.copyFile(source,target,fs.constants.COPYFILE_EXCL|fs.constants.COPYFILE_FICLONE); const handle=await f.open(target,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW); @@ -113,15 +121,38 @@ const reuseScript = ` }finally{await handle.close();} if(!matches)throw Error('digest mismatch'); await f.chmod(target,entry.mode);reused=true;break; - }catch{await f.unlink(target).catch(()=>{});}} - if(!reused)missing.push(index); + }catch{await f.unlink(target).catch(()=>{});}}if(reused)break;} + if(reused)anchors.set(entry.group,target); + else missing.push(index); } console.log(JSON.stringify(missing)); })().catch(()=>process.exitCode=1); `; +export type ProviderPackReuseStep = { + /** Image paths to copy these bytes from, own path first, then other paths with the same bytes. */ + sources: string[]; + /** Files with the same bytes and mode share a group; later files hardlink to the group's first private copy. */ + group: number; +}; + +/** Store repeated bytes once: the first private copy of each digest and mode is + * shared by hardlinks, and a path the image lacks may come from a same-bytes twin. */ +export function providerPackReusePlan(files: readonly Pick[]): ProviderPackReuseStep[] { + const pathsBySha = new Map(); + for (const file of files) pathsBySha.set(file.sha256, [...(pathsBySha.get(file.sha256) ?? []), file.path]); + const groups = new Map(); + return files.map(file => { + const key = `${file.sha256}:${file.mode}`; + if (!groups.has(key)) groups.set(key, groups.size); + return { sources: [file.path, ...pathsBySha.get(file.sha256)!.filter(path => path !== file.path)], group: groups.get(key)! }; + }); +} + export function providerPackLayersArgument(archive: ProviderPackLayers, targetPath: string, reuseRoots: readonly string[]) { - const spec = Buffer.from(JSON.stringify({ target: targetPath, roots: reuseRoots, files: archive.files })).toString("base64"); + const plan = providerPackReusePlan(archive.files); + const files = archive.files.map((file, index) => ({ ...file, ...plan[index] })); + const spec = Buffer.from(JSON.stringify({ target: targetPath, roots: reuseRoots, files })).toString("base64"); return Buffer.byteLength(spec) > 120_000 ? null : spec; }