mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
fix(workspaces): keep a run going when a retired recovered copy cannot be removed (#21509)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - With remote (sandbox) execution, preparation can attach saved work of an interrupted run under `.paperclip-recovered/<operation>`. After a run that was shown that copy succeeds, the next preparation retires the copy and removes it from the sandbox (#19979). > - The removal is only a save-size cleanup. A retired copy is never shown to an agent again. > - When the sandbox refuses the removal (the proof file changed, the path is not a plain directory, or a file cannot be deleted), the whole run preparation fails with `remote_workspace_operation_failed: operation=recovery_attachment exit=1`. The sandbox script drops its own reason, so the failure tells nobody why. > - Each later preparation that restores the same save meets the same copy and fails the same way. The task cannot start. > - This pull request makes a refused removal of a retired copy non-fatal and makes the sandbox report a closed reason. > - The benefit is that the run continues with the copy left in place, and the log names why the sandbox refused. ## Linked Issues or Issue Description Refs #19979 **What happened?** On hosted staging, four runs of four different tasks failed in setup with `remote_workspace_operation_failed: operation=recovery_attachment exit=1`. The stack goes through `retainRemoteRecoveryAttachments` and `removeRemoteRecoveryAttachment`. The run stopped before any provider work. The error has no reason, because the sandbox script writes only `remote_workspace_recovery_attachment_invalid` and the server accepts no cause for this operation. **Expected behavior** A retired recovered copy that the sandbox will not remove stays in place. The run continues. The log names a closed reason for the refusal. Timeouts and provider transport failures still stop the run. **Steps to reproduce** 1. Record a retired recovered copy in the workspace metadata (`remoteWorkspaceRecoveredFiles` with `retired: true`). 2. In the sandbox, put a different `provenance.json` in `.paperclip-recovered/<operation>`, or replace that directory with a symlink. 3. Start the next run in that workspace. Preparation calls `retainRemoteRecoveryAttachments`. 4. Preparation fails with `remote_workspace_operation_failed: operation=recovery_attachment exit=1`. **Relevant logs or output** `RemoteWorkspaceOperationError: remote_workspace_operation_failed: operation=recovery_attachment exit=1` at `realizeForRun` -> `prepareRemoteWorkspace` -> `retainRemoteRecoveryAttachments` -> `removeRemoteRecoveryAttachment`. ## What Changed - The recovered-copy sandbox script now writes `remote_workspace_recovery_attachment_invalid: reason=<closed reason>[ code=<errno>]`. The reasons are `invalid_attachment`, `unsafe_attachment`, `missing_workspace`, `attachment_proof_changed`, or `filesystem`. It never writes a path or file text. - `command()` accepts only that exact grammar as the cause for the `recovery_attachment` operation. Any other output is still dropped. - New `isRemoteRecoveryAttachmentRefusal()` identifies a refusal that the sandbox reported with an exit status. Timeouts and provider transport errors do not match. - `retainRemoteRecoveryAttachments` catches only that refusal when it removes a retired copy. It logs a warning with code `remote_workspace_retired_copy_kept` and the closed cause. The files stay in place. The retired record stays, so the copy is never shown again, and the next preparation tries the removal again. - New `remote-workspace-recovery-attachments.test.ts` runs the real sandbox script. ## Verification - `cd server && npx vitest run src/services/remote-workspace-recovery-attachments.test.ts` - Before the fix: 4 of 6 fail. The retain test fails with the production message `remote_workspace_operation_failed: operation=recovery_attachment exit=1`. - After the fix: 6 of 6 pass. - Safety cases in the same file: - A retired copy with its exact proof is still removed. - A changed proof or a symlinked directory leaves every file in place, also outside the workspace. - A provider failure (the runner throws) still fails preparation. - `npx vitest run src/services/remote-workspace-transport.test.ts`: all recovery-attachment cases pass. On this machine, three unrelated Git and restore-lock cases fail with and without this change, because of the local environment. - `npx vitest run src/services/workspace-recovery-preparation.test.ts`: 81 of 81 pass. - `tsc --noEmit -p server`: no errors in the changed files. ## Risks - Low risk. Only the cleanup of an already-retired copy becomes tolerant. Live recovered copies, attachment import, and the `hasRemoteRecoveryAttachment` check keep their current behavior. - A copy that cannot be removed stays in the saved workspace. Saves are bigger for that workspace, which is the behavior from before #19979. The warning makes this visible. - The sandbox now writes a short closed reason to stderr. The server accepts only the exact grammar, so no paths or file contents reach the record. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs). ## 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 - [ ] All Paperclip CI gates are green - [ ] 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 Opus 5.5 <noreply@anthropic.com> Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: paperclipbugbot <bots+paperclipbugbot@paperclip.ing>
This commit is contained in:
3 files changed
+144
-4
No files matched your search
@@ -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<CommandManagedRuntimeRunner["execute"]>(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<CommandManagedRuntimeRunner["syncOut"]> = 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<typeof retainRemoteRecoveryAttachments>[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");
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user