diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 5a2f0494b60..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, @@ -3000,6 +3009,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 @@ -4637,7 +4657,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/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/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/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/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/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( 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/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/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/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-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); +}); 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-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 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 } : {}), diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index d6cd1441faf..67a44eedf1e 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",