fix: retain bounded workspace transfer failure evidence (#15637)

## Thinking Path

> - Paperclip manages AI agents and the work they produce.
> - Sandbox work must return to the host when an agent run ends.
> - A failed transfer must keep its source available for recovery.
> - Some transfer errors lose their useful fields before restore
diagnostics reach Sentry.
> - This change records fixed transfer stages, failure kinds, and
numeric RPC codes.
> - The next failure can identify the operation that failed without
exposing workspace contents.

## Linked Issues or Issue Description

**What happened?**

A workspace transfer can fail after model execution succeeds. Several
command, archive validation, and download errors become plain errors.
The existing RPC envelope then reports `unknown`, with no transfer stage
or command exit code. A host RPC timeout also loses its code from
restore diagnostics.

**Expected behavior**

Keep bounded evidence through the provider, worker RPC, restore result,
and Sentry context. Keep the same exception, error message, retry rules,
and source retention policy. A transfer timeout must remain separate
from the model execution timeout flag.

**Steps to reproduce**

Return a nonzero exit code from the sandbox archive command, return a
per-file download error, exceed a tar listing limit, or time out the
sync-out RPC. Observe the missing fields in the saved restore
diagnostic. The added tests use local fixtures for these cases.

Related public work: #15479 preserves the source after restore failure.
#15481 carries bounded sync-out diagnostics through RPC. This change
supplies missing producer evidence and extends that same envelope. I
checked the roadmap and searched open PRs for duplicate transfer
diagnostic work.

## What Changed

- Add optional transfer stage and failure kind fields to the existing
diagnostic envelope. Capture command exits and listing deadlines at
their producers.
- Record only known codes from typed RPC errors at the sync-out
boundary. Revalidate every field before persistence and Sentry
projection.
- Keep annotations private to each outbound request and restore
settlement. Preserve frozen error identity and prevent evidence from
leaking across concurrent or later calls.
- Document the fields. Cover producer failures, quota limits, old
workers, concurrent error reuse, and redaction through the real Sentry
SDK.

## Verification

- Focused SDK, provider, host, persistence, and real Sentry tests: 449
passed, no skips. Independent review also ran the focused contracts and
all provider tests. The optional Sentry SDK is required for this check,
so the contract tests cannot skip.
- A compiled Daytona transfer and compiled SDK worker pass a local RPC
round trip. This uses the development TypeScript loader for workspace
dependency exports. The transfer and capture modules are compiled
JavaScript.
- `pnpm -r typecheck` and `pnpm build` passed. The excluded Daytona
package also passed `tsc --noEmit`.
- The initial local `pnpm test:run` stopped in the general-server group:
60 suites could not initialize embedded PostgreSQL because the isolated
install skipped its Darwin library-link setup. The existing package
postinstall repairs this; `initdb --version` now passes. All 60 affected
suites then passed: 1,342 tests, no skips. No local full aggregate pass
is claimed.
- Independent source review covers privacy, concurrency, packaging, and
recovery behavior.

## Risks

- These diagnostics help identify future failures. They do not establish
or repair the cause of a past transfer failure.
- New fields are optional. Older workers remain compatible. Unknown
values are omitted.
- The change adds a small request-local diagnostic scope. It keeps the
original thrown errors, archive confinement, cleanup order, timeout
values, retry count, and source retention policy.
- No schema or deployment changes are required. No live provider actions
are part of validation.

## Model Used

OpenAI Codex, based on GPT-6, with repository inspection, code
execution, and independent agent review. The exact deployed model ID and
context-window size are not exposed in this session.

## 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
- [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:
Devin FoleyandPaperclip authored and GitHub committed 2026-10-08 19:27:39 -07:00
1 parent 9b624a110e
commit 1c4ce44e13
17 files changed
+660 -102

No files matched your search

@@ -3,6 +3,7 @@ import { PassThrough } from "node:stream";
import { describe, expect, it } from "vitest";
import {
createRequest, definePlugin, isJsonRpcResponse, JsonRpcCallError, parseMessage,
readEnvironmentSyncErrorDiagnostic, withEnvironmentSyncTransferStep, recordEnvironmentSyncError,
PLUGIN_RPC_ERROR_CODES, serializeMessage, startWorkerRpcHost, type JsonRpcResponse,
} from "@paperclipai/plugin-sdk";
import {
@@ -53,8 +54,9 @@ describe("environment sync-out restore diagnostics", () => {
await expect(withWorkspaceRestoreDiagnostics("workspace", () => withWorkspaceRestoreStep("workspace_transfer", async () => {
throw preserveEnvironmentSyncOutErrorDiagnostic(error);
}), async (line) => { logs.push(line); })).rejects.toBe(error);
expect(getWorkspaceRestoreDiagnostic(error)).toEqual({ phase: "workspace", step: "workspace_transfer", errorCode: "ETIMEDOUT", httpStatus: 504 });
expect(logs).toEqual(['[paperclip] Workspace restore diagnostic: {"phase":"workspace","step":"workspace_transfer","errorCode":"ETIMEDOUT","httpStatus":504}\n']);
expect(getWorkspaceRestoreDiagnostic(error)).toEqual({ phase: "workspace", step: "workspace_transfer", errorCode: "ETIMEDOUT", httpStatus: 504, rpcCode: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR });
expect(logs).toHaveLength(1);
expect(JSON.parse(logs[0].slice(logs[0].indexOf("{")))).toEqual(getWorkspaceRestoreDiagnostic(error));
expect({ message: error.message, code: error.code, data: error.data }).toEqual(before);
expect(error).not.toHaveProperty("cause");
});
@@ -76,3 +78,69 @@ describe("environment sync-out restore diagnostics", () => {
expect(preserveEnvironmentSyncOutErrorDiagnostic(null)).toBeNull();
});
});
it("isolates overlapping and sequential worker calls that throw the same object", async () => {
const original = Object.freeze(new Error("Transfer failed"));
const before = Object.getOwnPropertyDescriptors(original);
const stdin = new PassThrough();
const stdout = new PassThrough();
const lines = createInterface({ input: stdout });
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
let started!: () => void;
const ready = new Promise<void>(resolve => { started = resolve; });
const worker = startWorkerRpcHost({ stdin, stdout, plugin: definePlugin({
async setup() {},
async onEnvironmentSyncOut(params) {
if (params.operations?.[0]?.operationId === "first") {
return withEnvironmentSyncTransferStep("archive_create", async () => {
recordEnvironmentSyncError(original, { exitCode: 2, transferFailureKind: "command_failed" });
started(); await gate; throw original;
});
}
if (params.operations?.[0]?.operationId === "second") {
return withEnvironmentSyncTransferStep("file_download", async () => { throw original; });
}
throw original;
},
async onEnvironmentSyncIn() { throw original; },
}) });
const call = (id: string, method = "environmentSyncOut") => new Promise<JsonRpcCallError>((resolve) => {
const listener = (wire: string) => {
const message = parseMessage(wire);
if (isJsonRpcResponse(message) && message.id === id && message.error) {
lines.off("line", listener); resolve(new JsonRpcCallError(message.error));
}
};
lines.on("line", listener);
stdin.write(serializeMessage(createRequest(method, { operations: [{ operationId: id, files: [] }] }, id)));
});
try {
const first = call("first");
await ready;
const second = await call("second");
expect(readEnvironmentSyncErrorDiagnostic(second)).toEqual({ errorCode: "unknown", transferStep: "file_download" });
release();
expect(readEnvironmentSyncErrorDiagnostic(await first)).toEqual({
errorCode: "unknown", transferStep: "archive_create", transferFailureKind: "command_failed", exitCode: 2,
});
expect((await call("third")).data).toBeUndefined();
expect((await call("unrelated", "environmentSyncIn")).data).toBeUndefined();
expect(Object.getOwnPropertyDescriptors(original)).toEqual(before);
} finally { release(); worker.stop(); lines.close(); stdin.destroy(); stdout.destroy(); }
});
it.each([
[new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.TIMEOUT, message: "private-rpc-message" }), PLUGIN_RPC_ERROR_CODES.TIMEOUT],
[new JsonRpcCallError({ code: 123, message: "private-rpc-message" }), undefined],
[Object.assign(new Error("private-rpc-message"), { code: PLUGIN_RPC_ERROR_CODES.TIMEOUT }), undefined],
])("records known typed RPC codes without interpreting arbitrary errors", async (error, rpcCode) => {
const logs: string[] = [];
await expect(withWorkspaceRestoreDiagnostics("workspace", () => withWorkspaceRestoreStep("workspace_transfer", async () => {
throw preserveEnvironmentSyncOutErrorDiagnostic(error);
}), async line => { logs.push(line); })).rejects.toBe(error);
expect(getWorkspaceRestoreDiagnostic(error)?.rpcCode).toBe(rpcCode);
expect(getWorkspaceRestoreDiagnostic(error)?.transferStep).toBeUndefined();
expect(JSON.stringify(logs)).not.toContain("private-");
});
@@ -378,4 +378,64 @@ describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK",
expect(unrelated).not.toHaveProperty("contexts.run_failure");
expect(unrelated).not.toHaveProperty("tags.error_code");
});
it("sends only validated transfer and RPC evidence, isolated from unrelated captures", async () => {
const Sentry = sentryPackage!;
const events: Array<Record<string, unknown>> = [];
vi.stubEnv("SENTRY_DSN_BACKEND", "https://public@example.invalid/1");
vi.doMock("../peer-version-check.js", () => ({ checkExactPeerVersions: () => ({ ok: true }) }));
vi.doMock("@sentry/node", () => ({ ...Sentry,
init: (options: Record<string, unknown>) => Sentry.init({ ...options,
transport: () => ({ send: async () => ({}), flush: async () => true }),
beforeSend: (event: Record<string, unknown>) => { events.push(event); return event; },
}),
}));
vi.resetModules();
const { sentryReady, captureRunFailure, captureException } = await import("../sentry.js");
await sentryReady;
for (const known of [true, false]) {
const error = Object.freeze(new Error("private-transfer-message"));
// Worker/typed-host propagation has its own real RPC round-trip test.
// This narrow contract exercises the host receipt through the real Sentry
// transport without requiring plugin builds or dependency lifecycle scripts.
const evidence = {
transferStep: known ? "archive_create" : "private-transfer-path",
transferFailureKind: known ? "command_failed" : "private-transfer-command",
rpcCode: known ? -32002 : -12345,
cause: { token: "private-transfer-token" }, output: "private-transfer-output",
};
const logs: string[] = [];
const restore = createWorkspaceRestoreTeardown({ stagedRuntime: {
restoreWorkspace: progress => withWorkspaceRestoreDiagnostics("workspace", () =>
withWorkspaceRestoreStep("workspace_transfer", async () => { throw preserveWorkspaceRestoreErrorDiagnostic(error, { exitCode: 2 }, evidence); }), progress),
}, onLog: async (_stream, line) => { logs.push(line); }, startMessage: "Restoring workspace\n", failurePrefix: "Workspace restore failed" });
const outcome = await restore();
expect(outcome.ok).toBe(false);
if (outcome.ok) throw new Error("Expected transfer fixture failure");
expect(outcome.diagnostic?.rpcCode).toBe(known ? -32002 : undefined);
expect(JSON.stringify({ outcome, logs })).not.toContain("private-transfer-");
const diagnostics = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics({ resultJson: {
workspaceRestoreFailure: outcome.code, workspaceRestoreDiagnostic: { ...outcome.diagnostic,
message: "private-transfer-persisted", cause: { token: "private-transfer-token" },
},
} } as unknown as typeof heartbeatRuns.$inferSelect, {}));
captureRunFailure({ taskId: "11111111-1111-4111-8111-111111111111", runId: "22222222-2222-4222-8222-222222222222",
errorMessage: "Workspace restore failed. Workspace files need recovery.", errorCode: "workspace_restore_failed",
agentAdapter: "fixture-adapter", runStatus: "failed", exitCode: 1, signal: null, diagnostics,
});
await Sentry.flush(2000);
const execution = (events.at(-1)?.contexts as Record<string, Record<string, unknown>>).run_execution;
expect(execution.workspaceRestoreTransferStep).toBe(known ? "archive_create" : undefined);
expect(execution.workspaceRestoreTransferFailureKind).toBe(known ? "command_failed" : undefined);
expect(execution.workspaceRestoreRpcCode).toBe(known ? -32002 : undefined);
expect(execution.workspaceRestoreExitCode).toBe(2);
}
captureException(new Error("Unrelated transfer fixture"));
await Sentry.flush(2000);
expect(events).toHaveLength(3);
expect(events[2]).not.toHaveProperty("contexts.run_execution");
expect(events[2]).not.toHaveProperty("contexts.run_failure");
expect(events[2]).not.toHaveProperty("tags.error_code");
expect(JSON.stringify(events)).not.toContain("private-transfer-");
});
});
@@ -342,3 +342,33 @@ describe("run failure diagnostics", () => {
expect(collectRunFailureDiagnostics(run({ startedAt: new Date(NaN), finishedAt: new Date() }), {}).execution).not.toHaveProperty("durationMs");
});
});
it("revalidates persisted transfer evidence and excludes arbitrary nested payloads", () => {
for (const known of [true, false]) {
const result = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics(run({ resultJson: {
workspaceRestoreFailure: "restore_failed", workspaceRestoreDiagnostic: {
phase: "workspace", step: "workspace_transfer", errorCode: "unknown",
transferStep: known ? "archive_create" : "private-command",
transferFailureKind: known ? "command_failed" : "private-output", rpcCode: known ? -32003 : -12345,
command: "private-command", cause: { message: "private-nested-message" },
},
} }), {}));
expect(result.execution.workspaceRestoreTransferStep).toBe(known ? "archive_create" : undefined);
expect(result.execution.workspaceRestoreTransferFailureKind).toBe(known ? "command_failed" : undefined);
expect(result.execution.workspaceRestoreRpcCode).toBe(known ? -32003 : undefined);
expect(JSON.stringify(result)).not.toContain("private-");
}
});
it("does not project transfer fields into an unrelated restore step", () => {
const result = collectRunFailureDiagnostics(run({ resultJson: {
workspaceRestoreFailure: "restore_failed", workspaceRestoreDiagnostic: {
phase: "workspace", step: "git_import", errorCode: "unknown",
transferStep: "archive_create", transferFailureKind: "command_failed", rpcCode: -32003,
},
} }), {});
expect(result.execution).not.toHaveProperty("workspaceRestoreTransferStep");
expect(result.execution).not.toHaveProperty("workspaceRestoreTransferFailureKind");
expect(result.execution).not.toHaveProperty("workspaceRestoreRpcCode");
});
@@ -1,15 +1,17 @@
import { readEnvironmentSyncErrorDiagnostic } from "@paperclipai/plugin-sdk";
import { readEnvironmentSyncErrorDiagnostic, JsonRpcCallError, PLUGIN_RPC_ERROR_CODES } from "@paperclipai/plugin-sdk";
import { preserveWorkspaceRestoreErrorDiagnostic } from "@paperclipai/adapter-utils/workspace-restore-diagnostics";
/** Keep the original RPC failure and policy fields; add only private diagnostic evidence. */
export function preserveEnvironmentSyncOutErrorDiagnostic(error: unknown): unknown {
const diagnostic = readEnvironmentSyncErrorDiagnostic(error);
if (diagnostic && error && typeof error === "object") {
const rpcCode = error instanceof JsonRpcCallError && (Object.values(PLUGIN_RPC_ERROR_CODES) as number[]).includes(error.code)
? error.code : undefined;
if ((diagnostic || rpcCode !== undefined) && error && typeof error === "object") {
preserveWorkspaceRestoreErrorDiagnostic(error, {
code: diagnostic.errorCode,
status: diagnostic.httpStatus,
exitCode: diagnostic.exitCode,
});
code: diagnostic?.errorCode,
status: diagnostic?.httpStatus,
exitCode: diagnostic?.exitCode,
}, { ...diagnostic, rpcCode });
}
return error;
}
@@ -203,6 +203,9 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReport
if (diagnostic.step) execution.workspaceRestoreStep = diagnostic.step;
if (diagnostic.httpStatus !== undefined) execution.workspaceRestoreHttpStatus = diagnostic.httpStatus;
if (diagnostic.exitCode !== undefined) execution.workspaceRestoreExitCode = diagnostic.exitCode;
if (diagnostic.transferStep) execution.workspaceRestoreTransferStep = diagnostic.transferStep;
if (diagnostic.transferFailureKind) execution.workspaceRestoreTransferFailureKind = diagnostic.transferFailureKind;
if (diagnostic.rpcCode !== undefined) execution.workspaceRestoreRpcCode = diagnostic.rpcCode;
if (diagnostic.gitCommand) execution.workspaceRestoreGitCommand = diagnostic.gitCommand;
if (diagnostic.gitFailureKind) execution.workspaceRestoreGitFailureKind = diagnostic.gitFailureKind;
}