mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
feat: parallelize sandbox file-sync behind a provider opt-in capability (#11736)
## Thinking Path > - Paperclip runs AI agents through local and remote execution adapters. > - Sandbox providers move workspace and asset files before and after agent runs. > - Serial file transfers delay startup and teardown when several operations do not depend on each other. > - Providers need an opt-in contract so existing providers keep their serial behavior. > - This pull request adds a bounded scheduler and routes inbound and outbound sync operations through it. > - The benefit is shorter sandbox setup and teardown with stable errors, clear telemetry, and a safe opt-in path. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (multiple of the above): packages/shared, packages/adapter-utils, packages/plugins, and server. **Problem or motivation** Sandbox sync processes the workspace, assets, and referenced projects in series. This adds avoidable wait time to agent startup and teardown. **Proposed solution** Add a fail-closed provider capability named concurrentSyncOperations. Use a bounded scheduler with a limit of four operations. Preserve operation order for error reporting. Keep non-opted-in providers on the serial path. **Alternatives considered** Increase the serial transfer speed or add provider-specific schedulers. Those options do not provide one shared contract or stable behavior across providers. **Roadmap alignment** ROADMAP.md lists cloud and sandbox agents as a product area. This change improves sandbox execution without changing the control-plane contract. **Additional context** The Daytona provider opts in. Board trials on this commit showed overlap for inbound sync and outbound restore, with no referenced-project staging failures. ## What Changed - Add the concurrentSyncOperations sandbox capability and fail-closed parsing. - Add a bounded settle-all scheduler with stable input-order errors. - Parallelize inbound workspace, asset, and referenced-project sync operations when the provider opts in. - Parallelize outbound workspace and asset restore operations when the provider opts in. - Surface referenced-project failure text in run logs and server telemetry. - Add Daytona sync spans and the capability declaration. - Preserve in-flight upload scratch tarballs during workspace wipe. - Add unit and regression tests for the scheduler, coordinators, provider behavior, telemetry, and wipe race. ## Verification - Run the adapter-utils and server type checks. - Run the targeted adapter-utils, server, and Daytona test suites. - Run the full automated sweep. - Review six cold Daytona trials, with three serial and three parallel runs. - Confirm that parallel trials show inbound overlap and outbound restore overlap. - Confirm that providers without the capability keep serial behavior. ## Risks - Providers must opt in only when their file operations can run safely at the same time. - A provider that declares the capability incorrectly can expose transfer races. - The scheduler keeps a limit of four to bound resource use. - Providers without the capability keep the prior serial behavior. ## Model Used OpenAI GPT-5 in the Codex runtime. The model used tool calls, code inspection, and GitHub workflow support. The model did not author the implementation commits. ## 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 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
a5f3ac6b48
commit
233be4b36c
30 files changed
+3032
-478
No files matched your search
@@ -0,0 +1,155 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
// The plugin module imports `@daytonaio/sdk` as a value, but the sync tests never
|
||||
// touch a real Daytona client — every sandbox call goes through a local mock. Stub
|
||||
// the SDK so the import resolves without the excluded provider package.
|
||||
import { vi } from "vitest";
|
||||
vi.mock("@daytonaio/sdk", () => ({
|
||||
Daytona: class MockDaytona {},
|
||||
DaytonaNotFoundError: class MockDaytonaNotFoundError extends Error {},
|
||||
DaytonaTimeoutError: class MockDaytonaTimeoutError extends Error {},
|
||||
}));
|
||||
|
||||
import { performSyncIn } from "./file-sync.js";
|
||||
import type { PluginSyncOperation } from "@paperclipai/plugin-sdk";
|
||||
|
||||
// One recorded in-sandbox command, so a test can assert the exact cleanup command.
|
||||
interface RecordedCommand {
|
||||
command: string;
|
||||
}
|
||||
|
||||
// Build a mock Daytona sandbox for the inbound directory path. `executeCommand`
|
||||
// records every command and returns exit 0, except that any command whose text
|
||||
// matches `failCommandMatch` returns exit 1 (to simulate an extract failure).
|
||||
// `uploadFiles` records each upload destination so a test can read the reserved
|
||||
// scratch tar path the runtime chose.
|
||||
function createMockSandbox(input: {
|
||||
failCommandMatch?: RegExp;
|
||||
uploadedDestinations: string[];
|
||||
commands: RecordedCommand[];
|
||||
}) {
|
||||
return {
|
||||
process: {
|
||||
executeCommand: async (command: string) => {
|
||||
input.commands.push({ command });
|
||||
if (input.failCommandMatch && input.failCommandMatch.test(command)) {
|
||||
return { exitCode: 1, result: "simulated extract failure" };
|
||||
}
|
||||
return { exitCode: 0, result: "" };
|
||||
},
|
||||
},
|
||||
fs: {
|
||||
uploadFiles: async (uploads: Array<{ source: string; destination: string }>) => {
|
||||
for (const upload of uploads) input.uploadedDestinations.push(upload.destination);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("daytona file-sync inbound scratch cleanup", () => {
|
||||
const cleanupDirs: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanupDirs.length > 0) {
|
||||
const dir = cleanupDirs.pop();
|
||||
if (!dir) continue;
|
||||
await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("removes the reserved scratch tar when a directory extraction fails", async () => {
|
||||
const rootDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-daytona-scratch-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
const sourceDir = path.join(rootDir, "referenced-project");
|
||||
await fs.mkdir(sourceDir, { recursive: true });
|
||||
await fs.writeFile(path.join(sourceDir, "README.md"), "referenced project\n", "utf8");
|
||||
|
||||
const remoteDir = "/workspace";
|
||||
const targetPath = "/workspace/.paperclip-runtime/test-adapter/project-abc";
|
||||
const uploadedDestinations: string[] = [];
|
||||
const commands: RecordedCommand[] = [];
|
||||
// Fail the extract round trip (the only command that runs `tar -xf`).
|
||||
const sandbox = createMockSandbox({
|
||||
failCommandMatch: /tar -xf/,
|
||||
uploadedDestinations,
|
||||
commands,
|
||||
});
|
||||
|
||||
const operations: PluginSyncOperation[] = [{
|
||||
operationId: "sync-op-1",
|
||||
files: [{ sourcePath: sourceDir, targetPath, kind: "directory" }],
|
||||
}];
|
||||
|
||||
await expect(
|
||||
performSyncIn({
|
||||
// The mock stands in for the Daytona SDK Sandbox; only the two methods the
|
||||
// inbound directory path calls are needed.
|
||||
sandbox: sandbox as never,
|
||||
operations,
|
||||
remoteDir,
|
||||
timeoutSeconds: 30,
|
||||
}),
|
||||
).rejects.toThrow(/syncIn extract/);
|
||||
|
||||
// The runtime uploaded exactly one reserved scratch tar under the workspace
|
||||
// root. Its name carries the reserved `.paperclip-upload-` prefix.
|
||||
expect(uploadedDestinations).toHaveLength(1);
|
||||
const scratchTar = uploadedDestinations[0];
|
||||
expect(scratchTar).toContain(".paperclip-upload-");
|
||||
expect(scratchTar.startsWith(`${remoteDir}/`)).toBe(true);
|
||||
|
||||
// The failure path swept the scratch tar: a standalone `rm -f` of the exact
|
||||
// scratch path ran after the failed extract. The extract command itself also
|
||||
// contains an `rm -f`, so the cleanup is the `rm -f` command that does NOT run
|
||||
// `tar -xf`.
|
||||
const cleanupCommands = commands.filter(
|
||||
(entry) =>
|
||||
entry.command.includes(scratchTar) &&
|
||||
entry.command.includes("rm -f") &&
|
||||
!entry.command.includes("tar -xf"),
|
||||
);
|
||||
expect(cleanupCommands.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("does not sweep scratch on the happy path (extract removes it)", async () => {
|
||||
const rootDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-daytona-scratch-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
const sourceDir = path.join(rootDir, "referenced-project");
|
||||
await fs.mkdir(sourceDir, { recursive: true });
|
||||
await fs.writeFile(path.join(sourceDir, "README.md"), "referenced project\n", "utf8");
|
||||
|
||||
const remoteDir = "/workspace";
|
||||
const targetPath = "/workspace/.paperclip-runtime/test-adapter/project-abc";
|
||||
const uploadedDestinations: string[] = [];
|
||||
const commands: RecordedCommand[] = [];
|
||||
// No failure: every command succeeds, so the extract's own `rm -f` clears the
|
||||
// scratch and no extra cleanup round trip runs.
|
||||
const sandbox = createMockSandbox({ uploadedDestinations, commands });
|
||||
|
||||
const operations: PluginSyncOperation[] = [{
|
||||
operationId: "sync-op-1",
|
||||
files: [{ sourcePath: sourceDir, targetPath, kind: "directory" }],
|
||||
}];
|
||||
|
||||
await performSyncIn({
|
||||
sandbox: sandbox as never,
|
||||
operations,
|
||||
remoteDir,
|
||||
timeoutSeconds: 30,
|
||||
});
|
||||
|
||||
const scratchTar = uploadedDestinations[0];
|
||||
// The standalone cleanup command (a `rm -f` without `tar -xf`) never runs on the
|
||||
// happy path — only the extract command, which ends with its own `rm -f`.
|
||||
const standaloneRemoves = commands.filter(
|
||||
(entry) =>
|
||||
entry.command.includes(scratchTar) &&
|
||||
entry.command.includes("rm -f") &&
|
||||
!entry.command.includes("tar -xf"),
|
||||
);
|
||||
expect(standaloneRemoves).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,10 @@ const SPAN_ATTR = {
|
||||
packWallMs: `${SPAN_ATTR_PREFIX}pack.wall_ms`,
|
||||
transferWallMs: `${SPAN_ATTR_PREFIX}transfer.wall_ms`,
|
||||
transferGuardCount: `${SPAN_ATTR_PREFIX}transfer.guard.count`,
|
||||
// The transfer direction: `inbound` for an upload to the sandbox, `outbound`
|
||||
// for a download from the sandbox. Operation identity comes from the parent
|
||||
// span, so the transfer span never carries an operation label.
|
||||
transferDirection: `${SPAN_ATTR_PREFIX}transfer.direction`,
|
||||
} as const;
|
||||
|
||||
/** The value of `SpanStatusCode.ERROR` in `@opentelemetry/api`. The plugin stays
|
||||
@@ -532,7 +536,10 @@ async function syncInFileMappings(input: {
|
||||
await withProviderSpan({
|
||||
name: "transfer",
|
||||
wallMsAttr: SPAN_ATTR.transferWallMs,
|
||||
attributes: { [SPAN_ATTR.transferGuardCount]: guardRoundTrips },
|
||||
attributes: {
|
||||
[SPAN_ATTR.transferGuardCount]: guardRoundTrips,
|
||||
[SPAN_ATTR.transferDirection]: "inbound",
|
||||
},
|
||||
run: () => sandbox.fs.uploadFiles(uploads, timeoutSeconds),
|
||||
});
|
||||
|
||||
@@ -655,52 +662,67 @@ async function syncInDirectoryMapping(input: {
|
||||
}),
|
||||
});
|
||||
guardRoundTrips += 1;
|
||||
// `transfer` span: the real byte upload — `sandbox.fs.uploadFiles`.
|
||||
await withProviderSpan({
|
||||
name: "transfer",
|
||||
wallMsAttr: SPAN_ATTR.transferWallMs,
|
||||
attributes: { [SPAN_ATTR.transferGuardCount]: guardRoundTrips },
|
||||
run: () =>
|
||||
sandbox.fs.uploadFiles([{ source: archivePath, destination: remoteTar }], timeoutSeconds),
|
||||
});
|
||||
// Bind validation and extraction into ONE sandbox invocation, then extract into
|
||||
// an OPEN directory inode rather than a path string. `exec 9<"$_pc_real"` itself
|
||||
// walks every ancestor of `$_pc_real` during the `open()` syscall, so a sandbox
|
||||
// process that swaps an ancestor component for a symlink AFTER `_pc_resolve`
|
||||
// returns but BEFORE the `open()` resolves would leave fd 9 pointing at a
|
||||
// directory outside the workspace — the earlier `case` check on the resolved
|
||||
// string cannot see that. Close the gap with open-then-verify: open fd 9 (which
|
||||
// PINS whatever inode `open()` landed on), then re-canonicalize `/proc/self/fd/9`
|
||||
// — the pinned inode's own path — and confirm it is still inside `$_pc_root`
|
||||
// before extracting. If an ancestor swap redirected the open, the pinned inode
|
||||
// resolves outside the root and the verify fails closed (exit 42); once the
|
||||
// verify passes, the inode is fixed and `tar -C /proc/self/fd/9` chdir's through
|
||||
// the magic symlink to that exact inode, so a post-open ancestor swap cannot
|
||||
// redirect the write. (The initial `case` on `$_pc_real` still fails fast on a
|
||||
// pre-open escape; the fd re-verify is what makes the guarantee race-free.)
|
||||
const extractScript = [
|
||||
...canonicalizerPreamble(shellQuote(remoteDir)),
|
||||
`_pc_real=$(_pc_resolve ${shellQuote(mapping.targetPath)}) || { echo "ESCAPE"; exit 42; };`,
|
||||
`case "$_pc_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE"; exit 42 ;; esac;`,
|
||||
`exec 9<"$_pc_real" || { echo "open failed"; exit 46; };`,
|
||||
`_pc_fd_real=$(_pc_resolve /proc/self/fd/9) || { echo "ESCAPE"; exit 42; };`,
|
||||
`case "$_pc_fd_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE"; exit 42 ;; esac;`,
|
||||
`tar -xf ${shellQuote(remoteTar)} -C /proc/self/fd/9 || { echo "extract failed"; exit 43; };`,
|
||||
`exec 9>&-;`,
|
||||
`rm -f ${shellQuote(remoteTar)};`,
|
||||
].join("\n");
|
||||
// `extractTarball` span: one round trip — re-check the path, `tar -xf`, and
|
||||
// remove the scratch tarball.
|
||||
await withProviderSpan({
|
||||
name: "extractTarball",
|
||||
run: () =>
|
||||
assertSandboxCommandOk(
|
||||
sandbox,
|
||||
`sh -c ${shellQuote(extractScript)}`,
|
||||
timeoutSeconds,
|
||||
"syncIn extract",
|
||||
),
|
||||
});
|
||||
// The uploaded scratch tar lands at the workspace root as a reserved
|
||||
// `.paperclip-upload-*` entry. The extract script below removes it only on
|
||||
// success. On an upload or extract failure the scratch tar can remain, and the
|
||||
// runtime workspace wipe preserves every `.paperclip-upload-*` entry, so a
|
||||
// stale tar would surface in the agent workspace. Sweep the scratch on any
|
||||
// failure — symmetric with the file-mapping path — so a failed sync (for
|
||||
// example a referenced-project extraction) leaves no residue.
|
||||
try {
|
||||
// `transfer` span: the real byte upload — `sandbox.fs.uploadFiles`.
|
||||
await withProviderSpan({
|
||||
name: "transfer",
|
||||
wallMsAttr: SPAN_ATTR.transferWallMs,
|
||||
attributes: {
|
||||
[SPAN_ATTR.transferGuardCount]: guardRoundTrips,
|
||||
[SPAN_ATTR.transferDirection]: "inbound",
|
||||
},
|
||||
run: () =>
|
||||
sandbox.fs.uploadFiles([{ source: archivePath, destination: remoteTar }], timeoutSeconds),
|
||||
});
|
||||
// Bind validation and extraction into ONE sandbox invocation, then extract into
|
||||
// an OPEN directory inode rather than a path string. `exec 9<"$_pc_real"` itself
|
||||
// walks every ancestor of `$_pc_real` during the `open()` syscall, so a sandbox
|
||||
// process that swaps an ancestor component for a symlink AFTER `_pc_resolve`
|
||||
// returns but BEFORE the `open()` resolves would leave fd 9 pointing at a
|
||||
// directory outside the workspace — the earlier `case` check on the resolved
|
||||
// string cannot see that. Close the gap with open-then-verify: open fd 9 (which
|
||||
// PINS whatever inode `open()` landed on), then re-canonicalize `/proc/self/fd/9`
|
||||
// — the pinned inode's own path — and confirm it is still inside `$_pc_root`
|
||||
// before extracting. If an ancestor swap redirected the open, the pinned inode
|
||||
// resolves outside the root and the verify fails closed (exit 42); once the
|
||||
// verify passes, the inode is fixed and `tar -C /proc/self/fd/9` chdir's through
|
||||
// the magic symlink to that exact inode, so a post-open ancestor swap cannot
|
||||
// redirect the write. (The initial `case` on `$_pc_real` still fails fast on a
|
||||
// pre-open escape; the fd re-verify is what makes the guarantee race-free.)
|
||||
const extractScript = [
|
||||
...canonicalizerPreamble(shellQuote(remoteDir)),
|
||||
`_pc_real=$(_pc_resolve ${shellQuote(mapping.targetPath)}) || { echo "ESCAPE"; exit 42; };`,
|
||||
`case "$_pc_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE"; exit 42 ;; esac;`,
|
||||
`exec 9<"$_pc_real" || { echo "open failed"; exit 46; };`,
|
||||
`_pc_fd_real=$(_pc_resolve /proc/self/fd/9) || { echo "ESCAPE"; exit 42; };`,
|
||||
`case "$_pc_fd_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE"; exit 42 ;; esac;`,
|
||||
`tar -xf ${shellQuote(remoteTar)} -C /proc/self/fd/9 || { echo "extract failed"; exit 43; };`,
|
||||
`exec 9>&-;`,
|
||||
`rm -f ${shellQuote(remoteTar)};`,
|
||||
].join("\n");
|
||||
// `extractTarball` span: one round trip — re-check the path, `tar -xf`, and
|
||||
// remove the scratch tarball.
|
||||
await withProviderSpan({
|
||||
name: "extractTarball",
|
||||
run: () =>
|
||||
assertSandboxCommandOk(
|
||||
sandbox,
|
||||
`sh -c ${shellQuote(extractScript)}`,
|
||||
timeoutSeconds,
|
||||
"syncIn extract",
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
await removeSandboxScratch(sandbox, [remoteTar], timeoutSeconds);
|
||||
throw error;
|
||||
}
|
||||
const filesTransferred = await countHostFiles(mapping.sourcePath, mapping.exclude);
|
||||
return { filesTransferred, bytesTransferred };
|
||||
});
|
||||
@@ -873,10 +895,25 @@ async function syncOutFileMappings(input: {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Count the serial sandbox round trips before the transfer, so the transfer
|
||||
// span records how much of the wall time is guard cost. The validate-and-
|
||||
// snapshot step is one sandbox round trip. This is symmetric with the inbound
|
||||
// transfer span.
|
||||
const guardRoundTrips = 1;
|
||||
|
||||
let responses: FileDownloadResponse[];
|
||||
try {
|
||||
// One batched bulk download for all file mappings, reading the snapshots.
|
||||
responses = await sandbox.fs.downloadFiles(requests, timeoutSeconds);
|
||||
// `transfer` span: the real byte download — `sandbox.fs.downloadFiles`.
|
||||
responses = await withProviderSpan({
|
||||
name: "transfer",
|
||||
wallMsAttr: SPAN_ATTR.transferWallMs,
|
||||
attributes: {
|
||||
[SPAN_ATTR.transferGuardCount]: guardRoundTrips,
|
||||
[SPAN_ATTR.transferDirection]: "outbound",
|
||||
},
|
||||
run: () => sandbox.fs.downloadFiles(requests, timeoutSeconds),
|
||||
});
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
@@ -926,6 +963,9 @@ async function syncOutDirectoryMapping(input: {
|
||||
}): Promise<{ filesTransferred: number; bytesTransferred: number }> {
|
||||
const { sandbox, mapping, remoteDir, timeoutSeconds } = input;
|
||||
assertConfinedSandboxPath(remoteDir, mapping.sourcePath, "source");
|
||||
// Count the serial sandbox round trips before the transfer, so the transfer
|
||||
// span records how much of the wall time is guard cost.
|
||||
let guardRoundTrips = 0;
|
||||
await assertSandboxPathsConfined({
|
||||
sandbox,
|
||||
remoteDir,
|
||||
@@ -933,6 +973,7 @@ async function syncOutDirectoryMapping(input: {
|
||||
timeoutSeconds,
|
||||
label: "outbound symlink-escape guard",
|
||||
});
|
||||
guardRoundTrips += 1;
|
||||
|
||||
return withHostTempDir(async (tmp) => {
|
||||
const remoteTar = path.posix.join(remoteDir, scratchName(".tar"));
|
||||
@@ -951,14 +992,22 @@ async function syncOutDirectoryMapping(input: {
|
||||
`else tar -c --no-xattrs ${mapping.followSymlinks ? "-h " : ""}${excludeFlags} -f ${shellQuote(remoteTar)} -- "$@"; fi`,
|
||||
].join(" && ");
|
||||
await assertSandboxCommandOk(sandbox, `sh -c ${shellQuote(tarScript)}`, timeoutSeconds, "syncOut tar");
|
||||
guardRoundTrips += 1;
|
||||
|
||||
const localTar = path.join(tmp, "sync-out.tar");
|
||||
let bytesTransferred = 0;
|
||||
try {
|
||||
const responses = await sandbox.fs.downloadFiles(
|
||||
[{ source: remoteTar, destination: localTar }],
|
||||
timeoutSeconds,
|
||||
);
|
||||
// `transfer` span: the real byte download — `sandbox.fs.downloadFiles`.
|
||||
const responses = await withProviderSpan({
|
||||
name: "transfer",
|
||||
wallMsAttr: SPAN_ATTR.transferWallMs,
|
||||
attributes: {
|
||||
[SPAN_ATTR.transferGuardCount]: guardRoundTrips,
|
||||
[SPAN_ATTR.transferDirection]: "outbound",
|
||||
},
|
||||
run: () =>
|
||||
sandbox.fs.downloadFiles([{ source: remoteTar, destination: localTar }], timeoutSeconds),
|
||||
});
|
||||
const response = responses.find((entry) => entry.source === remoteTar) ?? responses[0];
|
||||
if (!response || response.error) {
|
||||
throw new Error(
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
|
||||
|
||||
const PLUGIN_ID = "paperclip.daytona-sandbox-provider";
|
||||
// 0.1.3 renames the login transport flag from `supportsSetupTokenLogin` to the
|
||||
// neutral `supportsLoginPty`. The boot reconcile reads the persisted manifest
|
||||
// raw and does not re-run the validator, so it never canonicalizes the old
|
||||
// name. The version bump makes the reconcile refresh the persisted manifest for
|
||||
// an existing install, so the renamed capability propagates.
|
||||
const PLUGIN_VERSION = "0.1.3";
|
||||
// The bundled-plugin boot reconcile refreshes the persisted manifest for an
|
||||
// existing install only when PLUGIN_VERSION changes. A manifest change without a
|
||||
// version bump never reaches an existing install. The reconcile also reads the
|
||||
// persisted manifest raw and does not re-run the validator, so it never
|
||||
// canonicalizes a renamed capability.
|
||||
//
|
||||
// 0.1.3 renamed the login transport flag from `supportsSetupTokenLogin` to the
|
||||
// neutral `supportsLoginPty`.
|
||||
// 0.1.4 adds the `concurrentSyncOperations` sandbox capability to the driver.
|
||||
const PLUGIN_VERSION = "0.1.4";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: PLUGIN_ID,
|
||||
@@ -33,8 +37,16 @@ const manifest: PaperclipPluginManifestV1 = {
|
||||
// emits incremental session output while the command runs. Declare the
|
||||
// opt-in capability so the host selects the session-output streaming path.
|
||||
// A generic one-shot provider that omits this key keeps the poll path.
|
||||
//
|
||||
// Daytona also runs file transfers into and out of the sandbox in parallel.
|
||||
// Each concurrent sync hook call uses separate temporary state (random
|
||||
// scratch names and per-mapping host temporary directories), and teardown
|
||||
// waits for all active calls. Declare the opt-in capability so the host may
|
||||
// schedule sync operations concurrently. The host resolves it `true` only
|
||||
// when the worker also verifies both sync verbs.
|
||||
sandboxCapabilities: {
|
||||
incrementalSessionOutput: true,
|
||||
concurrentSyncOperations: true,
|
||||
},
|
||||
supportsInteractiveSetup: true,
|
||||
interactiveSetupConnectionTypes: ["ssh"],
|
||||
|
||||
@@ -139,6 +139,15 @@ describe("Daytona sandbox provider plugin", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("declares the concurrent-sync-operations capability so the host may parallelize sync operations", () => {
|
||||
// Daytona runs file transfers into and out of the sandbox in parallel, so it
|
||||
// declares the opt-in capability. The host resolves it `true` only when the
|
||||
// worker also verifies both sync verbs, which the sync hooks provide.
|
||||
expect(manifest.environmentDrivers?.[0]?.sandboxCapabilities).toMatchObject({
|
||||
concurrentSyncOperations: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes config and validates the API key fallback", async () => {
|
||||
process.env.DAYTONA_API_KEY = "host-key";
|
||||
|
||||
@@ -3014,6 +3023,95 @@ describe("daytona native file-sync hooks", () => {
|
||||
};
|
||||
}
|
||||
|
||||
// A concurrency gate for a fake transfer call (uploadFiles / downloadFiles).
|
||||
// The gate lets two concurrent hook calls both enter the fake, then holds them
|
||||
// there until the test releases them. It records the peak number of calls that
|
||||
// are in the fake at the same time, so a test proves the two calls overlap.
|
||||
//
|
||||
// `expected` is how many calls the test starts. `bothArrived` resolves once
|
||||
// that many calls sit inside the fake at the same moment. `release()` frees
|
||||
// them. `body` is the fake implementation: it marks arrival, waits for the
|
||||
// release, and then runs `onRelease` to produce the fake result.
|
||||
function createTransferGate<T>(expected: number, onRelease: (args: unknown[]) => Promise<T>) {
|
||||
let inFlight = 0;
|
||||
let peakInFlight = 0;
|
||||
let signalArrived!: () => void;
|
||||
const bothArrived = new Promise<void>((resolve) => {
|
||||
signalArrived = resolve;
|
||||
});
|
||||
let signalReleased!: () => void;
|
||||
const released = new Promise<void>((resolve) => {
|
||||
signalReleased = resolve;
|
||||
});
|
||||
const body = async (...args: unknown[]): Promise<T> => {
|
||||
inFlight += 1;
|
||||
peakInFlight = Math.max(peakInFlight, inFlight);
|
||||
if (inFlight === expected) signalArrived();
|
||||
await released;
|
||||
inFlight -= 1;
|
||||
return onRelease(args);
|
||||
};
|
||||
return {
|
||||
body,
|
||||
bothArrived,
|
||||
release: () => signalReleased(),
|
||||
peak: () => peakInFlight,
|
||||
};
|
||||
}
|
||||
|
||||
// Write each download request's snapshot bytes to its host destination and
|
||||
// report success, matching the real batch-download contract the outbound sync
|
||||
// path expects.
|
||||
async function fulfilDownload(args: unknown[]): Promise<Array<{ source: string; result: string }>> {
|
||||
const requests = args[0] as Array<{ source: string; destination: string }>;
|
||||
return Promise.all(
|
||||
requests.map(async (request) => {
|
||||
await fs.writeFile(request.destination, "bytes");
|
||||
return { source: request.source, result: request.destination };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function syncInParams(overrides: {
|
||||
operationId: string;
|
||||
sourcePath: string;
|
||||
targetPath: string;
|
||||
}) {
|
||||
return {
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { timeoutMs: 300000, reuseLease: false },
|
||||
lease: syncLease(),
|
||||
operations: [
|
||||
{
|
||||
operationId: overrides.operationId,
|
||||
files: [{ sourcePath: overrides.sourcePath, targetPath: overrides.targetPath, kind: "file" as const }],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function syncOutParams(overrides: {
|
||||
operationId: string;
|
||||
sourcePath: string;
|
||||
targetPath: string;
|
||||
}) {
|
||||
return {
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { timeoutMs: 300000, reuseLease: false },
|
||||
lease: syncLease(),
|
||||
operations: [
|
||||
{
|
||||
operationId: overrides.operationId,
|
||||
files: [{ sourcePath: overrides.sourcePath, targetPath: overrides.targetPath, kind: "file" as const }],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset();
|
||||
process.env.DAYTONA_API_KEY = "host-key";
|
||||
@@ -3295,6 +3393,66 @@ describe("daytona native file-sync hooks", () => {
|
||||
expect(spans.find((span) => span.name === "pack")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("marks the inbound transfer span with the inbound direction attribute", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const source = path.join(hostDir, "config.txt");
|
||||
await fs.writeFile(source, "plain");
|
||||
const sandbox = createMockSandbox();
|
||||
mockGet.mockResolvedValue(sandbox);
|
||||
|
||||
const { tracer, spans } = createRecordingPluginTracer();
|
||||
const restore = __setDaytonaPluginContextForTest({ tracer } as unknown as PluginContext);
|
||||
try {
|
||||
await plugin.definition.onEnvironmentSyncIn?.(
|
||||
syncInParams({
|
||||
operationId: "sync-op-in-dir",
|
||||
sourcePath: source,
|
||||
targetPath: `${REMOTE_DIR}/config.txt`,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
// An upload to the sandbox is an inbound transfer.
|
||||
const transfer = spans.find((span) => span.name === "transfer");
|
||||
expect(transfer).toBeDefined();
|
||||
expect(transfer!.attributes["paperclip.sandbox.startup.transfer.direction"]).toBe("inbound");
|
||||
});
|
||||
|
||||
it("marks the outbound transfer span with the outbound direction attribute", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const sandbox = createMockSandbox();
|
||||
sandbox.fs.downloadFiles.mockImplementation(async (requests: Array<{ source: string; destination?: string }>) => {
|
||||
return Promise.all(
|
||||
requests.map(async (req) => {
|
||||
await fs.writeFile(req.destination!, "bytes");
|
||||
return { source: req.source, result: req.destination };
|
||||
}),
|
||||
);
|
||||
});
|
||||
mockGet.mockResolvedValue(sandbox);
|
||||
|
||||
const { tracer, spans } = createRecordingPluginTracer();
|
||||
const restore = __setDaytonaPluginContextForTest({ tracer } as unknown as PluginContext);
|
||||
try {
|
||||
await plugin.definition.onEnvironmentSyncOut?.(
|
||||
syncOutParams({
|
||||
operationId: "sync-op-out-dir",
|
||||
sourcePath: `${REMOTE_DIR}/out/result.txt`,
|
||||
targetPath: path.join(hostDir, "result.txt"),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
// A download from the sandbox is an outbound transfer.
|
||||
const transfer = spans.find((span) => span.name === "transfer");
|
||||
expect(transfer).toBeDefined();
|
||||
expect(transfer!.attributes["paperclip.sandbox.startup.transfer.direction"]).toBe("outbound");
|
||||
});
|
||||
|
||||
it("opens a pack span and a transfer span around a directory mapping sync", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const sourceDir = path.join(hostDir, "assets");
|
||||
@@ -4530,6 +4688,239 @@ describe("daytona native file-sync hooks", () => {
|
||||
});
|
||||
expect(withEmpty.process.executeCommand.mock.calls.length).toBe(baselineExecCount);
|
||||
});
|
||||
|
||||
it("runs two concurrent inbound syncIn calls with separate reserved scratch names", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const sourceA = path.join(hostDir, "a.txt");
|
||||
const sourceB = path.join(hostDir, "b.txt");
|
||||
await fs.writeFile(sourceA, "alpha");
|
||||
await fs.writeFile(sourceB, "beta");
|
||||
|
||||
const sandbox = createMockSandbox();
|
||||
// Gate the upload so both concurrent calls sit inside uploadFiles together.
|
||||
const gate = createTransferGate(2, async () => undefined);
|
||||
sandbox.fs.uploadFiles.mockImplementation(gate.body);
|
||||
mockGet.mockResolvedValue(sandbox);
|
||||
|
||||
const callA = plugin.definition.onEnvironmentSyncIn?.(
|
||||
syncInParams({ operationId: "in-a", sourcePath: sourceA, targetPath: `${REMOTE_DIR}/a.txt` }),
|
||||
);
|
||||
const callB = plugin.definition.onEnvironmentSyncIn?.(
|
||||
syncInParams({ operationId: "in-b", sourcePath: sourceB, targetPath: `${REMOTE_DIR}/b.txt` }),
|
||||
);
|
||||
|
||||
// Both calls reached the upload before either finished, so they overlap.
|
||||
await gate.bothArrived;
|
||||
expect(gate.peak()).toBe(2);
|
||||
expect(sandbox.fs.uploadFiles).toHaveBeenCalledTimes(2);
|
||||
|
||||
gate.release();
|
||||
await Promise.all([callA, callB]);
|
||||
|
||||
// Each concurrent call staged its upload under its own reserved scratch name;
|
||||
// the two calls never share a temporary destination.
|
||||
const destinations = sandbox.fs.uploadFiles.mock.calls.flatMap(
|
||||
([uploads]) => (uploads as Array<{ destination: string }>).map((upload) => upload.destination),
|
||||
);
|
||||
expect(destinations).toHaveLength(2);
|
||||
for (const destination of destinations) {
|
||||
expect(path.posix.basename(destination)).toMatch(/^\.paperclip-upload-/);
|
||||
expect(path.posix.dirname(destination)).toBe(REMOTE_DIR);
|
||||
}
|
||||
expect(new Set(destinations).size).toBe(destinations.length);
|
||||
});
|
||||
|
||||
it("runs two concurrent outbound syncOut calls that both reach downloadFiles before either opens", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const targetA = path.join(hostDir, "a.txt");
|
||||
const targetB = path.join(hostDir, "b.txt");
|
||||
|
||||
const sandbox = createMockSandbox();
|
||||
// Gate the download so both concurrent calls sit inside downloadFiles
|
||||
// together before either resolves.
|
||||
const gate = createTransferGate(2, fulfilDownload);
|
||||
sandbox.fs.downloadFiles.mockImplementation(gate.body);
|
||||
mockGet.mockResolvedValue(sandbox);
|
||||
|
||||
const callA = plugin.definition.onEnvironmentSyncOut?.(
|
||||
syncOutParams({ operationId: "out-a", sourcePath: `${REMOTE_DIR}/a.txt`, targetPath: targetA }),
|
||||
);
|
||||
const callB = plugin.definition.onEnvironmentSyncOut?.(
|
||||
syncOutParams({ operationId: "out-b", sourcePath: `${REMOTE_DIR}/b.txt`, targetPath: targetB }),
|
||||
);
|
||||
|
||||
// Both calls reached the download before either gate opened, so they overlap.
|
||||
await gate.bothArrived;
|
||||
expect(gate.peak()).toBe(2);
|
||||
expect(sandbox.fs.downloadFiles).toHaveBeenCalledTimes(2);
|
||||
|
||||
gate.release();
|
||||
await Promise.all([callA, callB]);
|
||||
|
||||
// Each concurrent call read its own reserved snapshot; the two calls never
|
||||
// share a download source.
|
||||
const sources = sandbox.fs.downloadFiles.mock.calls.flatMap(
|
||||
([requests]) => (requests as Array<{ source: string }>).map((request) => request.source),
|
||||
);
|
||||
expect(sources).toHaveLength(2);
|
||||
for (const source of sources) {
|
||||
expect(source.startsWith(`${REMOTE_DIR}/`)).toBe(true);
|
||||
expect(path.posix.basename(source)).toMatch(/^\.paperclip-upload-/);
|
||||
}
|
||||
expect(new Set(sources).size).toBe(sources.length);
|
||||
expect(await fs.readFile(targetA, "utf8")).toBe("bytes");
|
||||
expect(await fs.readFile(targetB, "utf8")).toBe("bytes");
|
||||
});
|
||||
|
||||
it("waits for one active inbound and one active outbound call before teardown releases the sandbox", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const inboundSource = path.join(hostDir, "in.txt");
|
||||
const outboundTarget = path.join(hostDir, "out.txt");
|
||||
await fs.writeFile(inboundSource, "inbound");
|
||||
|
||||
const sandbox = createMockSandbox({ id: "sandbox-123" });
|
||||
// Hold the inbound upload and the outbound download open at the same time, so
|
||||
// the shared lease has two active sync calls when teardown starts.
|
||||
let releaseUpload!: () => void;
|
||||
sandbox.fs.uploadFiles.mockImplementation(async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseUpload = resolve;
|
||||
});
|
||||
});
|
||||
let releaseDownload!: () => void;
|
||||
sandbox.fs.downloadFiles.mockImplementation(async (requests: Array<{ source: string; destination: string }>) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseDownload = resolve;
|
||||
});
|
||||
return Promise.all(
|
||||
requests.map(async (request) => {
|
||||
await fs.writeFile(request.destination, "bytes");
|
||||
return { source: request.source, result: request.destination };
|
||||
}),
|
||||
);
|
||||
});
|
||||
mockGet.mockResolvedValue(sandbox);
|
||||
|
||||
const inboundCall = plugin.definition.onEnvironmentSyncIn?.(
|
||||
syncInParams({ operationId: "in-active", sourcePath: inboundSource, targetPath: `${REMOTE_DIR}/in.txt` }),
|
||||
);
|
||||
const outboundCall = plugin.definition.onEnvironmentSyncOut?.(
|
||||
syncOutParams({ operationId: "out-active", sourcePath: `${REMOTE_DIR}/out.txt`, targetPath: outboundTarget }),
|
||||
);
|
||||
// Let both sync calls register on the activity gate and reach their hung
|
||||
// transfer, so teardown sees a refCount of two.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const destroyCall = plugin.definition.onEnvironmentDestroyLease?.({
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
providerLeaseId: "sandbox-123",
|
||||
config: { timeoutMs: 300000, reuseLease: false },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
// Two active sync calls block teardown, so it must not delete the sandbox yet.
|
||||
expect(sandbox.delete).not.toHaveBeenCalled();
|
||||
|
||||
// Release only the inbound call. One outbound call is still active, so
|
||||
// teardown must keep waiting.
|
||||
releaseUpload();
|
||||
await inboundCall;
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(sandbox.delete).not.toHaveBeenCalled();
|
||||
|
||||
// Release the outbound call. No sync call is active now, so teardown deletes.
|
||||
releaseDownload();
|
||||
await Promise.all([outboundCall, destroyCall]);
|
||||
|
||||
expect(sandbox.fs.uploadFiles).toHaveBeenCalledTimes(1);
|
||||
expect(sandbox.fs.downloadFiles).toHaveBeenCalledTimes(1);
|
||||
expect(sandbox.delete).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("opens a transfer span with the guard round-trip count around the bulk file download", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const target = path.join(hostDir, "result.txt");
|
||||
const sandbox = createMockSandbox();
|
||||
sandbox.fs.downloadFiles.mockImplementation(async (requests: Array<{ source: string; destination: string }>) => {
|
||||
return Promise.all(
|
||||
requests.map(async (request) => {
|
||||
await fs.writeFile(request.destination, "bytes");
|
||||
return { source: request.source, result: request.destination };
|
||||
}),
|
||||
);
|
||||
});
|
||||
mockGet.mockResolvedValue(sandbox);
|
||||
|
||||
const { tracer, spans } = createRecordingPluginTracer();
|
||||
const restore = __setDaytonaPluginContextForTest({ tracer } as unknown as PluginContext);
|
||||
try {
|
||||
await plugin.definition.onEnvironmentSyncOut?.({
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { timeoutMs: 300000, reuseLease: false },
|
||||
lease: syncLease(),
|
||||
operations: [
|
||||
{
|
||||
operationId: "sync-op-out",
|
||||
files: [{ sourcePath: `${REMOTE_DIR}/out/result.txt`, targetPath: target, kind: "file" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
const transfer = spans.find((span) => span.name === "transfer");
|
||||
expect(transfer).toBeDefined();
|
||||
expect(transfer!.ended).toBe(true);
|
||||
// One serial guard round trip before the transfer: the validate-and-snapshot.
|
||||
expect(transfer!.attributes["paperclip.sandbox.startup.transfer.guard.count"]).toBe(1);
|
||||
expect(transfer!.attributes["paperclip.sandbox.startup.provider"]).toBe("daytona");
|
||||
expect(typeof transfer!.attributes["paperclip.sandbox.startup.transfer.wall_ms"]).toBe("number");
|
||||
});
|
||||
|
||||
it("opens a transfer span around a directory-mapping download with the guard round-trip count", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const targetDir = path.join(hostDir, "assets");
|
||||
const sandbox = createMockSandbox();
|
||||
sandbox.fs.downloadFiles.mockImplementation(async (requests: Array<{ source: string; destination: string }>) => {
|
||||
// Write a valid empty tar (1024-byte zero EOF marker) so host-side extract
|
||||
// is a clean no-op.
|
||||
await Promise.all(requests.map((request) => fs.writeFile(request.destination, Buffer.alloc(1024))));
|
||||
return requests.map((request) => ({ source: request.source, result: request.destination }));
|
||||
});
|
||||
mockGet.mockResolvedValue(sandbox);
|
||||
|
||||
const { tracer, spans } = createRecordingPluginTracer();
|
||||
const restore = __setDaytonaPluginContextForTest({ tracer } as unknown as PluginContext);
|
||||
try {
|
||||
await plugin.definition.onEnvironmentSyncOut?.({
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { timeoutMs: 300000, reuseLease: false },
|
||||
lease: syncLease(),
|
||||
operations: [
|
||||
{
|
||||
operationId: "sync-op-out-dir",
|
||||
files: [{ sourcePath: `${REMOTE_DIR}/out/assets`, targetPath: targetDir, kind: "directory" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
|
||||
const transfer = spans.find((span) => span.name === "transfer");
|
||||
expect(transfer).toBeDefined();
|
||||
expect(transfer!.ended).toBe(true);
|
||||
// Two serial guard round trips before the transfer: confinement + in-sandbox
|
||||
// tar.
|
||||
expect(transfer!.attributes["paperclip.sandbox.startup.transfer.guard.count"]).toBe(2);
|
||||
expect(typeof transfer!.attributes["paperclip.sandbox.startup.transfer.wall_ms"]).toBe("number");
|
||||
});
|
||||
});
|
||||
|
||||
describe("daytona manifest memory config", () => {
|
||||
|
||||
Reference in new issue
Block a user