diff --git a/server/src/services/remote-workspace-recovery-attachments.test.ts b/server/src/services/remote-workspace-recovery-attachments.test.ts new file mode 100644 index 00000000000..358dabf5d6f --- /dev/null +++ b/server/src/services/remote-workspace-recovery-attachments.test.ts @@ -0,0 +1,109 @@ +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; +import { removeRemoteRecoveryAttachment, type RemoteWorkspaceTarget } from "./remote-workspace-transport.js"; +import { retainRemoteRecoveryAttachments } from "./remote-workspace-recovery-attachments.js"; + +const exec = promisify(execFile); + +describe("retired recovered copies with real sandbox commands", () => { + let scratch: string; + let workspace: string; + beforeEach(async () => { + scratch = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "remote-recovery-attachments-"))); + workspace = path.join(scratch, "workspace"); + await fs.mkdir(workspace); + }); + afterEach(async () => { await fs.rm(scratch, { recursive: true, force: true }); }); + + function target() { + const execute = vi.fn(async input => { + try { + const result = await exec(input.command, input.args ?? [], { + cwd: input.cwd ?? workspace, timeout: input.timeoutMs, env: { PATH: process.env.PATH, ...input.env } }); + return { stdout: result.stdout, stderr: result.stderr, exitCode: 0, timedOut: false, signal: null, + pid: process.pid, startedAt: new Date().toISOString() }; + } catch (error) { + const failure = error as { code?: number; stdout?: string; stderr?: string; signal?: string }; + return { exitCode: typeof failure.code === "number" ? failure.code : 1, stdout: failure.stdout ?? "", + stderr: failure.stderr ?? "", timedOut: false, signal: failure.signal ?? null, + pid: process.pid, startedAt: new Date().toISOString() }; + } + }); + const transfer: NonNullable = async () => ({ operations: [] }); + const runner: CommandManagedRuntimeRunner = { execute, syncOut: transfer, syncIn: transfer }; + return { remote: { kind: "remote", transport: "sandbox", remoteCwd: workspace, runner } as RemoteWorkspaceTarget, execute }; + } + + async function retiredCopy(state: "foreign" | "directory_symlink" | "present") { + const operationId = randomUUID(), sourceRunId = randomUUID(); + const directory = path.join(workspace, ".paperclip-recovered", operationId); + const provenance = JSON.stringify({ operationId, sourceRunId }); + await fs.mkdir(path.join(directory, "files"), { recursive: true }); + await fs.writeFile(path.join(directory, "files", "kept.txt"), "kept\n"); + await fs.writeFile(path.join(directory, "provenance.json"), state === "foreign" ? "foreign proof" : provenance); + let outside = ""; + if (state === "directory_symlink") { + outside = path.join(scratch, "outside-attachment"); + await fs.rename(directory, outside); await fs.symlink(outside, directory); + } + return { operationId, sourceRunId, directory, provenance, outside }; + } + + it.each([["foreign", "attachment_proof_changed"], ["directory_symlink", "unsafe_attachment"]] as const)( + "names the closed reason a sandbox refused a removal for: %s", async (state, reason) => { + const { operationId, provenance } = await retiredCopy(state); + // The cause carries no sandbox path or file text. + await expect(removeRemoteRecoveryAttachment({ target: target().remote, remoteCwd: workspace, operationId, provenance })) + .rejects.toThrow(new RegExp(`^remote_workspace_operation_failed: operation=recovery_attachment exit=1; ` + + `remote_workspace_recovery_attachment_invalid: reason=${reason}$`)); + }); + + it.each(["foreign", "directory_symlink", "present"] as const)( + "continues preparation when a retired recovered copy cannot be removed: %s", async state => { + const { operationId, sourceRunId, directory, provenance, outside } = await retiredCopy(state); + const recoveredFiles: Parameters[0]["recoveredFiles"] = []; + const item = { operationId, sourceRunId, path: `.paperclip-recovered/${operationId}`, provenance }; + // A recorded proof needs no database read; only the sandbox command runs. + await expect(retainRemoteRecoveryAttachments({ db: {} as never, runId: randomUUID(), remoteRoot: workspace, + target: target().remote, recoveredFiles, retiredOperationIds: new Set([operationId]), + workspace: { id: randomUUID(), companyId: randomUUID(), sourceIssueId: null, + metadata: { remoteWorkspaceRecoveredFiles: [{ ...item, retired: true }] } } })).resolves.toBeUndefined(); + // The copy stays retired, so it is never shown again, and is removed only with its exact proof. + expect(recoveredFiles).toEqual([{ ...item, retired: true }]); + if (state === "present") expect(await fs.lstat(directory).catch(() => null)).toBeNull(); + else expect(await fs.readFile(path.join(outside || directory, "files", "kept.txt"), "utf8")).toBe("kept\n"); + }); + + it.each([ + ["an SSH connection failure", 255, "ssh: connect to host sandbox port 22: Connection refused"], + ["an unexplained exit", 1, "node: command not found"], + ] as const)("does not hide %s while removing a retired recovered copy", async (_name, exitCode, stderr) => { + const operationId = randomUUID(), sourceRunId = randomUUID(); + const item = { operationId, sourceRunId, path: `.paperclip-recovered/${operationId}`, provenance: "{}", retired: true }; + const { remote, execute } = target(); + execute.mockResolvedValueOnce({ exitCode, stdout: "", stderr, timedOut: false, signal: null, + pid: process.pid, startedAt: new Date().toISOString() }); + await expect(retainRemoteRecoveryAttachments({ db: {} as never, runId: randomUUID(), remoteRoot: workspace, + target: remote, recoveredFiles: [], retiredOperationIds: new Set([operationId]), + workspace: { id: randomUUID(), companyId: randomUUID(), sourceIssueId: null, + metadata: { remoteWorkspaceRecoveredFiles: [item] } } })) + .rejects.toThrow(new RegExp(`^remote_workspace_operation_failed: operation=recovery_attachment exit=${exitCode}$`)); + }); + + it("does not hide a provider failure while removing a retired recovered copy", async () => { + const operationId = randomUUID(), sourceRunId = randomUUID(); + const item = { operationId, sourceRunId, path: `.paperclip-recovered/${operationId}`, provenance: "{}", retired: true }; + const { remote, execute } = target(); + execute.mockRejectedValueOnce(new Error("sandbox connection reset")); + await expect(retainRemoteRecoveryAttachments({ db: {} as never, runId: randomUUID(), remoteRoot: workspace, + target: remote, recoveredFiles: [], retiredOperationIds: new Set([operationId]), + workspace: { id: randomUUID(), companyId: randomUUID(), sourceIssueId: null, + metadata: { remoteWorkspaceRecoveredFiles: [item] } } })).rejects.toThrow("sandbox connection reset"); + }); +}); diff --git a/server/src/services/remote-workspace-recovery-attachments.ts b/server/src/services/remote-workspace-recovery-attachments.ts index 7b7eff790fa..af299d642f9 100644 --- a/server/src/services/remote-workspace-recovery-attachments.ts +++ b/server/src/services/remote-workspace-recovery-attachments.ts @@ -1,7 +1,7 @@ import { lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import os from "node:os"; -import { hasRemoteRecoveryAttachment, removeRemoteRecoveryAttachment, type RemoteWorkspaceTarget } from "./remote-workspace-transport.js"; +import { hasRemoteRecoveryAttachment, isRemoteRecoveryAttachmentRefusal, removeRemoteRecoveryAttachment, type RemoteWorkspaceTarget } from "./remote-workspace-transport.js"; import { removeTaskDirectoryTree } from "./isolated-task-directory-snapshot.js"; import { LEGACY_WORKSPACE_RECOVERY_MIGRATION } from "./legacy-workspace-recovery-migration.js"; import { and, eq, inArray, sql } from "drizzle-orm"; @@ -301,7 +301,17 @@ export async function retainRemoteRecoveryAttachments(input: { await input.assertOwned?.(); const location = { target: input.target, remoteCwd: input.remoteRoot, operationId: item.operationId, provenance }; if (input.retiredOperationIds.has(item.operationId)) { - await removeRemoteRecoveryAttachment(location); + // Removing a retired copy only reduces save size; it is never shown + // again. When the sandbox refuses (its proof changed, the path is not a + // plain directory, a file cannot be deleted), its files stay in place + // and the run continues. Failing here failed every later preparation + // that restored the same save. + await removeRemoteRecoveryAttachment(location).catch((error: unknown) => { + if (!isRemoteRecoveryAttachmentRefusal(error)) throw error; + logger.warn({ companyId: input.workspace.companyId, workspaceId: input.workspace.id, runId: input.runId, + operationId: item.operationId, code: "remote_workspace_retired_copy_kept", cause: error.message }, + "A retired recovered copy was left in the workspace because the sandbox refused to remove it"); + }); input.recoveredFiles.push({ operationId: item.operationId, sourceRunId: item.sourceRunId, path: item.path, provenance, retired: true }); continue; } diff --git a/server/src/services/remote-workspace-transport.ts b/server/src/services/remote-workspace-transport.ts index 45d2f3ecfaa..bf043ab5bca 100644 --- a/server/src/services/remote-workspace-transport.ts +++ b/server/src/services/remote-workspace-transport.ts @@ -106,6 +106,9 @@ const SETUP_FAILURE_CHECK = String.raw`const setupFailure=(prefix,stage,error)=> for(const field of failureDetail(error).split(' ').filter(Boolean))if(!fields.some(value=>value.startsWith(field.split('=')[0]+'='))&&!(field==='reason=git_storage_guard_unavailable'&&fields.includes('git=storage_guard_unavailable')))fields.push(field); return prefix+': '+fields.join(' ');};`; const SANDBOX_SETUP_CAUSE = /^remote_workspace_(prepare|repository|restore)_failed: stage=[a-z_]{1,32}(?: (?:reason|archive|disk|git|code|exit|signal|syscall|killed|program|name)=[A-Za-z0-9_]{1,64}){0,16}$/; +// A recovered-copy check names its own refusal or the filesystem errno; never a path. +const SANDBOX_RECOVERY_ATTACHMENT_CAUSE = + /^remote_workspace_recovery_attachment_invalid: reason=(?:invalid_attachment|unsafe_attachment|missing_workspace|attachment_proof_changed|filesystem)(?: code=E[A-Z0-9]{1,20})?$/; type RemoteWorkspaceOperation = "prepare" | "repository" | "archive_helper" | "capture" | "download" | "upload" | "restore" | "cleanup" | "recovery_attachment"; @@ -293,7 +296,9 @@ async function command(target: RemoteWorkspaceTarget, operation: RemoteWorkspace if (reported) throw new Error(reported); const cause = operation === "capture" || operation === "archive_helper" ? output.find(value => value.length <= 1024 && SANDBOX_CAPTURE_CAUSE.test(value)) - : output.find(value => value.length <= 1024 && SANDBOX_SETUP_CAUSE.exec(value)?.[1] === operation); + : operation === "recovery_attachment" + ? output.find(value => value.length <= 1024 && SANDBOX_RECOVERY_ATTACHMENT_CAUSE.test(value)) + : output.find(value => value.length <= 1024 && SANDBOX_SETUP_CAUSE.exec(value)?.[1] === operation); const status = [`operation=${operation}`, Number.isSafeInteger(result.exitCode) ? `exit=${result.exitCode}` : null, typeof result.signal === "string" && /^SIG[A-Z0-9]{1,12}$/.test(result.signal) ? `signal=${result.signal}` : null, @@ -331,7 +336,10 @@ const fs=require('node:fs/promises'),path=require('node:path'); if(input.remove!==true){process.stdout.write('present');return} await fs.rename(destination,retiring);await discard(); process.stdout.write('removed'); -})().catch(()=>{process.stderr.write('remote_workspace_recovery_attachment_invalid');process.exitCode=1});`; +})().catch(e=>{const known=['invalid_attachment','unsafe_attachment','missing_workspace','attachment_proof_changed']; + const code=typeof e?.code==='string'&&/^E[A-Z0-9]{1,20}$/.test(e.code)?' code='+e.code:''; + process.stderr.write('remote_workspace_recovery_attachment_invalid: reason='+(known.includes(e?.message)?e.message:'filesystem')+code); + process.exitCode=1});`; /** Reuse a restored attachment only with its exact provenance. User edits to * its files remain intact; unknown destinations are never overwritten. */ @@ -355,6 +363,19 @@ export async function removeRemoteRecoveryAttachment(input: { return output === "removed"; } +// The recovered-copy script exits 1 after writing one closed reason. Any other +// failure, such as an SSH connection error (exit 255) with no reason, is not a +// refusal by the script. +const RECOVERY_ATTACHMENT_REFUSAL = new RegExp( + `^remote_workspace_operation_failed: operation=recovery_attachment exit=1; ${SANDBOX_RECOVERY_ATTACHMENT_CAUSE.source.slice(1)}`); + +/** The sandbox ran the recovered-copy check and refused it with its closed + * reason. Timeouts, provider transport failures and unexplained exits are not + * refusals. */ +export function isRemoteRecoveryAttachmentRefusal(error: unknown): error is RemoteWorkspaceOperationError { + return error instanceof RemoteWorkspaceOperationError && RECOVERY_ATTACHMENT_REFUSAL.test(error.message); +} + // A fresh clone from a network remote is blobless (--filter=blob:none): it gets // every commit and tree, but only the file contents a checkout needs. A full // clone also downloads every historical blob, which alone can exceed a Cloud