From ea25af759e09297f1154e447031d1b536c27193d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:30:27 -0600 Subject: [PATCH 1/5] fix(native): name a resume that finds no saved Runner state, so Retry starts a fresh session (#20757) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A native run can continue the provider session of the previous run on the same task. In a remote sandbox, the Runner keeps the session state inside the sandbox, and the server saves a harness backup after each run. > - On staging, five runs in 48 hours failed with `native_session_recovery_failed: Error: PRP provider resume state is unavailable` (class P in `doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md`). > - In each case we read, the previous run had an accepted result, but its `harness_state.backup.persist` failed. Its per-turn sandbox was then destroyed. The next run started in a new sandbox with no Runner state for the session. > - The Runner transport threw an untyped error. The runtime could not tell it apart from a transport drop. A governed-wait or same-session checkpoint ended as a generic `native_session_interrupted` with an "ambiguous state" hold that said not to open a replacement session. > - This pull request types that refusal and lets the driver classify it as `provider_state_incompatible` when nothing is in flight. The existing recovery policy then decides. > - The benefit is that the run ends with the permanent named code `native_provider_state_incompatible`. Retry, or the next message, continues in a fresh provider session in the same workspace. No provider turn or tool call can be repeated, because the follow-up never started a turn. ## Linked Issues or Issue Description Refs #20712, #20723 (the same classification for a moved remote workspace root). Refs #20691 (fixes the `provider_identity_incomplete` part of class P). **What happened?** 1. Run A on a chat task finished. Its result was accepted. Its harness backup failed to save (`harness_state.backup.persist` failed, `native.post_result_failure`). 2. Run B started for the next chat message in a new sandbox. It rebound run A's checkpoint with `providerRecoveryPolicy: allow_replacement_after_governed_wait`. 3. The Runner found no control-plane state and no archived authority epoch. It threw `PRP provider resume state is unavailable` as a plain `Error`. 4. The runtime refused a replacement for the governed-wait policy and failed run B with the generic `native_session_recovery_failed`. The task stayed blocked with an "ambiguous state" hold. **Expected behavior** The run ends with a permanent named code and a working Retry, as it does for other deterministic refusals. **Steps to reproduce** 1. Create a Runner transport that resumes a saved provider session from an empty state directory. 2. Request `thread/read`. On `master` it rejects with a plain `Error`. 3. Recover a saved Codex, OpenCode or ACPX session through the driver when the transport fails that way. On `master` the result has no `failureClass`. **Paperclip version or commit** `master` at `9574065a28`. ## What Changed - `packages/paperclip-runner/src/contracts/harness-driver.ts`: add `NativeRunnerResumeStateUnavailableError` (same message as before) and `isRunnerResumeStateUnavailable`. - `packages/paperclip-runner/src/live/runnerd-codex-transport.ts`: throw the typed error at the three branches where the control-plane state is absent. The branch with no PRP identity and the quarantine branch are unchanged. - `packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts`: classify the typed error as `provider_state_incompatible` when the saved session has no turn or runtime request in flight. Extract the in-flight test that the moved-root check already used, without changing it. - `doc/execution-semantics.md`: describe the new classification (additive). - Tests: a transport test (local and external Runner state), driver tests for Codex, OpenCode and ACPX Claude, in-flight cases that stay unclassified, and a server case that shows the blocked task offers Retry and that one click starts exactly one fresh-session run. ## Verification - `cd packages/paperclip-runner && npx vitest run src/backends/native-backend-factory.test.ts -t "no saved state"`: 5 pass. With the driver change reverted, the 3 "reports … as provider state incompatible" cases fail (no `failureClass`). - `cd packages/paperclip-runner && npx vitest run src/live/runnerd-codex-transport-cold-restore.test.ts`: 5 pass. On `master` the error is a plain `Error`. - `cd packages/paperclip-runner && npx vitest run src/backends/native-backend-factory.test.ts src/drivers/codex/codex-app-server-driver.recovery.test.ts src/live/runnerd-codex-transport-cold-restore.test.ts src/native-session-runtime.test.ts`: 410 pass. - `cd server && npx vitest run src/services/workspace-recovery-retry-copyback.test.ts -t "does not continue automatically"`: 5 pass, including the new case. It checks `canRetry: true`, an accepted Retry, exactly one queued successor, and `forceFreshSession: true`. - `cd packages/paperclip-runner && npx tsc --noEmit -p .`: clean. - `pnpm verify`: exit 2 (broader verification required) because `doc/execution-semantics.md` is a global CI input. The focused checks above pass. Required CI supplies the broad coverage. ## Risks - Low. The change only adds a class to a failure that already failed. A checkpoint with `allow_replacement_after_resume_failure` already replaced the session for this failure, and still does. - For `same_session_only` and `allow_replacement_after_governed_wait`, the run now ends with `native_provider_state_incompatible` instead of a retryable `native_session_interrupted`. Same-run retries stop at once. They could not succeed, because the state is absent. - A session with a turn or runtime request in flight keeps the old unclassified behavior. This PR does not change it. - The server code path is unchanged. The Rust Runner is unchanged, so no new runner image is needed. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code, with tool use (shell, file edit, test execution) and read-only staging API reads. ## 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 --- doc/execution-semantics.md | 11 ++++ .../backends/native-backend-factory.test.ts | 51 ++++++++++++++++++- .../src/contracts/harness-driver.ts | 19 +++++++ .../codex/codex-app-server-driver-impl.ts | 31 +++++++---- ...nnerd-codex-transport-cold-restore.test.ts | 32 ++++++++++++ .../src/live/runnerd-codex-transport.ts | 8 +-- .../workspace-recovery-retry-copyback.test.ts | 10 +++- 7 files changed, 146 insertions(+), 16 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 5a2f0494b60..5f4951a9620 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3000,6 +3000,17 @@ replacement behavior. When a replacement does archive remote continuity state and the remote move fails, the local state is not moved, and the run error keeps the bounded, redacted exit status and output of that move. +A Runner that keeps no control-plane state for the saved session (none is live +and no archived authority epoch matches it) reports a typed refusal. This +happens when a follow-up run starts in a new sandbox and the previous run's +harness backup was not saved. Resuming again reads the same empty state. When the +saved session has no turn or runtime request in flight, the driver classifies +the refusal as `provider_state_incompatible`. The checkpoint's recovery policy +then decides: a replacement session when the policy allows it, otherwise the run +ends with `native_provider_state_incompatible`, and Retry or the next message +continues in a fresh provider session in the same workspace. A session with +work in flight keeps the unclassified behavior. + Bootstrap retries, exact-checkpoint resumes, and fresh replacement sessions share three total provider attempts, including the original attempt. Linked run IDs, controller restarts, and duplicate wakes do not reset this budget. A resume after a graceful shutdown drain suspended the run for reattachment does not consume an attempt, because the run did not cause that restart. A crash restart (no drain record) consumes an attempt only when the attempt it interrupted spent provider work without progress. This is one rule over recorded outcomes, not over intents. The attempt counts as started only when the provider accepted a turn: a `turn.accepted` event or the provider's own `turn.started`. A startup still marked `beforeSpawn`, a runner that spawned but was never admitted, and a `turn.start` the provider did not accept are not charged. Progress means that an accepted turn then completed work: a tool execution or a completed item other than a usage report. An accepted turn with only usage, a failure, or no events is charged, so a resume that fails each time still uses up the budget. The first restart judges the original execution. Each later restart claim records the run's event-log position, and the next claim judges only the attempt recorded after it; a normal retry in between starts a new attempt (at its `native.process_start_requested`), so earlier work does not count for it. A reattachment adopts a provider that already started, so for it only progress counts. A resume that launches a new runner and that the controller died before starting used no provider work, so the next claim replaces it and the attempt ends at the attempt that resume was to run as. Uncharged restarts stop after 12 controller generations, so a crash loop that never starts the provider, or that makes progress and then crashes the controller each time, is still bounded. Legacy runs follow the same rule: a preparation interrupted before provider work started (`providerWorkStarted: false`) is retried in its own `interrupted_preparation` lane, which never spends the failure retry budget and is bounded at 12 retries. This holds for a hard kill as well as a graceful drain: once the killed controller's recorded process is proven gone, restart recovery fails the run as `process_lost` with the bootstrap certificate and schedules it in that lane. A run saved by an older release without a controller process stamp cannot be proven and stays in the charged lane. Exact-checkpoint resumes retain the 30-second delay. Replacement scheduling and predecessor lineage commit together, with one successor per predecessor and admission through the normal task locks, authorization, pause, approval, and budget gates. A due failed remote retry can retain its provider PID after heartbeat completion diff --git a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts index 134c048e310..8ccefae294d 100644 --- a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts +++ b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts @@ -32,7 +32,7 @@ import { WORKSPACE, } from "../drivers/codex/codex-app-server-driver.test-support.js"; import { createNativeSessionBackend } from "../index.js"; -import { PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE } from "../contracts/harness-driver.js"; +import { NativeRunnerResumeStateUnavailableError, PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE } from "../contracts/harness-driver.js"; import { createCodexNativeSessionBackend, createRunnerdNativeSessionBackend } from "./codex-native-backend.js"; import { createOpenCodeNativeSessionBackend } from "./opencode-native-backend.js"; @@ -453,6 +453,55 @@ describe("native backend factory", () => { expect(factory).not.toHaveBeenCalled(); }); + // Staging class P ("PRP provider resume state is unavailable"): the previous + // run's result was accepted but its harness backup failed to save, and its + // per-turn sandbox was destroyed. The follow-up's new sandbox holds no Runner + // control-plane state for the saved session, so every resume reads the same + // empty state. That failure was untyped, so a governed-wait or same-session + // checkpoint ended in a generic interruption, and each new message resumed + // the same session and failed again. + describe("a Runner that has no saved state for the session", () => { + function statelessRecovery(input: NativeExecutionInputV1) { + const transport = new FakeCodexTransport(); + transport.rejectMethods.set("initialize", new NativeRunnerResumeStateUnavailableError()); + const backend = createNativeSessionBackend(input, { + codexTransportFactory: () => transport, + environment: { ...process.env, PAPERCLIP_WORKSPACE_CWD: WORKSPACE }, + }); + const snapshot = { + schema: "paperclip.native-session.v1", backendKind: "codex_app_server", driverKind: "codex_app_server", + sessionId: transport.threadId, providerSessionId: transport.providerSessionId, workingDirectory: WORKSPACE, + identity: { runId: "run", sessionId: "session", companyId: "company", issueId: "issue", agentId: "agent" }, + activeTurnId: null, terminalTurns: [], pendingRuntimeRequests: [], lastCursor: null, + }; + return { backend, snapshot }; + } + + it.each([ + ["Codex", execution()], + ["OpenCode", opencodeExecution()], + ["ACPX Claude", acpxExecution("claude")], + ])("reports a %s session with nothing in flight as provider state incompatible", async (_label, input) => { + const { backend, snapshot } = statelessRecovery(input); + await expect(backend.recoverSession!(snapshot as never, { signal: new AbortController().signal })) + .resolves.toEqual({ + recovered: false, + reason: expect.stringContaining("PRP provider resume state is unavailable"), + failureClass: PROVIDER_STATE_INCOMPATIBLE, + }); + }); + + it.each([ + ["an active turn", { activeTurnId: "turn-in-flight" }], + ["a pending runtime request", { pendingRuntimeRequests: [{ requestId: "request-1" }] }], + ])("leaves a session that holds %s unclassified", async (_label, inFlight) => { + const { backend, snapshot } = statelessRecovery(acpxExecution("claude")); + const recovered = await backend.recoverSession!({ ...snapshot, ...inFlight } as never, { signal: new AbortController().signal }); + expect(recovered).toMatchObject({ recovered: false, reason: expect.stringContaining("PRP provider resume state is unavailable") }); + expect(recovered).not.toHaveProperty("failureClass"); + }); + }); + it("names the agent generically when a remote Claude session opens outside its workspace", async () => { const { factory, backend } = movedRootRecovery(acpxExecution("claude")); const failure = await backend.openSession({ diff --git a/packages/paperclip-runner/src/contracts/harness-driver.ts b/packages/paperclip-runner/src/contracts/harness-driver.ts index 406523d3b5f..b8903443c8c 100644 --- a/packages/paperclip-runner/src/contracts/harness-driver.ts +++ b/packages/paperclip-runner/src/contracts/harness-driver.ts @@ -532,6 +532,25 @@ export class NativeRunnerSourceReconciliationRequiredError extends Error { } } +/** The Runner keeps no control-plane state for the saved session: none is + * live and no archived authority epoch matches it. A new sandbox whose + * harness backup was never saved has nothing to resume, and recovering again + * reads the same empty state. The driver classifies it only for a session + * with no turn or runtime request in flight. */ +export class NativeRunnerResumeStateUnavailableError extends Error { + readonly code = "native_runner_resume_state_unavailable"; + constructor() { + super("PRP provider resume state is unavailable"); + this.name = "NativeRunnerResumeStateUnavailableError"; + } +} + +export function isRunnerResumeStateUnavailable(error: unknown, depth = 0): boolean { + if (!error || typeof error !== "object" || depth > 5) return false; + if (error instanceof NativeRunnerResumeStateUnavailableError) return true; + return isRunnerResumeStateUnavailable((error as { cause?: unknown }).cause, depth + 1); +} + export interface HarnessSessionRecoveryResult { recovered: boolean; session?: HarnessSession; diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts index a006348de21..834fdf100e8 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts @@ -20,7 +20,7 @@ import type { PersistedHarnessTurnTerminal, } from "../../contracts/harness-driver.js"; import { NativeSessionProtocolIntegrityError, nativeRestartInterruptedTurnId } from "../../contracts/native-session-backend.js"; -import { HarnessReconciliationError, PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE, runnerRecoveryFailureClass } from "../../contracts/harness-driver.js"; +import { HarnessReconciliationError, isRunnerResumeStateUnavailable, PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE, runnerRecoveryFailureClass } from "../../contracts/harness-driver.js"; import { CODEX_CODEX_PROTOCOL_VERSION, CODEX_SKILLLESS_BASE_INSTRUCTIONS, @@ -127,6 +127,18 @@ function bootstrapCancellation( }; } + +/** A saved turn or runtime request whose outcome is unknown. A crash can save a + * turn's terminal record before clearing its active marker; that turn finished + * and is not in flight. */ +function persistedSessionInFlight(snapshot: PersistedHarnessSession): boolean { + const activeTurnIsTerminal = (snapshot.terminalTurns ?? []).some( + (terminal) => terminal.turnId === snapshot.activeTurnId, + ); + return (Boolean(snapshot.activeTurnId) && !activeTurnIsTerminal) + || Boolean(snapshot.pendingRuntimeRequests?.length); +} + export class CodexAppServerDriver implements HarnessDriver { readonly #options: CodexAppServerDriverOptions; readonly #caps: CodexCapabilities; @@ -411,14 +423,7 @@ export class CodexAppServerDriver implements HarnessDriver { this.#options.workingDirectoryAuthority === "remote_runner" && remoteRunnerWorkingDirectoryMoved(snapshot.workingDirectory, this.#options.environment) ) { - // A crash can save a turn's terminal record before clearing its active - // marker; that turn finished and is not in flight. - const activeTurnIsTerminal = (snapshot.terminalTurns ?? []).some( - (terminal) => terminal.turnId === snapshot.activeTurnId, - ); - const inFlight = (Boolean(snapshot.activeTurnId) && !activeTurnIsTerminal) - || Boolean(snapshot.pendingRuntimeRequests?.length); - return inFlight + return persistedSessionInFlight(snapshot) ? { recovered: false, reason: "persisted session working directory is not the assigned remote workspace, and a provider turn or runtime request was in flight", @@ -764,7 +769,13 @@ export class CodexAppServerDriver implements HarnessDriver { await cancellation.close().catch(() => {}); if (error instanceof NativeSessionProtocolIntegrityError) throw error; if (options.signal.aborted) options.signal.throwIfAborted(); - const failureClass = runnerRecoveryFailureClass(error); + // A Runner with no saved control-plane state for this session can never + // resume it here. With nothing in flight, the runtime's recovery policy + // decides, as for a moved workspace root. An in-flight session keeps the + // unclassified failure. + const failureClass = runnerRecoveryFailureClass(error) + ?? (isRunnerResumeStateUnavailable(error) && !persistedSessionInFlight(snapshot) + ? PROVIDER_STATE_INCOMPATIBLE : undefined); return { recovered: false, reason: redactCodexDiagnostic(String(error)), diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-cold-restore.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-cold-restore.test.ts index d7598b004fa..ae7c3859ffa 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport-cold-restore.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-cold-restore.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; import { createCapabilityRunnerdCodexTransport } from "./runnerd-codex-transport.js"; +import { isRunnerResumeStateUnavailable, NativeRunnerResumeStateUnavailableError } from "../contracts/harness-driver.js"; import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js"; it.each(["restore", "refuse", "foreign-state"] as const)( @@ -105,3 +106,34 @@ it.each(["restore", "refuse", "foreign-state"] as const)( }, 30_000, ); + +// Staging class P: a follow-up's new sandbox holds no Runner control-plane +// state and no archived authority epoch for the saved session. The refusal is +// typed so the driver can tell the runtime the saved state cannot resume here. +it.each(["local", "external"] as const)("names a resume that finds no saved %s Runner state", async (placement) => { + const root = await mkdtemp(join(tmpdir(), "runnerd-resume-state-absent-")); + const prepare = vi.fn(async () => {}); + try { + const resumed = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: fakeCodex, + codexArgs: fakeCodexArgs(root), + stateDirectory: root, + prpIdentity: { runnerInstanceId: "absent-runner", environmentLeaseId: "absent-lease", runId: "follow-up-run", + normalizedSessionId: "absent-session", turnId: "follow-up-turn", itemId: "follow-up-item" }, + resumeProviderSession: { driverSessionId: "thread-saved", providerSessionId: "provider-saved" }, + ...(placement === "external" ? { + readRunnerState: vi.fn(async () => { throw new Error("no runner state"); }), + prepareExternalRunnerState: prepare, + archiveExternalRunnerState: vi.fn(async () => { throw new Error("nothing to archive"); }), + } : {}), + }); + const failure = await resumed.transport.request("thread/read", {}).then(() => null, (error: unknown) => error); + expect(failure).toBeInstanceOf(NativeRunnerResumeStateUnavailableError); + expect(isRunnerResumeStateUnavailable(failure)).toBe(true); + expect((failure as Error).message).toBe("PRP provider resume state is unavailable"); + await resumed.transport.close().catch(() => {}); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 03dcf56ff2d..e28ca0fa2c1 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -70,7 +70,7 @@ import type { HarnessRuntimeRequestResolution, PersistedHarnessProviderIdentity, } from "../contracts/harness-driver.js"; -import { NativeRunnerSourceReconciliationRequiredError } from "../contracts/harness-driver.js"; +import { NativeRunnerResumeStateUnavailableError, NativeRunnerSourceReconciliationRequiredError } from "../contracts/harness-driver.js"; import { DurablePrpControlPlane, inspectStagedRunAttachment, @@ -6498,7 +6498,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { let rotationSource: Record | null = null; if (controlPlaneState === null) { if (!supportsColdRotation) { - throw new Error("PRP provider resume state is unavailable"); + throw new NativeRunnerResumeStateUnavailableError(); } // An interrupted rotation leaves only its archive marker. rotationSource = committedRotationSource ?? latestArchivedControlPlaneState( @@ -6506,7 +6506,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { desiredIdentity, ); if (!rotationSource) { - throw new Error("PRP provider resume state is unavailable"); + throw new NativeRunnerResumeStateUnavailableError(); } } else if (!exactAuthority && warmRecovery === null) { if (!supportsColdRotation) { @@ -6540,7 +6540,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } // A missing control plane either rotated from its archive above or threw. if (controlPlaneState === null) { - throw new Error("PRP provider resume state is unavailable"); + throw new NativeRunnerResumeStateUnavailableError(); } const runnerBinaryPath = this.options.runnerBinary ?? (this.options.prepareLaunch ? "paperclip-runnerd" : defaultCapabilityRunnerdBinary()); diff --git a/server/src/services/workspace-recovery-retry-copyback.test.ts b/server/src/services/workspace-recovery-retry-copyback.test.ts index cdc45a308ef..39bbad5f77b 100644 --- a/server/src/services/workspace-recovery-retry-copyback.test.ts +++ b/server/src/services/workspace-recovery-retry-copyback.test.ts @@ -166,6 +166,10 @@ describe("automatic retained workspace recovery", () => { { title: "its provider turn ended without an observed provider terminal", change: "unproven" }, { title: "the source was a system wake", change: "system" }, { title: "the failure was not a lost runner or allocation", change: "error" }, + // Staging class P: the new sandbox had no Runner state to resume the saved + // provider session. The Runner now names it, so the run ends with the + // permanent code and Retry continues in a fresh provider session. + { title: "the Runner had no saved state to resume the provider session", change: "unrestorable" }, ])("does not continue automatically when $title, and offers a Retry that works on first use", async ({ change }) => { const f = await restartAllocationLostSource(change === "turn" ? "in_flight" : change === "unproven" ? "unproven" : "none"); if (change === "system") await db.update(agentWakeupRequests).set({ requestedByActorType: "system", requestedByActorId: null, @@ -173,6 +177,9 @@ describe("automatic retained workspace recovery", () => { if (change === "system") await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeReason: "issue_children_completed" } }) .where(eq(heartbeatRuns.id, f.runId)); if (change === "error") await db.update(heartbeatRuns).set({ error: "native_provider_terminal_failed" }).where(eq(heartbeatRuns.id, f.runId)); + if (change === "unrestorable") await db.update(heartbeatRuns).set({ errorCode: "native_provider_state_incompatible", + error: "native_session_recovery_failed: NativeRunnerResumeStateUnavailableError: PRP provider resume state is unavailable" }) + .where(eq(heartbeatRuns.id, f.runId)); const service = heartbeatService(db, { environmentRuntime: f.environmentRuntime }); await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }); expect(await requestRestartInterruptedTurnRetry(db, f.claim)).toMatchObject({ requested: false, @@ -195,7 +202,8 @@ describe("automatic retained workspace recovery", () => { await service.resumeTaskRetry(f.companyId, receipt.requestId!); const successors = await queuedSuccessors(f.companyId); expect(successors).toHaveLength(1); - expect(successors[0].contextSnapshot).toMatchObject({ previousRunId: f.runId, taskRetryRequestId: receipt.requestId }); + expect(successors[0].contextSnapshot).toMatchObject({ previousRunId: f.runId, taskRetryRequestId: receipt.requestId, + forceFreshSession: true }); }, 30_000); // S54: the automatic Retry's own run then lost its runner too. Saved-work From 1ac8b6a7118fa729b50200522bda996e789a297a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:31:50 -0600 Subject: [PATCH 2/5] fix(workspaces): stop re-saving a retained sandbox whose disk is still full (#20758) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - After a native run on a remote sandbox, Paperclip saves the sandbox workspace back to durable storage. When that save fails, saved-work recovery saves the files again from the retained sandbox, with no provider turn. > - A staging census of the last 48 hours (`doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md`, class F) found saves that failed because the sandbox disk was full. > - #20678 already ends finalization at the first full-disk copy-back and hands the work to saved-work recovery. Recovery then deletes inactive tool caches that it can prove safe, and saves again. > - When that save still found the disk full, recovery recorded a transient `export_interrupted` failure with cause `provider_error`. It then saved again on its automatic schedule (up to 5 retries in 30 minutes). Nothing frees space in a stopped, retained sandbox between those attempts, so each attempt failed the same way. The task showed "Recovering saved work…" and no Retry while this went on. > - This pull request ends the recovery generation at the first such failure with a named cause, `sandbox_disk_full`, and hands it to the board with a Retry. > - The benefit is that the task does not spend 30 minutes on saves that cannot succeed, the user sees why, and one Retry saves the files and starts one run. ## Linked Issues or Issue Description Refs #20678, #20695 (named sandbox disk-full failures for copy-back and restore) **What happened?** A native run on a remote sandbox finished, and its workspace copy-back hit a full sandbox disk. Finalization handed the task to saved-work recovery (#20678). Recovery's own save also hit the full disk. Recovery classified this as `export_interrupted` / `retry_transient` with cause `provider_error`, so it scheduled more automatic saves of the same sandbox. Each one failed the same way. The task showed "Recovering saved work…" with no Retry until the 30-minute window ran out. **Expected behavior** A save that still finds the disk full after the safe cache cleanup is not repeated automatically. The recovery ends at once with the cause `sandbox_disk_full`, and the board gets a Retry. The workspace keeps its previous saved version, and the run's unsaved files stay in the retained sandbox. One Retry saves the files once there is room and starts exactly one run. **Steps to reproduce** 1. Give a native run an accepted result whose copy-back failed (`native_workspace_sync_out_retry_exhausted`). 2. Make every save from its retained sandbox fail with `remote_workspace_sandbox_disk_full`, with no inactive tool cache to delete. 3. Run saved-work recovery. Before this change, it records `export_interrupted` with cause `provider_error` and schedules another save. ## What Changed - `workspace-recovery.ts`: a save that fails with `remote_workspace_sandbox_disk_full` after a confirmed cache cleanup (or with nothing to clean up) now fails the generation with `export_interrupted`, retry class `user_action_required`, and cause `{ label: "sandbox_disk_full", code: "ENOSPC" }`. That class is not retried automatically, and it is not a permanent-source class, so recovery never falls back to the last save and never drops the run's unsaved files. The next sweep hands the hold to the board. - A cleanup whose outcome is unknown (lost acknowledgement, interrupted journal) keeps the existing scheduled retry, because its journal resumes on the next attempt and can still free space. - `retained-provider-cache.ts`: `reclaimInactiveNativeProviderCache` returns `{ changed, confirmed }` instead of a boolean, so the caller can tell "nothing to delete" from "outcome unknown". It has one caller. - `system-recovery-state.ts`: the board handoff text for this cause says that the sandbox disk is full, that Paperclip deletes only inactive tool caches it can prove safe, and that Retry saves the files again. - New `workspace-recovery-disk-full.test.ts` covers the whole path: one failed attempt, no further automatic saves, the board handoff text, the previous saved version unchanged, the agent's files still in the sandbox, no unfinished in-sandbox capture attempt, a Retry offered in the task presentation and blocker, `POST /issues/:id/retry` accepted (202), the files saved after Retry, and exactly one run started (also with a replayed dispatch). - `doc/execution-semantics.md`: documents the behavior. ## Verification - Red on master: `cd server && npx vitest run src/services/workspace-recovery-disk-full.test.ts` fails. The recovery state is `scheduled` with cause `provider_error` instead of `exhausted` with cause `sandbox_disk_full`. - Green on this branch: the same command passes. - Related suites pass: `workspace-recovery-retry-copyback.test.ts` (79 tests, including the 8 cache-cleanup resume tests that need the scheduled retry after an unconfirmed cleanup), `system-recovery-state.test.ts`, `workspace-recovery-capture-policy.test.ts`, `workspace-recovery-fallback.test.ts`, `workspace-recovery-stop-proof.test.ts`, `native-run-finalizer-telemetry.test.ts` (167 tests in all). - `npx tsc --noEmit -p server/tsconfig.json` is clean. - `pnpm verify`: exit 2 (broader verification required), because `doc/execution-semantics.md` is a global CI input. The focused checks above pass. Required CI supplies the broad coverage. ## Risks - Low. The change touches only the saved-work recovery path when its save fails with the exact full-disk message. - Upgrade-safe: the failure code (`export_interrupted`), the retry class (`user_action_required`) and the cause label all pass the earlier release's recovery schema. An earlier release that reads this state shows its generic "Retry to try again" text. - A full-disk failure no longer gets automatic retries in its 30-minute window. If space became free by itself in that window, the user must now press Retry. Nothing in a stopped, retained sandbox frees space by itself, so this is expected to be rare. - No Runner (Rust) change, so no new sandbox image is needed. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file editing, test execution) and extended reasoning. ## 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 --- doc/execution-semantics.md | 11 +- .../native-runtime/retained-provider-cache.ts | 15 +-- server/src/services/system-recovery-state.ts | 4 + .../workspace-recovery-disk-full.test.ts | 100 ++++++++++++++++++ server/src/services/workspace-recovery.ts | 18 +++- 5 files changed, 137 insertions(+), 11 deletions(-) create mode 100644 server/src/services/workspace-recovery-disk-full.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 5f4951a9620..5df3d2d2b83 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -4648,7 +4648,16 @@ recovery then reclaims the retained sandbox's inactive provider cache and saves files again with no provider turn. The export Retry stays available. A read-only fallback that only lost its connection (a closed transport, a provider 5xx or rate limit, or a sandbox state change) reports its own cause instead, and finalization -keeps its bounded retry for it. +keeps its bounded retry for it. When saved-work recovery's own save still finds the +disk full after a confirmed reclaim, or with nothing to reclaim, the recovery +generation ends at once as +`export_interrupted` with cause `sandbox_disk_full` (retry class +`user_action_required`) and goes to the board. It is not retried on the automatic +schedule, and it never falls back to the last save, so the run's unsaved files stay +in the retained sandbox and the workspace keeps its previous saved version. The +board's Retry saves again; once the save succeeds, the accepted Retry starts one run. +A reclaim whose outcome is unknown keeps the scheduled retry, because its journal +resumes on the next attempt and can still free space. Native assigned app tools save governed responses above 500,000 encoded bytes before returning a bounded reference through PRP. `read_tool_result` retrieves the saved JSON in diff --git a/server/src/services/native-runtime/retained-provider-cache.ts b/server/src/services/native-runtime/retained-provider-cache.ts index eccd1efcba4..2386ebcbf1f 100644 --- a/server/src/services/native-runtime/retained-provider-cache.ts +++ b/server/src/services/native-runtime/retained-provider-cache.ts @@ -162,10 +162,13 @@ function readInventory(value: unknown, runId: string, expected: string): Invento return parsed; } +export type NativeProviderCacheReclaim = { changed: boolean; confirmed: boolean }; + export async function reclaimInactiveNativeProviderCache(input: { db: Db; companyId: string; issueId: string; runId: string; workspaceId: string; target: RemoteWorkspaceTarget; assertOwned: () => Promise; -}): Promise { +}): Promise { + const nothing = { changed: false, confirmed: true } as const; await input.assertOwned(); const [source] = await input.db.select({ run: heartbeatRuns, coordinator: nativeRunFinalizations }) .from(heartbeatRuns).innerJoin(nativeRunFinalizations, and(eq(nativeRunFinalizations.companyId, heartbeatRuns.companyId), @@ -175,9 +178,9 @@ export async function reclaimInactiveNativeProviderCache(input: { if (!source || source.run.status !== "failed" || source.run.runtimeMode !== "native" || (source.run.nativeIssueId ?? source.run.issueId ?? source.run.contextSnapshot?.issueId) !== input.issueId || source.coordinator.phase !== "terminal_failure" || source.coordinator.leaseOwner !== null - || record(source.coordinator.failureDetail).recoverable === true) return false; + || record(source.coordinator.failureDetail).recoverable === true) return nothing; const expected = verifiedCacheDigest(source.run, input.workspaceId, input.target); - if (!expected) return false; + if (!expected) return nothing; const scope = and(eq(workspaceOperations.companyId, input.companyId), eq(workspaceOperations.issueId, input.issueId), eq(workspaceOperations.heartbeatRunId, input.runId), eq(workspaceOperations.executionWorkspaceId, input.workspaceId)); const execute = async (mode: "inventory" | "stage" | "reclaim", @@ -200,7 +203,7 @@ export async function reclaimInactiveNativeProviderCache(input: { .orderBy(asc(workspaceOperations.startedAt), asc(workspaceOperations.id)).limit(1); if (!prepared) { const inventory = readInventory(await execute("inventory"), input.runId, expected); - if (!inventory.targets.length) return false; + if (!inventory.targets.length) return nothing; await input.assertOwned(); [prepared] = await withDedicatedDbConnection(input.db, journal => journal.transaction(async tx => { await tx.execute(sql`select set_config('statement_timeout', '10000', true), set_config('lock_timeout', '2000', true)`); @@ -222,7 +225,7 @@ export async function reclaimInactiveNativeProviderCache(input: { eq(workspaceOperations.phase, "native_provider_cache_reclaim"), eq(workspaceOperations.status, "succeeded"), sql`${workspaceOperations.metadata}->>'preparationOperationId' = ${preparationOperationId}`, sql`${workspaceOperations.metadata}->>'outcome' = 'evicted'`)).limit(1); - if (completed) return false; + if (completed) return nothing; let staged: Staged = []; if (inventory.targets.some(target => target.generation.startsWith("c:"))) { if (prepared.metadata.staged === undefined) { @@ -257,5 +260,5 @@ export async function reclaimInactiveNativeProviderCache(input: { await input.db.insert(workspaceOperations).values({ companyId: input.companyId, issueId: input.issueId, heartbeatRunId: input.runId, executionWorkspaceId: input.workspaceId, phase: "native_provider_cache_reclaim", status: confirmed ? "succeeded" : "failed", startedAt, finishedAt: new Date(), metadata }); - return changed; + return { changed, confirmed }; } diff --git a/server/src/services/system-recovery-state.ts b/server/src/services/system-recovery-state.ts index e5492404584..ffe8e22dfa7 100644 --- a/server/src/services/system-recovery-state.ts +++ b/server/src/services/system-recovery-state.ts @@ -194,6 +194,10 @@ export function exhaustedSystemRecoveryAction(state: SystemRecoveryState, eviden return "Recovery of saved work is waiting to confirm that the previous run stopped. " + "Paperclip tries again automatically, and the agent will not repeat its work."; const cause = state.failure?.cause ? `, cause: ${state.failure.cause.label}` : ""; + if (state.failure?.cause?.label === "sandbox_disk_full") + return "Saving the agent's files stopped because the sandbox disk is full. Paperclip deletes only inactive tool " + + "caches it can prove safe, and that did not free enough space. Automatic recovery does not repeat a save that fails the same way. " + + "Retry saves the files again. The agent's result is kept, and the agent will not repeat its work."; if (isDeterministicRecoveryRefusal(state)) { const code = state.failure!.code; // Never promise a release. A retained-file hold the fallback settles diff --git a/server/src/services/workspace-recovery-disk-full.test.ts b/server/src/services/workspace-recovery-disk-full.test.ts new file mode 100644 index 00000000000..e954a781c75 --- /dev/null +++ b/server/src/services/workspace-recovery-disk-full.test.ts @@ -0,0 +1,100 @@ +import { randomUUID } from "node:crypto"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import request from "supertest"; +import { and, eq } from "drizzle-orm"; +import { agentWakeupRequests, executionWorkspaces, heartbeatRuns, issues } from "@paperclipai/db"; +import { heartbeatService } from "./heartbeat.js"; +import { describe, expect, it, vi } from "vitest"; +import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; +import { readSystemRecovery } from "./system-recovery-state.js"; +import { recoverRetainedWorkspace } from "./workspace-recovery.js"; +import { readWorkspaceRecovery } from "./workspace-recovery-receipt.js"; +import { REMOTE_WORKSPACE_SANDBOX_DISK_FULL } from "./remote-workspace-transport.js"; +import { getExecutionBlocker } from "./execution-blocker.js"; +import { taskInterruptionPresentation } from "./task-interruption-presentation.js"; +import { createSavedWorkspaceLoader, readRemoteWorkspaceAuthority } from "./remote-workspaces.js"; +import { useWorkspaceRecoveryFixture, acceptedRemoteExport, action, db, receiptOnlyRecoveryApp } from "./__tests__/workspace-recovery-fixture.js"; +const targets = vi.hoisted(() => new Map()); +vi.mock("./environment-execution-target.js", async importOriginal => { + const actual = await importOriginal(); + return { ...actual, resolveEnvironmentExecutionTarget: async (input: Parameters[0]) => + (input.leaseId ? targets.get(input.leaseId) : undefined) ?? actual.resolveEnvironmentExecutionTarget(input) }; +}); + +describe("saved-work recovery on a full sandbox disk", () => { + useWorkspaceRecoveryFixture(targets); + + it("ends recovery at the first full-disk save with a named cause and a Retry that saves once there is room", async () => { + const f = await acceptedRemoteExport(); + const target = targets.get(f.lease.id)!, syncOut = target.runner!.syncOut!; + let full = true, saves = 0; + target.runner!.syncOut = async operations => { + saves++; + if (full) throw new Error(REMOTE_WORKSPACE_SANDBOX_DISK_FULL); + return syncOut(operations); + }; + const workspaceBefore = (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)))[0]; + + await recoverRetainedWorkspace(f.input); + const failed = readSystemRecovery((await action(f.actionId)).evidence); + expect(failed).toMatchObject({ state: "exhausted", nextAttemptAt: null, attempts: 1, failure: { + code: "export_interrupted", retryClass: "user_action_required", + cause: { label: "sandbox_disk_full", code: "ENOSPC", status: null } } }); + const savesAtFailure = saves; + expect(savesAtFailure).toBeGreaterThan(0); + + await recoverRetainedWorkspace(f.input); + await recoverRetainedWorkspace(f.input); + expect(saves).toBe(savesAtFailure); + const handedOff = await action(f.actionId); + expect(handedOff).toMatchObject({ status: "active", ownerType: "board" }); + expect(handedOff.nextAction).toMatch(/sandbox disk is full/); + expect(handedOff.nextAction).toMatch(/Retry saves the files again/); + + const workspaceAfter = (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)))[0]; + expect(readRemoteWorkspaceAuthority(workspaceAfter.metadata)?.snapshotId) + .toBe(readRemoteWorkspaceAuthority(workspaceBefore.metadata)?.snapshotId ?? null); + expect(await readFile(path.join(f.remote, "saved.txt"), "utf8")).toBe("finished work\n"); + const staging = path.join(f.remote, ".paperclip-runtime", "workspace-snapshots"); + for (const attempt of await readdir(staging).catch(() => [] as string[])) + expect((await readdir(path.join(staging, attempt))).filter(name => name.startsWith("capture-"))).toEqual([]); + + const issue = (await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]; + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ canRetry: true, observedRunId: f.runId }); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ runId: f.runId, + workspaceRecovery: { canRetry: true } }); + const runsBefore = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId)); + + full = false; + const app = receiptOnlyRecoveryApp(); + const receipt = (await request(app).post(`/api/issues/${f.issueId}/retry`) + .send({ observedRunId: f.runId, idempotencyKey: randomUUID() }).expect(202)).body; + expect(receipt).toMatchObject({ accepted: true, observedRunId: f.runId }); + await recoverRetainedWorkspace(f.input); + const recovered = await action(f.actionId); + expect(readWorkspaceRecovery(recovered.evidence)?.status).toBe("recovered"); + expect(readSystemRecovery(recovered.evidence)?.preservationOperationIds).toHaveLength(1); + const authority = readRemoteWorkspaceAuthority((await db.select().from(executionWorkspaces) + .where(eq(executionWorkspaces.id, f.workspaceId)))[0].metadata)!; + const saved = await createSavedWorkspaceLoader(db)({ companyId: f.companyId, workspaceId: f.workspaceId, + snapshotId: authority.snapshotId! }); + try { expect(await readFile(path.join(saved.root, "saved.txt"), "utf8")).toBe("finished work\n"); } + finally { await saved.cleanup(); } + const savesAfterRetry = saves; + await recoverRetainedWorkspace(f.input); + expect(saves).toBe(savesAfterRetry); + expect(await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))) + .toEqual(runsBefore); + const heartbeat = heartbeatService(db); + await Promise.all([heartbeat.resumeTaskRetry(f.companyId, receipt.requestId), + heartbeat.resumeTaskRetry(f.companyId, receipt.requestId)]); + await heartbeat.resumeTaskRetry(f.companyId, receipt.requestId); + const successors = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))) + .filter(row => row.id !== f.runId); + expect(successors).toHaveLength(1); + expect(successors[0].contextSnapshot).toMatchObject({ previousRunId: f.runId, taskRetryRequestId: receipt.requestId }); + expect(await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId), + eq(agentWakeupRequests.idempotencyKey, `task-retry-dispatch:${receipt.requestId}`)))).toHaveLength(1); + }, 60_000); +}); diff --git a/server/src/services/workspace-recovery.ts b/server/src/services/workspace-recovery.ts index 2bc45c172ab..31177ac4c57 100644 --- a/server/src/services/workspace-recovery.ts +++ b/server/src/services/workspace-recovery.ts @@ -44,6 +44,8 @@ import { settleRecoveredWorkspaceRestoreHolds } from "./workspace-restore-hold-s const exportCauses = ["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"]; const terminal = ["failed", "interrupted", "timed_out", "cancelled", "succeeded"]; const sandboxDiskFull = /No space left on device|Disk quota exceeded/i; +export const SANDBOX_DISK_FULL_RECOVERY_CAUSE = { label: "sandbox_disk_full", code: "ENOSPC", status: null } as const; +const isSandboxDiskFullSave = (error: unknown) => error instanceof Error && error.message === REMOTE_WORKSPACE_SANDBOX_DISK_FULL; type Source = { companyId: string; issueId: string; runId: string; actionId: string }; type StopEvidenceSource = Omit & { actionId?: string }; @@ -258,6 +260,7 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,attemptId}' = ${reserved.attemptId}`)); }; let observing = Promise.resolve(); + let cacheReclaimUnconfirmed = false; const observer = setInterval(() => { observing = observing.then(observeActive).catch(() => undefined); }, 15_000); try { await observeActive(); @@ -368,13 +371,18 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ let saved: Awaited>; try { saved = await save(); } catch (error) { - if (!(error instanceof Error) || error.message !== REMOTE_WORKSPACE_SANDBOX_DISK_FULL) throw error; + if (!isSandboxDiskFullSave(error)) throw error; let reclaimed = false; try { - reclaimed = await reclaimInactiveNativeProviderCache({ db, companyId: input.companyId, + const reclaim = await reclaimInactiveNativeProviderCache({ db, companyId: input.companyId, issueId: input.issueId, runId: input.runId, workspaceId: workspace.id, target, assertOwned: ownership.assertHeld }); - } catch { logger.warn({ runId: input.runId }, "Retained provider cache cleanup could not be confirmed"); } + reclaimed = reclaim.changed; + cacheReclaimUnconfirmed = !reclaim.confirmed; + } catch { + cacheReclaimUnconfirmed = true; + logger.warn({ runId: input.runId }, "Retained provider cache cleanup could not be confirmed"); + } if (!reclaimed) throw error; await ownership.assertHeld(); saved = await save(); @@ -471,7 +479,9 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ return; } const classification = classifyNativeWorkspaceFailure(error); + const diskFull = !(error instanceof SystemRecoveryFailure) && !cacheReclaimUnconfirmed && isSandboxDiskFullSave(error); const failure = error instanceof SystemRecoveryFailure ? error + : diskFull ? new SystemRecoveryFailure("export_interrupted", "user_action_required") : classifyWorkspaceRestoreFailure(error) === "restore_invalid_metadata" ? new SystemRecoveryFailure("snapshot_verification_failed", "service_required") : classification.code === "workspace_sync_out_unsafe_archive" @@ -485,7 +495,7 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ // A classified failure already names its subsystem. const generic = !(error instanceof SystemRecoveryFailure) && failure.retryClass === "retry_transient" && (failure.code === "provider_unavailable" || failure.code === "export_interrupted"); - const cause = generic ? sandboxProviderFailureLabel(error) : undefined; + const cause = diskFull ? { ...SANDBOX_DISK_FULL_RECOVERY_CAUSE } : generic ? sandboxProviderFailureLabel(error) : undefined; const failed = failSystemRecovery(current!, failure, { ...(typeof retryAfterAt === "number" && Number.isFinite(retryAfterAt) ? { retryAfterAt } : {}), ...(cause ? { cause } : {}), From f125b823f4c7c37680ffa788ceee1ab0bc8f44b1 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 01:42:29 -0600 Subject: [PATCH 3/5] fix(recovery): release a parent's Retry once a done child's recovered files are saved (#20728) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A parent task waits for its done child tasks to save their workspace files before it runs again (the workspace-finalize barrier) > - "Recover saved files" saves the retained work of a done child and records a successful `workspace_finalize` > - That finalize row had no `execution_workspace_id`. The barrier reads finalize rows by the blocker's workspace, so it never saw the row > - The parent's saved Retry then waited forever with "Saving its files" on a child that had already saved its files > - This pull request lets the barrier accept the recovery's own finalize for the recovered task's finished operations of the same run. It does not make the recovery finalize a workspace-wide save > - The benefit is that recoveries work by themselves: the parent's dependency wait releases and its saved Retry starts on the next dependency pass, with no migration ## Linked Issues or Issue Description **What happened?** A parent task had three done children. One legacy child shared the parent's execution workspace. The operator pressed "Recover saved files" on that child. The recovery saved the files and marked the old run succeeded. The operator then pressed Retry on the parent. The server accepted the Retry, but the parent stayed on "Retry is waiting for a finished task this one depends on to save its files" for more than 15 minutes. `blockerAttention.pendingFinalizeBlockerIssueIds` named the recovered child. The child had no active recovery action and no execution blocker. The workspace was clean (`dirty: false`, `writerRunId: null`). The child's workspace operations showed the cause. The latest operation on the workspace was a succeeded `workspace_recovery`. The recovery's succeeded `workspace_finalize` existed, but with `execution_workspace_id = NULL`. Earlier finalize attempts of that run had failed. `pendingFinalizeBlockerCondition` only looks at operations on the blocker's workspace, so it found no successful finalize after the recovery. **Expected behavior** When "Recover saved files" saves a done child's work, the child must stop holding its dependents. The parent's saved Retry must start without another operator action. **Steps to reproduce** 1. Let a child task finish as `done` with a retained remote workspace whose finalize failed. 2. Run "Recover saved files" on the child, so recovery saves the remote workspace snapshot. 3. Block a parent task on the child. The parent can share the child's workspace. 4. Read the parent's dependency readiness. Before this fix it reports the child in `pendingFinalizeBlockerIssueIds` forever. **Paperclip version or commit** Seen on staging at `a46b9ac7`. Reproduced on `master` at `e039be9202`. ## What Changed - `server/src/services/issues.ts` (`pendingFinalizeBlockerCondition`): the blocker task's latest workspace operation is settled when a succeeded recovery finalize (`owningService: workspace_recovery`) from the same company, task, and run started at or after that operation finished. The operation must be finished (`succeeded`, `failed`, or `skipped`). The recovery finalize can have no workspace (all rows written so far) or this workspace. - The rule is scoped to the blocker task and its run. It does not change the workspace-wide `finalized_at`, so other tasks that share the workspace keep their own barrier. - `server/src/services/workspace-recovery-dependency-finalize.test.ts`: new regression tests that run the real remote "Recover saved files" path, make the child `done`, and block a parent that shares the child's workspace. - `doc/execution-semantics.md`: documents how the recovery finalize settles the dependency barrier. ## Verification - Red (unfixed `issues.ts`): `npx vitest run src/services/workspace-recovery-dependency-finalize.test.ts` fails 3 of 4 tests. The parent stays not ready with the recovered child in `pendingFinalizeBlockerIssueIds`. - Green (fixed): the same file passes 4 of 4 tests: - a real recovery releases the parent in `getDependencyReadiness` and in the issue list `blockerAttention`; - snapshot-fallback shape: the preservation receipt has no workspace and the child's latest operation is the run's failed finalize. The parent is released; - safety: a sibling task that started work on the shared workspace while the recovery waited for teardown still holds the parent; - safety: child work that starts after the recovery still holds the parent. - Focused suites pass: `src/__tests__/issues-service.test.ts`, `src/services/workspace-recovery-admission.test.ts`, `src/services/task-retry.test.ts`, `src/services/saved-bootstrap-continuation.test.ts`, `src/services/remote-workspace-recovery-receipt-fallback.test.ts`, `src/__tests__/issue-dependency-wakeups-routes.test.ts` (414 tests with the new file). - `pnpm verify` exits 2 (a doc change is a global CI input), so required CI supplies broad coverage. Server `tsc --noEmit` passes. ## Risks - Previous-release story: no persisted shape changes. Recovery finalize rows already saved (with no workspace) are read by the new rule. Affected parents become dependency-ready on the next read, with no migration or backfill. The deferred-receipt and dependency backstop passes then start the saved Retry. - The barrier keeps its protection. Unfinished operations, operations from another run, operations that start after the recovery finalize, and other tasks on a shared workspace still wait for their own save. - No schema change and no write-path change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, code search, test execution, read-only staging API inspection). ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/execution-semantics.md | 9 ++ server/src/services/issues.ts | 14 ++++ ...space-recovery-dependency-finalize.test.ts | 83 +++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 server/src/services/workspace-recovery-dependency-finalize.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 5df3d2d2b83..326a85c1687 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -235,6 +235,15 @@ Workspace readiness accepts a completed operation enclosed by a successful finalize from the same company, workspace, issue, and run. A nested snapshot that finishes before that finalize finishes does not leave a permanent wait. Unfinished operations and work after the finalize still require a later save. +Saved-work recovery ("Recover saved files") ends with its own successful +finalize for the recovered run. That finalize settles the task's finished +workspace operations from the same run that started before it, including on a +workspace that a legacy done child shares with its parent. So the dependents +of a recovered done child stop waiting, and a saved Retry starts on the next +dependency pass. Recovery finalizes already saved by earlier releases count, +with no migration. The recovery finalize never counts as a workspace-wide +save: another task that started work on a shared workspace while the recovery +waited for sandbox teardown still waits for its own save. Daytona file export can preserve an already captured workspace archive when the guarded download copy runs out of sandbox capacity. It removes partial copies, diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 565da8152da..b71f2dd7457 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -2606,6 +2606,20 @@ function pendingFinalizeBlockerCondition(companyId: string, issueId: SQL, worksp and owning_finalize.finished_at >= latest_blocker_operation.finished_at ) ) + and not ( + latest_blocker_operation.status in ('succeeded', 'failed', 'skipped') + and exists ( + select 1 from workspace_operations recovery_finalize + where recovery_finalize.company_id = ${companyId}::uuid + and recovery_finalize.issue_id = ${issueId} + and recovery_finalize.heartbeat_run_id = latest_blocker_operation.heartbeat_run_id + and recovery_finalize.phase = 'workspace_finalize' and recovery_finalize.status = 'succeeded' + and recovery_finalize.metadata->>'owningService' = 'workspace_recovery' + and (recovery_finalize.execution_workspace_id is null + or recovery_finalize.execution_workspace_id = ${workspaceId}) + and recovery_finalize.started_at >= coalesce(latest_blocker_operation.finished_at, latest_blocker_operation.started_at) + ) + ) )`; } diff --git a/server/src/services/workspace-recovery-dependency-finalize.test.ts b/server/src/services/workspace-recovery-dependency-finalize.test.ts new file mode 100644 index 00000000000..5f1210649db --- /dev/null +++ b/server/src/services/workspace-recovery-dependency-finalize.test.ts @@ -0,0 +1,83 @@ +import { and, eq } from "drizzle-orm"; +import { describe, expect, it, vi } from "vitest"; +import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; +import { issueRelations, issues, workspaceOperations } from "@paperclipai/db"; +import { issueService } from "./issues.js"; +import { recoverRetainedWorkspace } from "./workspace-recovery.js"; +import { readWorkspaceRecovery } from "./workspace-recovery-receipt.js"; +import { useWorkspaceRecoveryFixture, acceptedRemoteExport, action, db } from "./__tests__/workspace-recovery-fixture.js"; + +const targets = vi.hoisted(() => new Map()); +vi.mock("./environment-execution-target.js", async importOriginal => { + const actual = await importOriginal(); + return { ...actual, resolveEnvironmentExecutionTarget: async (input: Parameters[0]) => + (input.leaseId ? targets.get(input.leaseId) : undefined) ?? actual.resolveEnvironmentExecutionTarget(input) }; +}); + +describe("dependency readiness after a done child's work is recovered", () => { + useWorkspaceRecoveryFixture(targets); + + async function recoveredDoneChildWithParent() { + const f = await acceptedRemoteExport(); + await recoverRetainedWorkspace(f.input); + expect(readWorkspaceRecovery((await action(f.actionId)).evidence)?.status).toBe("recovered"); + const [child] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId)); + const [parent] = await db.insert(issues).values({ companyId: f.companyId, title: "Parent", + status: "blocked", priority: "medium", assigneeAgentId: child.assigneeAgentId, + executionWorkspaceId: f.workspaceId }).returning(); + await db.insert(issueRelations).values({ companyId: f.companyId, issueId: f.issueId, + relatedIssueId: parent.id, type: "blocks" }); + return { ...f, parentId: parent.id }; + } + + const recoveryFinalize = async (f: { companyId: string; runId: string }) => (await db.select().from(workspaceOperations).where(and( + eq(workspaceOperations.companyId, f.companyId), eq(workspaceOperations.heartbeatRunId, f.runId), + eq(workspaceOperations.phase, "workspace_finalize"), eq(workspaceOperations.status, "succeeded"))))[0]!; + const readiness = (id: string) => issueService(db).getDependencyReadiness(id); + + it("releases the parent once Recover saved files has saved a done child's work", async () => { + const f = await recoveredDoneChildWithParent(); + await expect(readiness(f.parentId)).resolves.toMatchObject({ + isDependencyReady: true, pendingFinalizeBlockerIssueIds: [], unresolvedBlockerIssueIds: [] }); + const listed = (await issueService(db).list(f.companyId, { status: "blocked" }) as Array<{ id: string; + blockerAttention?: { pendingFinalizeBlockerIssueIds?: string[] } | null }>).find(issue => issue.id === f.parentId); + expect(listed?.blockerAttention?.pendingFinalizeBlockerIssueIds ?? []).toEqual([]); + }, 30_000); + + it("releases the parent when the recovery saved through a snapshot without a workspace", async () => { + const f = await recoveredDoneChildWithParent(); + const finalize = await recoveryFinalize(f); + await db.update(workspaceOperations).set({ executionWorkspaceId: null }).where(and( + eq(workspaceOperations.companyId, f.companyId), eq(workspaceOperations.heartbeatRunId, f.runId), + eq(workspaceOperations.phase, "workspace_recovery"))); + await db.insert(workspaceOperations).values({ companyId: f.companyId, issueId: f.issueId, heartbeatRunId: f.runId, + executionWorkspaceId: f.workspaceId, phase: "workspace_finalize", status: "failed", + startedAt: new Date(finalize.startedAt.getTime() - 60_000), finishedAt: new Date(finalize.startedAt.getTime() - 59_000) }); + await expect(readiness(f.parentId)).resolves.toMatchObject({ + isDependencyReady: true, pendingFinalizeBlockerIssueIds: [] }); + }, 30_000); + + it("keeps a sibling's work that started during the recovery waiting for its own save", async () => { + const f = await recoveredDoneChildWithParent(); + const finalize = await recoveryFinalize(f); + const [sibling] = await db.insert(issues).values({ companyId: f.companyId, title: "Sibling", status: "done", + priority: "medium", executionWorkspaceId: f.workspaceId }).returning(); + await db.insert(issueRelations).values({ companyId: f.companyId, issueId: sibling.id, relatedIssueId: f.parentId, type: "blocks" }); + await db.insert(workspaceOperations).values({ companyId: f.companyId, issueId: sibling.id, + executionWorkspaceId: f.workspaceId, phase: "worktree_prepare", status: "succeeded", + startedAt: new Date(finalize.startedAt.getTime() - 1_000), finishedAt: new Date(finalize.startedAt.getTime() - 500) }); + await expect(readiness(f.parentId)).resolves.toMatchObject({ + isDependencyReady: false, pendingFinalizeBlockerIssueIds: [sibling.id] }); + }, 30_000); + + it("keeps the barrier for child workspace work started after the recovery", async () => { + const f = await recoveredDoneChildWithParent(); + const finalize = await recoveryFinalize(f); + await db.insert(workspaceOperations).values({ companyId: f.companyId, issueId: f.issueId, + executionWorkspaceId: f.workspaceId, phase: "worktree_prepare", status: "succeeded", + startedAt: new Date(finalize.startedAt.getTime() + 1_000), finishedAt: new Date(finalize.startedAt.getTime() + 2_000) }); + await expect(readiness(f.parentId)).resolves.toMatchObject({ + isDependencyReady: false, pendingFinalizeBlockerIssueIds: [f.issueId] }); + }, 30_000); +}); From 4d141cdf64394b5466eedacc6397187c4cd32f1b Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 11 Nov 2026 00:49:03 -0800 Subject: [PATCH 4/5] Carry plugin task refusals and batch project reads (#20762) --- doc/plugins/PLUGIN_AUTHORING_GUIDE.md | 11 ++++ packages/plugins/sdk/src/environment-tasks.ts | 5 +- .../plugins/sdk/src/host-client-factory.ts | 30 ++++++++- packages/plugins/sdk/src/index.ts | 1 + packages/plugins/sdk/src/protocol.ts | 24 ++++--- packages/plugins/sdk/src/testing.ts | 16 +++++ packages/plugins/sdk/src/types.ts | 31 ++++----- packages/plugins/sdk/src/worker-rpc-host.ts | 8 +++ packages/shared/src/types/plugin.ts | 2 + .../environment-task-runtime.test.ts | 27 ++++++++ .../plugin-project-snapshots.test.ts | 66 +++++++++++++++++++ .../src/__tests__/plugin-sdk-testing.test.ts | 21 ++++++ .../__tests__/plugin-tenant-isolation.test.ts | 8 +++ .../src/services/environment-task-runtime.ts | 20 +++++- .../native-session-executor.test.ts | 10 +++ .../native-runtime/native-session-executor.ts | 12 ++++ .../native-runtime/plugin-runner-task.test.ts | 17 +++++ .../native-runtime/plugin-runner-task.ts | 18 +++-- server/src/services/plugin-host-services.ts | 2 +- server/src/services/plugin-registry.ts | 2 + .../runner-e2e/source-sdk-public-inputs.json | 16 ++--- 21 files changed, 303 insertions(+), 44 deletions(-) create mode 100644 server/src/__tests__/plugin-project-snapshots.test.ts diff --git a/doc/plugins/PLUGIN_AUTHORING_GUIDE.md b/doc/plugins/PLUGIN_AUTHORING_GUIDE.md index 71c79e37742..cb25c2cb365 100644 --- a/doc/plugins/PLUGIN_AUTHORING_GUIDE.md +++ b/doc/plugins/PLUGIN_AUTHORING_GUIDE.md @@ -719,6 +719,17 @@ filesystem — there is no such capability. The browser still goes through the worker via `getData` / `performAction`, and the worker only exposes paths it chose to expose. +### Reading project snapshots + +Workers with `projects.read`, `project.workspaces.read`, and +`projects.instance-secrets` can call +`ctx.projects.readSnapshots(projectIds, companyId, entityType)` to read up to +64 distinct projects in one call. Each snapshot includes workspaces, the +worker's authorized instance secrets, and its own company-scoped entity of the +given type keyed by the project ID. A missing, archived, inaccessible, or +changing project fails the whole request. Older hosts return `null` through +the SDK. Keep instance secrets inside the trusted worker. + ### When to keep worker-mediated project workspace browsing When the data lives inside an existing project workspace, keep the browsing diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index 3dd691d4423..98e5f69a00b 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -121,6 +121,8 @@ export const environmentTaskOperationSchema = z.discriminatedUnion("kind", [ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [ z.object({ kind: z.literal("accepted"), taskId: providerId }).strict(), + z.object({ kind: z.literal("admission_rejected"), taskId: providerId, + reason: z.enum(["session_state_unavailable", "account_binding_mismatch"]) }).strict(), z.object({ kind: z.literal("released"), taskId: providerId }).strict(), z.object({ kind: z.literal("resume"), taskId: providerId, outcome: z.enum(["resumed", "unavailable"]) }).strict(), z.object({ kind: z.literal("copilot_metadata"), taskId: providerId, metadata: z.record(z.string(), z.unknown()), @@ -210,6 +212,7 @@ export interface PluginEnvironmentTaskParams extends Omit { + const companyId = resolveRequiredCompanyId("projects.readSnapshots", params, context); + requireCapability("projects.get"); + requireCapability("projects.listWorkspaces"); + const { projectIds, entityType } = params; + validateProjectSnapshotRequest(projectIds, entityType); + const snapshots: WorkerToHostMethods["projects.readSnapshots"][1] = []; + for (const projectId of projectIds) { + const scope = { companyId, projectId }; + const project = await services.projects.get(scope); + if (project?.id !== projectId || project.companyId !== companyId || project.archivedAt) { + throw new Error("Project snapshot unavailable"); + } + const query = { entityType, scopeKind: "company" as const, scopeId: companyId, externalId: projectId, limit: 1 }; + const [entity] = await services.entities.list(query); + const instanceSecrets = await services.projects.getInstanceSecrets(scope); + const workspaces = await services.projects.listWorkspaces(scope); + const current = await services.projects.get(scope); + const [latest] = await services.entities.list(query); + if (!isDeepStrictEqual(current, project) || !isDeepStrictEqual(latest, entity)) { + throw new Error("Project snapshot changed during read"); + } + snapshots.push({ projectId, workspaces, entity: entity ?? null, instanceSecrets }); + } + return snapshots; + }), "projects.get": gated("projects.get", async (params) => { return services.projects.get(params); }), diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.ts index 20e52d9e4ad..4e573c18119 100644 --- a/packages/plugins/sdk/src/index.ts +++ b/packages/plugins/sdk/src/index.ts @@ -329,6 +329,7 @@ export type { PluginEntityRecord, PluginEntityQuery, PluginWorkspace, + PluginProjectSnapshot, PluginExecutionWorkspaceMetadata, Company, Project, diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.ts index 215258cc886..95e8af999da 100644 --- a/packages/plugins/sdk/src/protocol.ts +++ b/packages/plugins/sdk/src/protocol.ts @@ -26,6 +26,7 @@ import type { PluginLauncherRenderContextSnapshot, PluginLauncherRenderEnvironment, PluginStateScopeKind, + PluginEntityQuery, Company, Project, Issue, @@ -70,6 +71,7 @@ import type { PluginJobContext, PluginExecutionWorkspaceMetadata, PluginWorkspace, + PluginProjectSnapshot, ToolRunContext, ToolResult, PluginLocalFolderListing, @@ -310,6 +312,15 @@ export interface PluginInvocationContext { traceparent?: string; } +export function validateProjectSnapshotRequest(projectIds: unknown, entityType: unknown): void { + if (!Array.isArray(projectIds) || !projectIds.length || projectIds.length > 64 || + new Set(projectIds).size !== projectIds.length || + projectIds.some(id => typeof id !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(id)) || + typeof entityType !== "string" || !/^[a-zA-Z0-9._-]{1,128}$/.test(entityType)) { + throw new Error("Invalid project snapshot scope"); + } +} + /** * Context provided to host-side worker→host handlers after the worker echoes a * host-issued invocation id. @@ -1734,14 +1745,7 @@ export interface WorkerToHostMethods { }, ]; "entities.list": [ - params: { - entityType?: string; - scopeKind?: PluginStateScopeKind; - scopeId?: string; - externalId?: string; - limit?: number; - offset?: number; - }, + params: PluginEntityQuery, result: Array<{ id: string; entityType: string; @@ -1855,6 +1859,10 @@ export interface WorkerToHostMethods { params: { projectId: string; companyId: string }, result: Record, ]; + "projects.readSnapshots": [ + params: { projectIds: string[]; companyId: string; entityType: string }, + result: PluginProjectSnapshot[], + ]; "projects.get": [ params: { projectId: string; companyId: string }, result: Project | null, diff --git a/packages/plugins/sdk/src/testing.ts b/packages/plugins/sdk/src/testing.ts index eb496adf22c..fa99065efa8 100644 --- a/packages/plugins/sdk/src/testing.ts +++ b/packages/plugins/sdk/src/testing.ts @@ -75,6 +75,7 @@ import type { PluginPerformActionActorContext, PluginPerformActionContext, } from "./protocol.js"; +import { validateProjectSnapshotRequest } from "./protocol.js"; export interface TestHarnessOptions { /** Plugin manifest used to seed capability checks and metadata. */ @@ -1044,6 +1045,21 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness { if (!isInCompany(project, companyId) || project.archivedAt) throw new Error("Project instance secrets unavailable"); return structuredClone(projectInstanceSecrets.get(JSON.stringify([companyId, projectId])) ?? {}); }, + async readSnapshots(projectIds, companyId, entityType) { + requireCapability(manifest, capabilitySet, "projects.read"); + requireCapability(manifest, capabilitySet, "project.workspaces.read"); + requireCapability(manifest, capabilitySet, "projects.instance-secrets"); + requireCompanyId(companyId); + validateProjectSnapshotRequest(projectIds, entityType); + return Promise.all(projectIds.map(async projectId => { + const project = await ctx.projects.get(projectId, companyId); + if (!project || project.archivedAt) throw new Error("Project snapshot unavailable"); + const [entity] = await ctx.entities.list({ entityType, scopeKind: "company", scopeId: companyId, externalId: projectId, limit: 1 }); + const instanceSecrets = await ctx.projects.getInstanceSecrets(projectId, companyId); + const workspaces = await ctx.projects.listWorkspaces(projectId, companyId); + return { projectId, workspaces, entity: entity ?? null, instanceSecrets }; + })); + }, async list(input) { requireCapability(manifest, capabilitySet, "projects.read"); const companyId = requireCompanyId(input?.companyId); diff --git a/packages/plugins/sdk/src/types.ts b/packages/plugins/sdk/src/types.ts index 9555522abfd..80375e46504 100644 --- a/packages/plugins/sdk/src/types.ts +++ b/packages/plugins/sdk/src/types.ts @@ -13,6 +13,7 @@ import type { PaperclipPluginManifestV1, PluginStateScopeKind, PluginEventType, + PluginEntityQuery, PluginToolDeclaration, PluginLauncherDeclaration, Company, @@ -64,6 +65,7 @@ import type { PluginPerformActionContext } from "./protocol.js"; export type { PaperclipPluginManifestV1, + PluginEntityQuery, PluginJobDeclaration, PluginWebhookDeclaration, PluginToolDeclaration, @@ -344,24 +346,6 @@ export interface PluginEntityRecord { updatedAt: string; } -/** - * Query parameters for `ctx.entities.list()`. - */ -export interface PluginEntityQuery { - /** Filter by entity type. */ - entityType?: string; - /** Filter by scope kind. */ - scopeKind?: PluginStateScopeKind; - /** Filter by scope ID. */ - scopeId?: string; - /** Filter by external ID. */ - externalId?: string; - /** Maximum number of results to return. */ - limit?: number; - /** Number of results to skip (for pagination). */ - offset?: number; -} - // --------------------------------------------------------------------------- // Project workspace metadata (read-only via ctx.projects) // --------------------------------------------------------------------------- @@ -876,6 +860,13 @@ export interface PluginEntitiesClient { * * @see PLUGIN_SPEC.md §7 — Project Workspaces */ +export interface PluginProjectSnapshot { + projectId: string; + workspaces: PluginWorkspace[]; + entity: PluginEntityRecord | null; + instanceSecrets: Record; +} + export interface PluginProjectsClient { /** Transient GitHub credential for a stored repository in the current host-issued * lifecycle/workspace invocation. Requires projects.git-credentials. Never persist or log. */ @@ -883,6 +874,10 @@ export interface PluginProjectsClient { /** Trusted worker access to this plugin’s native project credentials. * Requires projects.instance-secrets; never expose via UI/data handlers. */ getInstanceSecrets(projectId: string, companyId: string): Promise>; + /** Read authorized project workspaces, instance secrets and one plugin-owned entity per project. + * Missing or changing projects reject the batch. Null means the host does not support this method. + * Keep the result in the trusted worker. */ + readSnapshots(projectIds: string[], companyId: string, entityType: string): Promise; /** * List projects visible to the plugin. diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts index f6b801fc085..72f844508f6 100644 --- a/packages/plugins/sdk/src/worker-rpc-host.ts +++ b/packages/plugins/sdk/src/worker-rpc-host.ts @@ -761,6 +761,14 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost async getInstanceSecrets(projectId, companyId) { return callHost("projects.getInstanceSecrets", { projectId, companyId }); }, + async readSnapshots(projectIds, companyId, entityType) { + try { + return await callHost("projects.readSnapshots", { projectIds, companyId, entityType }); + } catch (error) { + if (error instanceof JsonRpcCallError && error.code === JSONRPC_ERROR_CODES.METHOD_NOT_FOUND) return null; + throw error; + } + }, async listWorkspaces(projectId: string, companyId: string) { return callHost("projects.listWorkspaces", { projectId, companyId }); diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts index 31fe2fb3346..36e0f50d97f 100644 --- a/packages/shared/src/types/plugin.ts +++ b/packages/shared/src/types/plugin.ts @@ -923,6 +923,8 @@ export interface PluginCompanySettings { * Query filter for `ctx.entities.list`. */ export interface PluginEntityQuery { + scopeKind?: PluginStateScopeKind; + scopeId?: string; /** Optional filter by entity type (e.g. 'project', 'issue'). */ entityType?: string; /** Optional filter by external system identifier. */ diff --git a/server/src/__tests__/environment-task-runtime.test.ts b/server/src/__tests__/environment-task-runtime.test.ts index 349c335aaca..0638ca050ad 100644 --- a/server/src/__tests__/environment-task-runtime.test.ts +++ b/server/src/__tests__/environment-task-runtime.test.ts @@ -61,6 +61,28 @@ describe("stopped Runner checkpoint settlement", () => { }); describe("plugin-provided Runner execution", () => { + it("records a confirmed admission refusal so lease cleanup never looks for a Runner", async () => { + const value = row(); + const fixture = database(value); + const refusal = { kind: "admission_rejected", taskId: "attempt-1", reason: "session_state_unavailable" }; + const workers = worker(refusal); + await expect(executeEnvironmentTask(fixture.db, workers as never, { + companyId: "company", leaseId, operation: submit, + })).resolves.toEqual(refusal); + const update = new PgDialect().sqlToQuery(fixture.sets.at(-1)!.metadata as never); + expect(update.sql).toContain("- 'runnerTaskIdentity'"); + const durable = JSON.parse(String(update.params[0])); + expect(durable).toEqual({ + runnerTaskAdmissionRejection: { taskId: "attempt-1", reason: "session_state_unavailable" }, + runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: false, + }); + Object.assign(value.lease.metadata, durable); + await expect(settleDispatchedEnvironmentTask(database(value).db, workers as never, { + companyId: "company", id: leaseId, + })).resolves.toBe("stopped"); + expect(workers.call.mock.calls).toHaveLength(1); + }); + it.each([false, true])("retires an undispatched warm task only with required preparation proof (%s)", async preparationStopped => { const value = row(); Object.assign(value.lease.metadata, { runnerTaskDispatched: false, @@ -615,5 +637,10 @@ describe("plugin-provided Runner execution", () => { expect(environmentTaskOperationSchema.safeParse({ ...submit, runner: { ...submit.runner, unknownField: true } }).success).toBe(false); expect(() => parseEnvironmentTaskResult({ kind: "status" }, "attempt-1", { kind: "accepted", taskId: "attempt-1" })).toThrow(); expect(parseEnvironmentTaskResult(submit, "attempt-1", { kind: "accepted", taskId: "attempt-1" }).kind).toBe("accepted"); + const rejected = { kind: "admission_rejected", taskId: "attempt-1", reason: "account_binding_mismatch" }; + expect(parseEnvironmentTaskResult(submit, "attempt-1", rejected)).toEqual(rejected); + expect(() => parseEnvironmentTaskResult(submit, "attempt-2", rejected)).toThrow(); + expect(() => parseEnvironmentTaskResult(submit, "attempt-1", { ...rejected, reason: "unknown" })).toThrow(); + expect(() => parseEnvironmentTaskResult({ kind: "stop" }, "attempt-1", rejected)).toThrow(); }); }); diff --git a/server/src/__tests__/plugin-project-snapshots.test.ts b/server/src/__tests__/plugin-project-snapshots.test.ts new file mode 100644 index 00000000000..0a08aaa279d --- /dev/null +++ b/server/src/__tests__/plugin-project-snapshots.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from "vitest"; +import { createHostClientHandlers, type HostServices } from "../../../packages/plugins/sdk/src/host-client-factory.js"; +import type { PluginCapability } from "@paperclipai/shared"; + +const companyId = "00000000-0000-4000-8000-000000000001"; +const otherCompany = "00000000-0000-4000-8000-000000000002"; +const first = "00000000-0000-4000-8000-000000000003"; +const second = "00000000-0000-4000-8000-000000000004"; +const capabilities: PluginCapability[] = ["projects.read", "project.workspaces.read", "projects.instance-secrets"]; +const entityType = "project-settings"; + +function fixture(granted = capabilities) { + const projects = new Map([first, second].map(id => [id, { id, companyId, archivedAt: null as Date | null }])); + const entities = new Map([first, second].map(id => [id, { id, status: "ready" }])); + const services = { + projects: { + get: vi.fn(async ({ projectId }: { projectId: string }) => structuredClone(projects.get(projectId) ?? null)), + listWorkspaces: vi.fn(async ({ projectId }: { projectId: string }) => [{ projectId }]), + getInstanceSecrets: vi.fn(async ({ projectId }: { projectId: string }) => ({ fixture: projectId })), + }, + entities: { list: vi.fn(async ({ externalId }: { externalId: string }) => entities.has(externalId) ? [{ ...entities.get(externalId) }] : []) }, + }; + const handlers = createHostClientHandlers({ pluginId: "project-plugin", capabilities: granted, services: services as unknown as HostServices }); + return { services, projects, entities, read: (projectIds: string[], requestedCompany = companyId) => handlers["projects.readSnapshots"]( + { projectIds, companyId: requestedCompany, entityType }, { invocationScope: { companyId } }, + ) }; +} + +describe("plugin project snapshots", () => { + it("returns the requested projects in order with only the plugin's company-scoped entity", async () => { + const f = fixture(); + const result = await f.read([second, first]); + expect(result.map(row => [row.projectId, row.workspaces[0].projectId, row.entity?.id, row.instanceSecrets.fixture])) + .toEqual([[second, second, second, second], [first, first, first, first]]); + expect(f.services.entities.list.mock.calls.map(([query]) => query)).toEqual([second, second, first, first].map(externalId => ({ + entityType, scopeKind: "company", scopeId: companyId, externalId, limit: 1, + }))); + }); + + it("requires each underlying capability and the invocation's company", async () => { + for (const omitted of capabilities) { + const f = fixture(capabilities.filter(capability => capability !== omitted)); + await expect(f.read([first])).rejects.toThrow("missing required capability"); + expect(f.services.projects.get).not.toHaveBeenCalled(); + } + const f = fixture(); + await expect(f.read([first], otherCompany)).rejects.toThrow(/invocation.*company/i); + await expect(f.read([first, first])).rejects.toThrow("Invalid project snapshot scope"); + expect(f.services.projects.get).not.toHaveBeenCalled(); + }); + + it.each(["wrong company", "archived", "missing", "changed entity"])("rejects the whole batch for a %s project", async failure => { + const f = fixture(); + if (failure === "wrong company") f.projects.set(second, { id: second, companyId: otherCompany, archivedAt: null }); + else if (failure === "archived") f.projects.get(second)!.archivedAt = new Date(); + else if (failure === "missing") f.projects.delete(second); + else f.services.projects.listWorkspaces.mockImplementation(async ({ projectId }: { projectId: string }) => { + if (projectId === second) f.entities.get(second)!.status = "changed"; + return [{ projectId }]; + }); + await expect(f.read([first, second])).rejects.toThrow(/Project snapshot (unavailable|changed during read)/); + if (failure !== "changed entity") { + expect(f.services.projects.getInstanceSecrets).not.toHaveBeenCalledWith({ companyId, projectId: second }); + } + }); +}); diff --git a/server/src/__tests__/plugin-sdk-testing.test.ts b/server/src/__tests__/plugin-sdk-testing.test.ts index 6c2edd9e0bc..4d1a4f09338 100644 --- a/server/src/__tests__/plugin-sdk-testing.test.ts +++ b/server/src/__tests__/plugin-sdk-testing.test.ts @@ -42,6 +42,27 @@ function seededIssue(input: Partial & Pick { + it("rejects project snapshot requests that the host would deny", async () => { + const manifest: PaperclipPluginManifestV1 = { + id: "paperclip.test-project-snapshots", + apiVersion: 1, + version: "0.1.0", + displayName: "Project Snapshots", + description: "Test plugin", + author: "Paperclip", + categories: ["automation"], + capabilities: ["projects.read", "project.workspaces.read", "projects.instance-secrets"], + entrypoints: { worker: "./dist/worker.js" }, + }; + const harness = createTestHarness({ manifest }); + const projectId = "10000000-0000-4000-8000-000000000001"; + await expect(harness.ctx.projects.readSnapshots([], "company", "settings")).rejects.toThrow("Invalid project snapshot scope"); + await expect(harness.ctx.projects.readSnapshots([projectId, projectId], "company", "settings")).rejects.toThrow("Invalid project snapshot scope"); + await expect(harness.ctx.projects.readSnapshots([projectId], "company", "bad type")).rejects.toThrow("Invalid project snapshot scope"); + const denied = createTestHarness({ manifest: { ...manifest, capabilities: [] } }); + await expect(denied.ctx.projects.readSnapshots([], "company", "settings")).rejects.toThrow("missing required capability"); + }); + it("returns scoped execution workspace metadata with the read capability", async () => { const manifest: PaperclipPluginManifestV1 = { id: "paperclip.test-execution-workspace-metadata", diff --git a/server/src/__tests__/plugin-tenant-isolation.test.ts b/server/src/__tests__/plugin-tenant-isolation.test.ts index dc5776d10de..646653c1cb2 100644 --- a/server/src/__tests__/plugin-tenant-isolation.test.ts +++ b/server/src/__tests__/plugin-tenant-isolation.test.ts @@ -372,6 +372,14 @@ describeEmbeddedPostgres("plugin tenant isolation (company_id FK)", () => { expect(fromInstance?.companyId).toBeNull(); expect(fromInstance?.title).toBe("instance"); + const services = buildHostServices(db, pluginId, "tenant-isolation-test", createEventBusStub()); + await expect(services.entities.list({ + entityType: "issue", scopeKind: "company", scopeId: companyB, externalId: "ext-shared", limit: 1, + })).resolves.toEqual([expect.objectContaining({ title: "B" })]); + await expect(services.entities.list({ + entityType: "issue", scopeKind: "company", scopeId: randomUUID(), externalId: "ext-shared", limit: 1, + })).resolves.toEqual([]); + // Unknown tenant returns null, not another tenant's row. const unknown = await registry.getEntityByExternalId( pluginId, diff --git a/server/src/services/environment-task-runtime.ts b/server/src/services/environment-task-runtime.ts index 7aa54e50c3e..7c8a787a953 100644 --- a/server/src/services/environment-task-runtime.ts +++ b/server/src/services/environment-task-runtime.ts @@ -258,7 +258,7 @@ export async function executeEnvironmentTask(db: Db, workers: PluginWorkerManage if (operation.kind === "submit" || operation.kind === "copilot_metadata") { // No ticket, headers, environment values, or launch paths belong in metadata. const marked = await db.update(environmentLeases).set({ - metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskLease: true, runnerTaskDispatched: true, runnerTaskExecutionStopped: false, runnerTaskSessionRetained: false, ...(operation.kind === "submit" ? { runnerTaskIdentity: operation.runner, runnerTaskResumeFrom: operation.resumeFrom ?? null } : {}) })}::jsonb`, + metadata: sql`(coalesce(${environmentLeases.metadata}, '{}'::jsonb) - 'runnerTaskAdmissionRejection') || ${JSON.stringify({ runnerTaskLease: true, runnerTaskDispatched: true, runnerTaskExecutionStopped: false, runnerTaskSessionRetained: false, ...(operation.kind === "submit" ? { runnerTaskIdentity: operation.runner, runnerTaskResumeFrom: operation.resumeFrom ?? null } : {}) })}::jsonb`, }).where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.status, "active"), sql`coalesce(${environmentLeases.metadata}->>'runnerTaskRetiring', 'false') != 'true'`, requiredProjectAuthProof ? sql`${environmentLeases.metadata}->'runnerTaskProjectAuthValidation' = ${JSON.stringify(requiredProjectAuthProof)}::jsonb` : undefined, @@ -280,7 +280,9 @@ export async function executeEnvironmentTask(db: Db, workers: PluginWorkerManage if (marked.length !== 1) throw new Error("Plugin warm task attachment lost authority"); } try { - const stoppedWithoutSession = !!run && metadata.runnerTaskExecutionStopped === true && metadata.runnerTaskSessionRetained !== true; + const admissionRejection = metadata.runnerTaskAdmissionRejection as { taskId?: unknown } | undefined; + const stoppedWithoutSession = !!run && metadata.runnerTaskExecutionStopped === true && + metadata.runnerTaskSessionRetained !== true && admissionRejection?.taskId !== taskId; if (operation.kind === "describe" && (metadata.runnerTaskReused === true || stoppedWithoutSession)) { const state = parseEnvironmentTaskResult({kind:"status"}, taskId, await callWorker("environmentTask", { driverKey: metadata.driverKey, companyId: input.companyId, environmentId: environment?.id ?? null, @@ -408,6 +410,20 @@ export async function executeEnvironmentTask(db: Db, workers: PluginWorkerManage const result = await callWorker("environmentTask", params, timeout); if (executionContext) context!.assertOpen(); const parsed = parseEnvironmentTaskResult(operation, taskId, result); + if (operation.kind === "submit" && parsed.kind === "admission_rejected") { + const recorded = await db.update(environmentLeases).set({ + metadata: sql`(coalesce(${environmentLeases.metadata}, '{}'::jsonb) - 'runnerTaskIdentity') || ${JSON.stringify({ + runnerTaskAdmissionRejection: { taskId, reason: parsed.reason }, + runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: false, + })}::jsonb`, + }).where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, input.companyId), + eq(environmentLeases.providerLeaseId, taskId), + sql`${environmentLeases.metadata}->>'runnerTaskDispatched' = 'true'`, + sql`${environmentLeases.metadata}->'runnerTaskIdentity' = ${JSON.stringify(operation.runner)}::jsonb`, + )).returning({ id: environmentLeases.id }); + if (recorded.length !== 1) throw new Error("Plugin Runner admission receipt is stale"); + return parsed; + } if (stoppedSourceCheckpoint && parsed.kind === "state" && isSettledReadyRunnerState(parsed.state)) { parsed.state = { ...parsed.state, lifecycle: "suspended" }; } diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 65aa6b99f5a..09fff02dfce 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -13989,6 +13989,16 @@ describe("native session bounded recovery", () => { }, ); + it("stops same-run retries when the execution provider proves task admission was rejected", () => { + for (const prefix of ["", "runner_ingress_unavailable: runnerd exited unexpectedly with code 1: "]) { + const code = nativeSessionFailureSourceCode(new Error(`${prefix}runner_task_admission_rejected: session_state_unavailable`)); + expect(code).toBe("runner_task_admission_rejected"); + expect(nativeSessionFailureDisposition(1, new Date(), code)).toEqual({ + phase: "terminal_failure", failureCode: code, nextAttemptAt: null, + }); + } + }); + it("stops same-run retries when the runner proves the saved provider session incompatible", () => { const failure = new NativeProviderStateIncompatibleError( "Error: PRP command run.attach failed: ACPX durable launch profile digest does not match runner startup", diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 3f50677c75a..3b37d6c3145 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -8426,6 +8426,7 @@ export function nativeSessionFailureDisposition( sourceFailureCode?: ReturnType, ) { const permanentFailure = + sourceFailureCode === "runner_task_admission_rejected" || sourceFailureCode === "runner_ingress_access_rejected" || sourceFailureCode === "native_provider_runtime_missing" || sourceFailureCode === "native_provider_model_rejected" || @@ -8543,6 +8544,7 @@ export function nativeSessionFailureSourceCode( | typeof NATIVE_CURRENT_WAKE_COMMENTS_CHANGED_AFTER_READ | "provider_session_open_rejected" | "provider_session_open_timeout" + | "runner_task_admission_rejected" | "runner_ingress_access_rejected" | "runner_ingress_acquisition_failed" | "local_runtime_api_listener_unavailable" @@ -8583,6 +8585,9 @@ export function nativeSessionFailureSourceCode( } if (runnerClosedTurnStartSession(error)) return NATIVE_PROVIDER_SESSION_CLOSED; const message = error instanceof Error ? error.message : String(error); + if (/^(?:runner_ingress_unavailable: runnerd exited unexpectedly with code 1: )?runner_task_admission_rejected: (session_state_unavailable|account_binding_mismatch)$/.test(message)) { + return "runner_task_admission_rejected"; + } if (/classification=runtime_package_missing\)/.test(message)) return "native_provider_runtime_missing"; if (/native_provider_model_rejected/i.test(message)) @@ -8679,6 +8684,9 @@ export function nativeSessionFailureSourceCode( const NATIVE_PROVIDER_SIDE_EFFECT_PENDING_ACTION = "The saved provider session has an unfinished provider turn, or a tool call whose result never reached the runner, so Paperclip did not replace the session or retry it. Reconcile the action: check whether it ran and record the outcome. The task then continues in a fresh provider session in the same workspace. The saved session and workspace are unchanged."; +const RUNNER_TASK_ADMISSION_REJECTED_ACTION = + "The execution provider refused to start this task. Review the admission reason before retrying. Automatic retries are stopped."; + const NATIVE_PROVIDER_STATE_INCOMPATIBLE_ACTION = "The current runner cannot restore this task's saved provider session, so retrying this run cannot succeed. Retry the task to continue in a fresh provider session with the same workspace. The earlier provider conversation is not carried over."; @@ -12425,6 +12433,8 @@ async function executePaperclipNativeSessionAttempt( ? nativeCleanupRefusalAction(completedTurnCleanup) : sourceFailureCode === "runner_remote_provider_verification_unavailable" ? "Provider files could not be verified after two read attempts. Inspect the retained workspace and command transport before retrying the original run." + : sourceFailureCode === "runner_task_admission_rejected" + ? RUNNER_TASK_ADMISSION_REJECTED_ACTION : sourceFailureCode === "runner_ingress_access_rejected" ? "The computer provider rejected access. Restore the environment's credentials or permissions before retrying. Automatic retries are stopped." : sourceFailureCode === "native_provider_terminal_failed" @@ -12694,6 +12704,8 @@ async function executePaperclipNativeSessionAttempt( ? NATIVE_PROVIDER_SESSION_CLOSED_ACTION : sourceFailureCode === "native_session_cleanup_quarantined" ? nativeCleanupRefusalAction(completedTurnCleanup) + : sourceFailureCode === "runner_task_admission_rejected" + ? RUNNER_TASK_ADMISSION_REJECTED_ACTION : sourceFailureCode === "runner_ingress_access_rejected" ? "The computer provider rejected access. Restore the environment's credentials or permissions before retrying. Automatic retries are stopped." : sourceFailureCode === "native_provider_terminal_failed" diff --git a/server/src/services/native-runtime/plugin-runner-task.test.ts b/server/src/services/native-runtime/plugin-runner-task.test.ts index d7089dfaf35..004a1e8ab60 100644 --- a/server/src/services/native-runtime/plugin-runner-task.test.ts +++ b/server/src/services/native-runtime/plugin-runner-task.test.ts @@ -440,6 +440,23 @@ describe("plugin native Runner ownership", () => { expect(task.mock.calls.find(([op]) => op.kind === "stop")).toBeUndefined(); await registration.release(); await registration.checkpoint("settled"); await handle.completion; }); + it("surfaces a proven admission rejection without polling or stopping the task", async () => { + const { task } = provider(); + const perform = task.getMockImplementation()!; + task.mockImplementation(async op => op.kind === "submit" + ? { kind: "admission_rejected", taskId: "task", reason: "session_state_unavailable" } : perform(op)); + const owner = createPluginRunnerTaskOwner({ taskId: "task", projectAuthCheckVersion: 1, task, projectIds: [], harness: "codex" }); + await prepare(owner); + const registration = await owner.registration({} as never, "run"); + const process = owner.launcher(launchSpec()); + registration.activate(); + await expect(registration.ready()).rejects.toThrow("runner_task_admission_rejected: session_state_unavailable"); + await expect(registration.failure).rejects.toThrow("runner_task_admission_rejected: session_state_unavailable"); + await expect(process.completion).resolves.toMatchObject({ code: 1 }); + await registration.checkpoint("unsettled"); + expect(task.mock.calls.map(([op]) => op.kind)).toEqual(["prepare", "check_project_auth", "submit"]); + }); + it("reconciles a lost submit reply without launching another attempt", async () => { const { task } = provider(); const perform = task.getMockImplementation()!; diff --git a/server/src/services/native-runtime/plugin-runner-task.ts b/server/src/services/native-runtime/plugin-runner-task.ts index 2b5855fa2ce..72893bff48c 100644 --- a/server/src/services/native-runtime/plugin-runner-task.ts +++ b/server/src/services/native-runtime/plugin-runner-task.ts @@ -71,7 +71,7 @@ export function createPluginRunnerTaskOwner(input: { let adoptionVerified = false; let markReady!: () => void; let failReady!: (error: unknown) => void; - let confirmStopped: (code: number) => void = () => {}; + let confirmStopped: (code: number, error?: Error) => void = () => {}; let stoppedState: Extract | undefined; let completed = false; let retiredBeforeClaim = false; @@ -225,11 +225,11 @@ export function createPluginRunnerTaskOwner(input: { return true; } }; const completion = new Promise>(resolve => { - confirmStopped = code => { + confirmStopped = (code, error) => { if (child.exitCode !== null) return; child.exitCode = code; - failReady(new Error("Plugin Runner stopped before connection")); - resolve({ code, signal: null, stdout: "", stderr: "" }); + failReady(error ?? new Error("Plugin Runner stopped before connection")); + resolve({ code, signal: null, stdout: "", stderr: error?.message ?? "" }); }; }); void (async () => { @@ -248,9 +248,17 @@ export function createPluginRunnerTaskOwner(input: { return; } submitted = true; - try { await call(operation); } catch { + const result = await call(operation).catch(async () => { // Submission can have succeeded remotely. Inspect the same saved task. await readStatus(); + }); + if (result?.kind === "admission_rejected") { + submitted = false; + removeStartupAbort(); + const error = new Error(`runner_task_admission_rejected: ${result.reason}`); + rejectFailure(error); + confirmStopped(1, error); + return; } let stopSent = false; while (child.exitCode === null) { diff --git a/server/src/services/plugin-host-services.ts b/server/src/services/plugin-host-services.ts index ee41f2c1e33..caf0a02bb67 100644 --- a/server/src/services/plugin-host-services.ts +++ b/server/src/services/plugin-host-services.ts @@ -1754,7 +1754,7 @@ export function buildHostServices( return registry.upsertEntity(pluginId, params as any) as any; }, async list(params) { - return registry.listEntities(pluginId, params as any) as any; + return registry.listEntities(pluginId, params) as any; }, }, diff --git a/server/src/services/plugin-registry.ts b/server/src/services/plugin-registry.ts index 68d15d5d9de..5f5c84470d3 100644 --- a/server/src/services/plugin-registry.ts +++ b/server/src/services/plugin-registry.ts @@ -541,6 +541,8 @@ export function pluginRegistryService(db: Db) { const conditions = [eq(pluginEntities.pluginId, pluginId)]; if (query?.entityType) conditions.push(eq(pluginEntities.entityType, query.entityType)); if (query?.externalId) conditions.push(eq(pluginEntities.externalId, query.externalId)); + if (query?.scopeKind) conditions.push(eq(pluginEntities.scopeKind, query.scopeKind)); + if (query?.scopeId) conditions.push(eq(pluginEntities.scopeId, query.scopeId)); return db .select() diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 6eccbfd0a56..016c2082ccd 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -13,23 +13,23 @@ "packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb", "packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8", "packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4", - "packages/plugins/sdk/src/environment-tasks.ts": "3dd691d4423402ab7c0d3249a03bf6b22eeb78f2", - "packages/plugins/sdk/src/host-client-factory.ts": "f1bba9f1830701510f2c94bc623465cb2d93413b", + "packages/plugins/sdk/src/environment-tasks.ts": "98e5f69a00b81eb6e8c25bdb5fcdc22e5485ef18", + "packages/plugins/sdk/src/host-client-factory.ts": "e0301c390ea13f2340b669383f07af2455e48c8a", "packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a", "packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f", - "packages/plugins/sdk/src/index.ts": "20e52d9e4ad3d5015cfbc604da49756e568e34ba", + "packages/plugins/sdk/src/index.ts": "4e573c181198ea98442321cc136341741e856ff7", "packages/plugins/sdk/src/invocation-tracer.ts": "b28ac4aa4bc3e82658abac4a8081ed4508008696", "packages/plugins/sdk/src/protocol.duplex-channel.test.ts": "18255eb3d63038dc459240c111cbcb29fcba25cc", - "packages/plugins/sdk/src/protocol.ts": "215258cc8862b342acdbd6446fb49d00cc578fd8", - "packages/plugins/sdk/src/testing.ts": "eb496adf22c62b6d68ef467c25465afd0973d236", - "packages/plugins/sdk/src/types.ts": "9555522abfd796c59b1439dd433be356ec344bb5", + "packages/plugins/sdk/src/protocol.ts": "95e8af999dabf93b1b0e531edfec4c80daf52b61", + "packages/plugins/sdk/src/testing.ts": "fa99065efa867d8f8a9372cb4a448b8f9d687883", + "packages/plugins/sdk/src/types.ts": "80375e46504f96c7c0c1f156319dfb81275d16cc", "packages/plugins/sdk/src/ui/clipboard.ts": "1f42069c97d731e636a6ad5481dad22d20c0ed63", "packages/plugins/sdk/src/ui/components.ts": "3f0594408a1bb5ac3a8d00e709f91877dd260359", "packages/plugins/sdk/src/ui/hooks.ts": "686d02cf4b35f1cddb79a83a4c4d81fd52f0100e", "packages/plugins/sdk/src/ui/index.ts": "f7d1cee64a8f0c924bd10a1bd20745a52fe2060e", "packages/plugins/sdk/src/ui/runtime.ts": "998428e9701eba3b762d3417236d32c2d0d5763d", "packages/plugins/sdk/src/ui/types.ts": "5a5644acf6554d2e5e1d000bfd03b97d57001eb2", - "packages/plugins/sdk/src/worker-rpc-host.ts": "f6b801fc08596a8ab6344f12ac0ee80f256b2066", + "packages/plugins/sdk/src/worker-rpc-host.ts": "72f844508f695737a44d34b01b3949ec3be10aec", "packages/plugins/sdk/src/workspace-operation-error.ts": "2cd247d002d83b163239229e631bca4e519e5075", "packages/plugins/sdk/src/workspace-provider.ts": "c212c3baffd4151010060c9ec7393bd989a9e833", "packages/plugins/sdk/tsconfig.json": "d62ebdff94bc4b75dabf1fcad187e1e7a90fc794", @@ -405,7 +405,7 @@ "packages/shared/src/types/issue.ts": "4598caecc50e60450a1204de832a4fcd7991096d", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", - "packages/shared/src/types/plugin.ts": "31fe2fb3346dabbf83aa7e37193bb0dd229ea8a7", + "packages/shared/src/types/plugin.ts": "36e0f50d97f96532cb1fbdf3223368d92a7e9b1e", "packages/shared/src/types/project.ts": "2a20b4d8772d5f0fa5015828818b025abc7cedcf", "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", From eb75c9bb855ce83915256efc9d6b308a272cdeff Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 02:56:52 -0600 Subject: [PATCH 5/5] fix(native): resend a throttled harness backup upload instead of losing it (#20772) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - After a native run in a per-turn remote sandbox, the server saves a durable harness backup to object storage. The next run restores the provider session from it. > - On staging, two OpenCode runs had an accepted result, but `harness_state.backup.persist` failed. The run log for both says `remote checkpoint failed: Please reduce your request rate.` This is the S3 `SlowDown` (HTTP 503) answer. > - The backup and the OpenCode provider-artifact bundle were uploaded as one stream `PUT`. The S3 SDK cannot send a stream body again, and this path had no retry for a request-rate limit. One `SlowDown` lost the backup. > - The sandbox was then released. The follow-up run had no state to resume and failed with `PRP provider resume state is unavailable` (class P, see #20757). > - This pull request uploads both objects from their encrypted scratch file, as workspace snapshots already do. The existing throttled-retry path then sends them again. > - The benefit is that a short request-rate limit no longer loses the only copy of a provider session. ## Linked Issues or Issue Description Refs #20757 (the failure this causes on the next run). Refs #19917 (added the file-source upload path that this change uses). **What happened?** 1. An OpenCode run in a per-turn Daytona sandbox finished, and its result was accepted. 2. The server uploaded the encrypted harness backup with `storage.putFile` and a stream body. 3. Object storage answered `503 SlowDown` ("Please reduce your request rate."). Nothing sent the request again. 4. `harness_state.backup.persist` failed, and `native.post_result_failure` was recorded. 5. The next run for the same chat task started in a new sandbox and could not resume the provider session. **Expected behavior** A request-rate limit slows the upload down. It does not lose the backup. **Steps to reproduce** 1. Point the storage service at an S3 endpoint that answers the first `PUT` of each object with `503 SlowDown`. 2. Call `persistNativeHarnessBackup`. 3. On `master` it throws `SlowDown: Please reduce your request rate.` **Paperclip version or commit** `master` at `9574065a28`. ## What Changed - `server/src/services/native-runtime/native-harness-backup-storage.ts`: pass the encrypted scratch file as `sourceFile` to `putFile`. - `server/src/services/native-runtime/native-provider-artifacts.ts`: the same for the provider-artifact bundle. - `native-harness-backup-throttle.integration.test.ts` (new, focused file): a real S3 client against a local endpoint that throttles the first `PUT` of each object once. Cases for a Codex backup, and for an OpenCode backup with provider artifacts. Each case also throttles the first read-back of each object once. Each case checks that the backup is current and restores the provider session bytes. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-harness-backup-throttle.integration.test.ts`: both cases fail on `master` with `SlowDown: Please reduce your request rate.` and pass with this change. - `cd server && npx vitest run src/services/native-runtime/native-harness-backup-storage.integration.test.ts`: 68 pass (file unchanged). - `cd server && npx tsc --noEmit -p .`: clean. - `pnpm verify`: it selected the full server suite and failed 16 of 34,997 tests, all local-environment failures unrelated to object storage: missing `.claude/skills/*/SKILL.md` files in this worktree, `ENAMETOOLONG` under the macOS temp directory, and 30 s hook timeouts under load. Required CI is the authority for that suite. ## Risks - Low. A file source also sends a `Content-MD5` header, so the backend rejects any byte it did not receive intact. Workspace snapshots have used this path since #19917. - An upload above 16 MiB now uses the file multipart path. That path has the same verified-part retry. - The read-back check (`getObject`) needs no change: a GET has no body, so the S3 client resends it after `SlowDown`. The test now also throttles the first read of each object once and proves the backup still publishes. - The Rust Runner is unchanged. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code, with tool use (shell, file edit, test execution) and read-only staging API reads. ## 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 --- .../native-harness-backup-storage.ts | 4 +- ...arness-backup-throttle.integration.test.ts | 145 ++++++++++++++++++ .../native-provider-artifacts.ts | 2 + 3 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts diff --git a/server/src/services/native-runtime/native-harness-backup-storage.ts b/server/src/services/native-runtime/native-harness-backup-storage.ts index 993952c7a9a..6df1d5f2749 100644 --- a/server/src/services/native-runtime/native-harness-backup-storage.ts +++ b/server/src/services/native-runtime/native-harness-backup-storage.ts @@ -242,7 +242,9 @@ export async function persistNativeHarnessBackup(input: { }); await input.storage.putFile({ companyId: ref.companyId, namespace: "native-harness-backups", objectKey: ref.objectKey, originalFilename: null, contentType: "application/octet-stream", body: createReadStream(encrypted), - byteSize: ref.byteSize, sha256: ref.sha256, signal: input.signal }); + // The file source lets a request-rate limit (503 SlowDown) or a dropped + // connection resend the upload; a stream body can be sent only once. + byteSize: ref.byteSize, sha256: ref.sha256, sourceFile: encrypted, signal: input.signal }); await receive(input.storage, ref, undefined, input.signal); await input.db.transaction(async tx => { await fence(tx, input.owner, inactiveSource, input.signal); diff --git a/server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts b/server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts new file mode 100644 index 00000000000..f5b148d5484 --- /dev/null +++ b/server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts @@ -0,0 +1,145 @@ +import { createHash, randomUUID } from "node:crypto"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { join } from "node:path"; +import { and, eq } from "drizzle-orm"; +import { heartbeatRuns, nativeHarnessBackups, nativeRunFinalizations } from "@paperclipai/db"; +import { afterEach, expect, it, vi } from "vitest"; +import { describeEmbeddedPostgres, nativeRestartFixture } from "../../__tests__/helpers/native-restart.js"; +import { createLocalDiskStorageProvider } from "../../storage/local-disk-provider.js"; +import { createS3StorageProvider } from "../../storage/s3-provider.js"; +import { createStorageService } from "../../storage/service.js"; +import { nativeHarnessBackupOwner, persistNativeHarnessBackup, restoreDurableNativeHarnessBackup } from "./native-harness-backup-storage.js"; +import { removeNativeHarnessBackup } from "./native-harness-backup-cleanup.js"; +import { canonicalProviderPackJson } from "./remote-provider-pack-verification.js"; + +// Durable harness backups against an S3 endpoint that throttles requests. +describeEmbeddedPostgres("durable native provider backups under an object-storage request-rate limit", () => { + const environment = nativeRestartFixture(); + const ownedHomes: string[] = []; + afterEach(async () => { + for (const home of ownedHomes.splice(0)) await removeNativeHarnessBackup(home); + vi.unstubAllEnvs(); + }); + async function fixture(provider = "codex") { + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "51".repeat(32)); + const f = await environment.seedRun(randomUUID()); + const { companyId, runtimeRoot, successor } = environment.current; + await f.db.update(nativeRunFinalizations).set({ controllerBootId: successor.bootId, controllerGeneration: 1, + leaseOwner: "backup-writer", leaseExpiresAt: new Date(Date.now() + 120_000) }).where(eq(nativeRunFinalizations.runId, f.runId)); + const owner = await nativeHarnessBackupOwner(f.db, { companyId, issueId: f.issueId, runId: f.runId, bootId: successor.bootId }); + const home = join(runtimeRoot, randomUUID()), root = join(home, "failover-backups", "current"); + ownedHomes.push(home); + await mkdir(join(root, provider, "sessions"), { recursive: true }); + await mkdir(join(root, "runner")); + const identity = { normalizedSessionId: randomUUID(), providerSessionId: randomUUID(), provider }; + await writeFile(join(root, provider, "sessions", "history.json"), JSON.stringify(identity), { mode: 0o600 }); + await writeFile(join(root, "runner", "runner-state.json"), JSON.stringify({ runId: f.runId, lifecycle: "suspended" }), { mode: 0o600 }); + const manifest = JSON.stringify({ schema: "paperclip.native-harness-backup.v1", ...identity, directories: [provider, "runner"] }); + await writeFile(join(root, "manifest.json"), manifest, { mode: 0o600 }); + await chmod(join(root, provider, "sessions"), 0o500); + const sessionScopeId = randomUUID(), scopeDigest = createHash("sha256").update(sessionScopeId).digest("hex"); + const storage = createStorageService(createLocalDiskStorageProvider(join(runtimeRoot, "durable-objects"))); + return { ...f, home, root, companyId, owner, scopeDigest, sessionScopeId, storage, identity, + manifestSha256: `sha256:${createHash("sha256").update(manifest).digest("hex")}` }; + } + async function artifactFixture(artifactVersion = randomUUID()) { + const f = await fixture("opencode"); + const sourceRoot = join(f.home, "qualified-provider-pack"); + await mkdir(sourceRoot); + const original = { nodeCommand: "qualified Node executable", opencodeExecutable: "qualified OpenCode executable", + opencodeProxy: `qualified original proxy bytes ${artifactVersion}` }; + const artifacts = Object.fromEntries(await Promise.all(Object.entries(original).map(async ([name, bytes]) => { + await writeFile(join(sourceRoot, name), bytes, { mode: 0o500 }); + return [name, { path: name, sha256: `sha256:${createHash("sha256").update(bytes).digest("hex")}` }]; + }))); + const payload = { runnerSourceRevision: "a".repeat(40), target: { platform: "linux", architecture: "x64" }, + pins: { opencode: "1.18.34" }, artifacts: { ...artifacts, opencodeCommand: artifacts.opencodeExecutable } }; + const manifest = { schema: "paperclip-runner/remote-provider-pack/v1", payload, + digest: `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` }; + const launchRoot = `/home/daytona/.paperclip-runtime/paperclip-runner/provider-artifacts/${manifest.digest.slice(7)}`; + await f.db.update(heartbeatRuns).set({ nativeSessionId: f.identity.normalizedSessionId, driverKind: "opencode_server", + runnerProfileJson: { ...f.preparedProfile, nativeProviderPackAdmissionState: { + schema: "paperclip.native-provider-pack-admission-state.v1", state: "verified", admissionEpoch: randomUUID() }, + nativeProviderPackAdmission: { schema: "paperclip.native-provider-pack-admission.v1", stage: "session_admitted", + authority: "core_verified_selection", companyId: f.companyId, agentId: environment.current.agentId, + runId: f.runId, sessionId: f.identity.normalizedSessionId, runnerInstanceId: "artifact-fixture-runner", + runnerEnvironmentLeaseId: "artifact-fixture-lease", providerPackDigest: manifest.digest, + opencodeProxySha256: artifacts.opencodeProxy.sha256, sourceRevision: payload.runnerSourceRevision } }, + }).where(eq(heartbeatRuns.id, f.runId)); + return { ...f, original, manifest, launchRoot, providerArtifacts: { sourceRoot, manifest, launchRoot, accountUid: 1000 } }; + } + // Staging: two OpenCode per-turn runs had an accepted result, but object + // storage answered the backup upload with one 503 SlowDown ("Please reduce + // your request rate."). The upload was a single stream PUT that nothing + // retried, so the only provider-session backup was lost when the sandbox was + // released, and the follow-up could not resume. + it.each(["Codex backup", "OpenCode backup with provider artifacts"])("backs off and publishes when object storage throttles each %s upload and read-back once", async label => { + const f = label.startsWith("OpenCode") ? await artifactFixture() : await fixture(); + const objects = new Map(), throttled = new Set(), throttledReads = new Set(); let puts = 0, reads = 0; + const server = createServer((request, response) => { + const key = new URL(request.url!, "http://localhost").pathname; + const chunks: Buffer[] = []; + request.on("data", chunk => chunks.push(chunk)); + request.on("end", () => { + if (request.method === "PUT") { + puts++; + if (!throttled.has(key)) { + throttled.add(key); + response.writeHead(503, { "Content-Type": "application/xml" }).end( + "SlowDownPlease reduce your request rate.throttled"); + return; + } + objects.set(key, Buffer.concat(chunks)); + response.writeHead(200, { ETag: `"${createHash("md5").update(objects.get(key)!).digest("hex")}"` }).end(); + } else if (request.method === "GET" || request.method === "HEAD") { + const body = objects.get(key); + if (request.method === "GET" && body) { + reads++; + if (!throttledReads.has(key)) { + throttledReads.add(key); + response.writeHead(503, { "Content-Type": "application/xml" }).end( + "SlowDownPlease reduce your request rate.throttled-read"); + return; + } + } + if (!body) { response.writeHead(404, { "Content-Type": "application/xml" }).end("NoSuchKey"); return; } + response.writeHead(200, { "Content-Length": body.length, ETag: `"${createHash("md5").update(body).digest("hex")}"`, + "Content-Type": "application/octet-stream" }).end(request.method === "GET" ? body : undefined); + } else if (request.method === "DELETE") { + objects.delete(key); response.writeHead(204).end(); + } else response.writeHead(500).end(); + }); + }); + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + vi.stubEnv("AWS_ACCESS_KEY_ID", "fixture"); vi.stubEnv("AWS_SECRET_ACCESS_KEY", "fixture"); + const random = vi.spyOn(Math, "random").mockReturnValue(0); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const storage = createStorageService(createS3StorageProvider({ bucket: "bucket", region: "us-east-1", forcePathStyle: true, + endpoint: `http://127.0.0.1:${(server.address() as AddressInfo).port}` })); + try { + await persistNativeHarnessBackup({ ...f, storage }); + // Every object was refused once and then stored: the harness archive, and + // for OpenCode the provider artifact bundle too. + expect(throttled.size).toBe(label.startsWith("OpenCode") ? 2 : 1); + expect(puts).toBe(2 * throttled.size); + expect(objects.size).toBe(throttled.size); + // The verification read after each upload was refused once and repeated + // (the S3 client already resends a bodiless GET after SlowDown). + expect(throttledReads.size).toBe(throttled.size); + expect(reads).toBe(2 * throttled.size); + const [current] = await f.db.select().from(nativeHarnessBackups).where(and(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest), + eq(nativeHarnessBackups.status, "current"))); + expect(current).toBeDefined(); + const replacement = join(environment.current.runtimeRoot, randomUUID(), "restored-throttled"); ownedHomes.push(replacement); + expect(await restoreDurableNativeHarnessBackup({ ...f, storage, backupRoot: replacement })).toBe(true); + const providerDirectory = label.startsWith("OpenCode") ? "opencode" : "codex"; + expect(JSON.parse(await readFile(join(replacement, "current", providerDirectory, "sessions", "history.json"), "utf8"))).toEqual(f.identity); + } finally { + random.mockRestore(); warn.mockRestore(); + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + } + }); +}); diff --git a/server/src/services/native-runtime/native-provider-artifacts.ts b/server/src/services/native-runtime/native-provider-artifacts.ts index d7ff6b6a815..4d472794f41 100644 --- a/server/src/services/native-runtime/native-provider-artifacts.ts +++ b/server/src/services/native-runtime/native-provider-artifacts.ts @@ -300,6 +300,8 @@ export async function retainNativeProviderArtifacts(input: { body: createReadStream(encrypted), byteSize: reference.byteSize, sha256: reference.sha256.slice(7), + // A file source can be resent after a request-rate limit; a stream cannot. + sourceFile: encrypted, signal: input.signal, }); await receive(