mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
fix(runner): persist warm Daytona workspaces (#12901)
## Thinking Path > - Paperclip manages AI agent work and the execution state for each task. > - Remote agents run in sandbox environments such as Daytona. > - Daytona keeps files while a sandbox is stopped, but deletion removes those files. > - Runner Codex did not copy successful remote workspace changes back to the host workspace. > - A warm sandbox could therefore hide data loss until Daytona replaced or deleted the sandbox. > - This pull request makes the host workspace durable after every successful turn and keeps verified reusable sandboxes warm. > - The benefit is reliable multi-turn work across warm reuse, restart, stop, and sandbox replacement. ## Linked Issues or Issue Description **What happened?** A successful native Codex turn in Daytona could leave workspace changes only in the remote sandbox. A later warm turn appeared to work because it reused that filesystem. A replacement sandbox could start from stale host data and lose the successful changes. **Expected behavior** Paperclip must merge each successful remote turn into the authoritative host workspace before it completes the run. A verified warm lease may reuse its remote files. A replacement lease must reconstruct the exact durable workspace seed. **Steps to reproduce** 1. Run Codex in a reusable Daytona environment. 2. Write a file during one successful turn. 3. Replace the Daytona sandbox before the next turn. 4. Observe that the next turn can start without the prior file on the unpatched code. Related remote workspace foundation: #10070. ## What Changed - Added explicit `host_current`, `durable_seed`, and `adopt_remote` workspace preparation modes. - Added atomic, versioned native workspace descriptors and seed archives under `PAPERCLIP_HOME`. - Added real native sandbox export and three-way host merge before terminal result completion. - Added workspace-only recovery after a proposed result. Recovery does not submit another provider turn or consume the provider retry budget. - Added fail-closed handling when a sandbox with unexported changes is gone. - Kept healthy reusable Daytona sandboxes started for legacy Codex and Runner Codex. - Kept the Runner Codex process and provider session across verified warm turns. - Added the paid `daytona-warm-continuity` browser suite. It contains exactly the legacy Codex and Runner Codex cells. Each cell performs three measured turns. - Documented `pnpm test:e2e:runner -- --suite daytona-warm-continuity`. No package script was added. - Added no database migration. The metadata format is backward compatible and idempotent. ## Verification - `pnpm typecheck` - `pnpm test:e2e:runner:unit` — 114 passed - Native workspace, finalizer, session, and environment tests — 232 passed - Daytona provider tests — 150 passed - Workspace staging and merge tests — 98 passed - Runner transport tests — 63 passed - Legacy Codex restore tests — 5 passed - Rust format and compile checks pass through root typecheck - The paid Daytona suite was not run locally because the required Daytona, OpenAI, and immutable image credentials are not present. ## Risks - The main risk is an incorrect workspace identity or merge after a crash. Durable descriptors bind the run, workspace, lease, provider lease, local root, remote root, and baseline digest. Ambiguous evidence fails closed. - The host merge may conflict with concurrent host edits. The existing three-way merge and exclusion rules handle this case and surface failures. - A deleted sandbox cannot recover unexported bytes. Paperclip now blocks with `workspace_sync_out_unrecoverable` instead of reporting success or rerunning the provider. - There is no database migration. Descriptor writes and recovery are atomic and idempotent. ## Model Used OpenAI Codex with GPT-5. The run used agentic reasoning, repository inspection, code execution, test execution, Git, and GitHub CLI tools. ## 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
This commit is contained in:
1 parent
be407f3456
commit
1dceee9a4e
47 files changed
+4296
-359
No files matched your search
@@ -1240,6 +1240,8 @@ describe("Daytona sandbox provider plugin", () => {
|
||||
providerLeaseId: "sandbox-reuse",
|
||||
metadata: {
|
||||
resumedLease: true,
|
||||
resumedFromState: "stopped",
|
||||
sandboxState: "started",
|
||||
workspaceSentinel: {
|
||||
result: "matched",
|
||||
token: "sentinel-token",
|
||||
@@ -4060,6 +4062,35 @@ describe("daytona native file-sync hooks", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies a deleted sandbox during syncOut with a stable unrecoverable code", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
mockGet.mockRejectedValue(
|
||||
new MockDaytonaNotFoundError("provider detail must not escape"),
|
||||
);
|
||||
|
||||
await expect(
|
||||
plugin.definition.onEnvironmentSyncOut?.({
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
config: { timeoutMs: 300000, reuseLease: true },
|
||||
lease: syncLease(),
|
||||
operations: [
|
||||
{
|
||||
operationId: "sync-op-missing-sandbox",
|
||||
files: [
|
||||
{
|
||||
sourcePath: `${REMOTE_DIR}/out/result.txt`,
|
||||
targetPath: path.join(hostDir, "result.txt"),
|
||||
kind: "file",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toThrow("daytona_sandbox_not_found");
|
||||
});
|
||||
|
||||
it("syncOut snapshot guard re-checks the resolved source is a non-symlink regular file immediately before copying (validation→copy TOCTOU)", async () => {
|
||||
const hostDir = await makeHostDir();
|
||||
const sandbox = createMockSandbox();
|
||||
|
||||
@@ -619,6 +619,8 @@ function leaseMetadata(input: {
|
||||
shellCommand: "bash" | "sh";
|
||||
remoteCwd: string;
|
||||
resumedLease: boolean;
|
||||
resumedFromState?: string | null;
|
||||
sandboxState?: string | null;
|
||||
workspaceSentinel?: WorkspaceSentinelResult;
|
||||
}) {
|
||||
return {
|
||||
@@ -626,7 +628,7 @@ function leaseMetadata(input: {
|
||||
shellCommand: input.shellCommand,
|
||||
sandboxId: input.sandbox.id,
|
||||
sandboxName: input.sandbox.name,
|
||||
sandboxState: input.sandbox.state ?? null,
|
||||
sandboxState: input.sandboxState ?? input.sandbox.state ?? null,
|
||||
image: input.config.image,
|
||||
snapshot: input.config.snapshot,
|
||||
target: input.sandbox.target,
|
||||
@@ -637,6 +639,9 @@ function leaseMetadata(input: {
|
||||
...(input.config.archiveOnRelease ? { archiveOnRelease: true } : {}),
|
||||
remoteCwd: input.remoteCwd,
|
||||
resumedLease: input.resumedLease,
|
||||
...(input.resumedLease
|
||||
? { resumedFromState: input.resumedFromState ?? null }
|
||||
: {}),
|
||||
// Record the resources Paperclip attempted to request so future diagnosis
|
||||
// can compare requested allocation against what Daytona provisioned.
|
||||
...(input.config.cpu != null ? { cpu: input.config.cpu } : {}),
|
||||
@@ -2187,61 +2192,72 @@ const plugin = definePlugin({
|
||||
return { providerLeaseId: null, metadata: { expired: true } };
|
||||
}
|
||||
|
||||
// A stopped sandbox loses its session shell, so the stored session id is
|
||||
// stale after a real restart. Clear the id only when the sandbox is not
|
||||
// already running, and clear it before the restart. A stopped sandbox has
|
||||
// no live session, so the clear drops a dead id and a later command opens
|
||||
// a fresh session. A running sandbox keeps its live session, so the resume
|
||||
// leaves the id in place; a concurrent command still finds it and teardown
|
||||
// deletes one session. An unconditional clear would drop the id of a live
|
||||
// session and leak its shell until sandbox reaping.
|
||||
if (sandbox.state !== "started") {
|
||||
sandboxHandleSessionStore.clear(scope);
|
||||
// A stopped sandbox loses its pseudo-terminals, so a stored duplex channel
|
||||
// is dead after a real restart. Close and drop every channel on this lease
|
||||
// before the restart, so no stale channel id survives the resume.
|
||||
await closeDaytonaDuplexChannelsForLease(params.providerLeaseId);
|
||||
}
|
||||
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs));
|
||||
try {
|
||||
const remoteCwd = await resolveSandboxWorkingDirectory(sandbox);
|
||||
// C3: a resumed lease must clear the workspace sentinel before it is
|
||||
// trusted, even when the handle came from the cache. On any non-match we
|
||||
// evict the cached handle and expire the lease so a stale/foreign sandbox
|
||||
// is never reused on the subsequent (sentinel-skipping) exec path.
|
||||
const workspaceSentinel = await verifyWorkspaceSentinel({
|
||||
sandbox,
|
||||
remoteCwd,
|
||||
leaseMetadata: params.leaseMetadata,
|
||||
timeoutSeconds: toTimeoutSeconds(config.timeoutMs),
|
||||
});
|
||||
if (workspaceSentinel.result !== "matched") {
|
||||
evictSandboxHandle(scope);
|
||||
return { providerLeaseId: null, metadata: { expired: true, workspaceSentinel } };
|
||||
}
|
||||
const shellCommand = await detectSandboxShellCommand(sandbox, toTimeoutSeconds(config.timeoutMs));
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
sandboxHandleLeaseAdmissionStates.open(scope);
|
||||
return {
|
||||
providerLeaseId: sandbox.id,
|
||||
metadata: leaseMetadata({
|
||||
config,
|
||||
sandbox,
|
||||
shellCommand,
|
||||
remoteCwd,
|
||||
resumedLease: true,
|
||||
workspaceSentinel,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
evictSandboxHandle(scope);
|
||||
// A timeout, rate limit, or provider 5xx does not prove this sandbox is
|
||||
// lost. Preserve the exact resource and let the host retry its recorded
|
||||
// lease; replacement is permitted only after an explicit not-found or
|
||||
// an immutable workspace identity mismatch.
|
||||
throw error;
|
||||
}
|
||||
}, { allowClosed: true });
|
||||
// A stopped sandbox loses its session shell, so the stored session id is
|
||||
// stale after a real restart. Clear the id only when the sandbox is not
|
||||
// already running, and clear it before the restart. A stopped sandbox has
|
||||
// no live session, so the clear drops a dead id and a later command opens
|
||||
// a fresh session. A running sandbox keeps its live session, so the resume
|
||||
// leaves the id in place; a concurrent command still finds it and teardown
|
||||
// deletes one session. An unconditional clear would drop the id of a live
|
||||
// session and leak its shell until sandbox reaping.
|
||||
if (sandbox.state !== "started") {
|
||||
sandboxHandleSessionStore.clear(scope);
|
||||
// A stopped sandbox loses its pseudo-terminals, so a stored duplex channel
|
||||
// is dead after a real restart. Close and drop every channel on this lease
|
||||
// before the restart, so no stale channel id survives the resume.
|
||||
await closeDaytonaDuplexChannelsForLease(params.providerLeaseId);
|
||||
}
|
||||
const resumedFromState = sandbox.state ?? null;
|
||||
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs));
|
||||
try {
|
||||
const remoteCwd = await resolveSandboxWorkingDirectory(sandbox);
|
||||
// C3: a resumed lease must clear the workspace sentinel before it is
|
||||
// trusted, even when the handle came from the cache. On any non-match we
|
||||
// evict the cached handle and expire the lease so a stale/foreign sandbox
|
||||
// is never reused on the subsequent (sentinel-skipping) exec path.
|
||||
const workspaceSentinel = await verifyWorkspaceSentinel({
|
||||
sandbox,
|
||||
remoteCwd,
|
||||
leaseMetadata: params.leaseMetadata,
|
||||
timeoutSeconds: toTimeoutSeconds(config.timeoutMs),
|
||||
});
|
||||
if (workspaceSentinel.result !== "matched") {
|
||||
evictSandboxHandle(scope);
|
||||
return {
|
||||
providerLeaseId: null,
|
||||
metadata: { expired: true, workspaceSentinel },
|
||||
};
|
||||
}
|
||||
const shellCommand = await detectSandboxShellCommand(
|
||||
sandbox,
|
||||
toTimeoutSeconds(config.timeoutMs),
|
||||
);
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
sandboxHandleLeaseAdmissionStates.open(scope);
|
||||
return {
|
||||
providerLeaseId: sandbox.id,
|
||||
metadata: leaseMetadata({
|
||||
config,
|
||||
sandbox,
|
||||
shellCommand,
|
||||
remoteCwd,
|
||||
resumedLease: true,
|
||||
resumedFromState,
|
||||
sandboxState: "started",
|
||||
workspaceSentinel,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
evictSandboxHandle(scope);
|
||||
// A timeout, rate limit, or provider 5xx does not prove this sandbox is
|
||||
// lost. Preserve the exact resource and let the host retry its recorded
|
||||
// lease; replacement is permitted only after an explicit not-found or
|
||||
// an immutable workspace identity mismatch.
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
{ allowClosed: true },
|
||||
);
|
||||
},
|
||||
|
||||
async onEnvironmentReleaseLease(
|
||||
@@ -2828,18 +2844,28 @@ const plugin = definePlugin({
|
||||
providerLeaseId: params.lease.providerLeaseId,
|
||||
config,
|
||||
};
|
||||
return await withSandboxActivityGate(scope, async () => {
|
||||
const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
|
||||
await ensureSandboxStarted(sandbox, timeoutSeconds);
|
||||
const result = await performSyncOut({
|
||||
sandbox,
|
||||
operations: params.operations,
|
||||
remoteDir,
|
||||
timeoutSeconds,
|
||||
try {
|
||||
return await withSandboxActivityGate(scope, async () => {
|
||||
const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
|
||||
await ensureSandboxStarted(sandbox, timeoutSeconds);
|
||||
const result = await performSyncOut({
|
||||
sandbox,
|
||||
operations: params.operations,
|
||||
remoteDir,
|
||||
timeoutSeconds,
|
||||
});
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
return result;
|
||||
});
|
||||
sandboxHandleCache.markFresh(scope);
|
||||
return result;
|
||||
});
|
||||
} catch (error) {
|
||||
// A deleted Daytona sandbox is the one provider failure that proves its
|
||||
// unexported workspace bytes no longer exist. Convert the SDK class to a
|
||||
// stable cross-worker message; every other error remains retryable.
|
||||
if (error instanceof DaytonaNotFoundError) {
|
||||
throw new Error("daytona_sandbox_not_found");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
// Open one live login pseudo-terminal. Resolve the cached sandbox by the
|
||||
|
||||
Reference in new issue
Block a user