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 5be6fcb8072..5bf7b7850ae 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -20733,6 +20733,95 @@ describe("runnerd provider runtime wiring", () => { } finally { portable?.mockRestore(); } }); + it("classifies a stopped plugin_task on reattach_remote_runner with turn proof and emits native.remote_runner_recovery_failed", async () => { + const current = scopedNativeExecution("plugin-stopped-reattach"); + const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!, + runnerInstanceId: "plugin-runner", environmentLeaseId: "same-task-lease", turnId: "admitted-turn", itemId: "admitted-item" }; + const root = await initializeScopedRunnerRoot(current, identity.runnerInstanceId); + await mkdir(join(root, "control-plane"), { recursive: true }); + await writeFile(join(root, "control-plane/control-plane-state.json"), JSON.stringify({ + schema: "paperclip.runner.durable.control-plane-state.v2", + identity, + connectionCount: 1, + commands: [{ type: "run.prepare", status: "completed" }, { type: "session.open", status: "completed" }], + committedEvents: [{ sourceSeq: 1, eventType: "session.started" }], + ackedSourceSeq: 1, + })); + const task = vi.fn(async (operation: any) => { + environmentTaskOperationSchema.parse(operation); + if (operation.kind === "status") { + return { kind: "status", taskId: "same-task", phase: "completed", executionStopped: true, sessionStateAvailable: true }; + } + if (operation.kind === "read_state") { + return { + kind: "state", + taskId: "same-task", + state: { + ...durableRunnerState(identity, "recoverable_failure"), + recoverableFailure: "transport_reconnect_grace_exceeded", + outbox: [], + }, + }; + } + throw new Error(`unexpected operation: ${operation.kind}`); + }); + const onEvent = vi.fn(async () => undefined); + const db = leaseDb(current, { + leaseOwner: "controller", + leaseExpiresAt: new Date(Date.now() + 60_000), + controllerBootId: "successor", + controllerPid: process.pid, + controllerGeneration: 2, + attempt: 1, + recoveryState: "awaiting_runner_reattach", + recoveryHistory: [{ disposition: "reattach_remote_runner", controllerGeneration: 2, providerAttempt: 1 }], + }); + + const caught = await executePaperclipNativeSession({ + db, + execution: current, + runnerInstanceId: identity.runnerInstanceId, + useRunnerd: true, + runnerIngressAuthorized: true, + onEvent, + runnerExecutionTarget: { + kind: "remote", + transport: "sandbox", + remoteCwd: ".", + leaseId: identity.environmentLeaseId, + runnerTask: task, + }, + leaseOwner: "controller", + restartRecovery: { + kind: "reattach_remote_runner", + runId: current.binding.runId, + leaseOwner: "controller", + controllerGeneration: 2, + providerAttempt: 1, + restartKind: "hard", + recoveryRequestId: null, + remote: { kind: "plugin_task", leaseId: identity.environmentLeaseId }, + }, + }).catch(error => error); + + const expectedDiagnostic = { + stage: "process_verification", + reason: "process_not_running", + providerTurnIssued: false, + runnerLifecycle: "recoverable_failure", + runnerSettled: true, + runnerRecoverableFailure: "transport_reconnect_grace_exceeded", + }; + expect(caught).toBeInstanceOf(RemoteRunnerRecoveryError); + expect(readRemoteRunnerRecoveryError(caught)).toEqual(expectedDiagnostic); + expect(onEvent).toHaveBeenCalledWith({ + eventType: "native.remote_runner_recovery_failed", + level: "error", + message: "Could not verify the existing remote runner.", + payload: { remoteRunnerRecovery: expectedDiagnostic }, + }); + }); + it.each([true, false])("routes OpenCode credential events with live writeback capability %s", async enabled => { const current = scopedNativeExecution("credential-capability"); const run: NativeExecutionInput = { ...current, provider: { kind: "opencode", model: "openai/test" } }; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 4fd0f99a82a..1cd49c164fa 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -6752,8 +6752,12 @@ async function migrateRunnerdStateRoot(input: { throw new Error("native_plugin_recovery_lease_mismatch"); } const taskId = await assertPluginTaskReattachmentBinding(input, target, identity); - await verifyPluginRunnerTaskReattachment(operation => target.runnerTask!(operation, - taskId ? { expectedTaskId: taskId } : undefined), identity); + try { + await verifyPluginRunnerTaskReattachment(operation => target.runnerTask!(operation, + taskId ? { expectedTaskId: taskId } : undefined), identity); + } catch (error) { + throw withRemoteRunnerTurnProof(error, scoped); + } return; } try { @@ -17284,6 +17288,7 @@ async function createRunnerdBackendWithinSessionClaim( savePluginRunnerCheckpoint(root, state, state); }); }, onDispatched: input.onTaskDispatched, + mapReattachmentError: error => withRemoteRunnerTurnProof(error, root), }; if (input.remoteWarmRecovery?.releasedSource && description.releaseResumeVersion !== 1) throw new Error("Plugin Runner release/resume unavailable"); if (input.execution.session.lifecyclePolicy.mode === "warm" && (!credentials.accountIdentity || description.warmTaskVersion !== 1)) throw new Error("Plugin warm task capability or account unavailable"); 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 32962aeab0f..d1eb93f843a 100644 --- a/server/src/services/native-runtime/plugin-runner-task.test.ts +++ b/server/src/services/native-runtime/plugin-runner-task.test.ts @@ -4,8 +4,9 @@ import { describe, expect, it, vi } from "vitest"; import WebSocket from "ws"; import type { RunnerProviderLaunchRequirements } from "@paperclipai/paperclip-runner"; import { runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessLaunchSpec } from "../../vendor/paperclip-runner/index.js"; -import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js"; +import { createPluginRunnerTaskOwner, verifyPluginRunnerTaskReattachment } from "./plugin-runner-task.js"; import { NativeExecutionContext } from "./native-execution-context.js"; +import { RemoteRunnerRecoveryError, readRemoteRunnerRecoveryError } from "./remote-runner-recovery-diagnostics.js"; const sockets = vi.hoisted(() => ({ create: null as (() => unknown) | null })); vi.mock("ws", async importOriginal => { @@ -1392,3 +1393,158 @@ describe("plugin task configured environment", () => { expect(owner.configuredEnvironmentDelivered()).toBeUndefined(); }); }); + +describe("verifyPluginRunnerTaskReattachment", () => { + it("throws structured process_not_running with exited diagnostics when stopped with sessionStateAvailable", async () => { + const task = vi.fn(async (operation: any): Promise => { + if (operation.kind === "status") { + return { kind: "status", taskId: "task", phase: "completed", executionStopped: true, sessionStateAvailable: true }; + } + if (operation.kind === "read_state") { + return { + kind: "state", + taskId: "task", + state: { + schema: "paperclip.runner.durable.state.v1", + ...requirements.identity, + lifecycle: "recoverable_failure", + recoverableFailure: "transport_reconnect_grace_exceeded", + diagnostics: ["Authorization: Bearer secret-token-value"], + outbox: [], + }, + }; + } + throw new Error(`unexpected operation: ${operation.kind}`); + }); + + const caught = await verifyPluginRunnerTaskReattachment(task, requirements.identity).catch(error => error); + expect(caught).toBeInstanceOf(RemoteRunnerRecoveryError); + expect((caught as Error).message).toBe("runner_remote_process_identity_unavailable"); + expect(readRemoteRunnerRecoveryError(caught)).toEqual({ + stage: "process_verification", + reason: "process_not_running", + runnerLifecycle: "recoverable_failure", + runnerSettled: true, + runnerRecoverableFailure: "transport_reconnect_grace_exceeded", + runnerDiagnostics: [expect.not.stringContaining("secret-token-value")], + }); + expect(task.mock.calls.map(([op]) => op.kind)).toEqual(["status", "read_state"]); + }); + + it("throws structured process_not_running without reading state when sessionStateAvailable is false", async () => { + const task = vi.fn(async (operation: any): Promise => { + if (operation.kind === "status") { + return { kind: "status", taskId: "task", phase: "failed", executionStopped: true, sessionStateAvailable: false }; + } + throw new Error(`unexpected operation: ${operation.kind}`); + }); + + const caught = await verifyPluginRunnerTaskReattachment(task, requirements.identity).catch(error => error); + expect(caught).toBeInstanceOf(RemoteRunnerRecoveryError); + expect(readRemoteRunnerRecoveryError(caught)).toEqual({ + stage: "process_verification", + reason: "process_not_running", + }); + expect(task.mock.calls.map(([op]) => op.kind)).toEqual(["status"]); + }); + + it("still throws process_not_running when best-effort read_state fails or mismatches identity", async () => { + const failingTask = vi.fn(async (operation: any): Promise => { + if (operation.kind === "status") { + return { kind: "status", taskId: "task", phase: "completed", executionStopped: true, sessionStateAvailable: true }; + } + throw new Error("state read transient failure"); + }); + const caughtFailed = await verifyPluginRunnerTaskReattachment(failingTask, requirements.identity).catch(error => error); + expect(caughtFailed).toBeInstanceOf(RemoteRunnerRecoveryError); + expect(readRemoteRunnerRecoveryError(caughtFailed)).toEqual({ + stage: "process_verification", + reason: "process_not_running", + }); + + const mismatchedTask = vi.fn(async (operation: any): Promise => { + if (operation.kind === "status") { + return { kind: "status", taskId: "task", phase: "completed", executionStopped: true, sessionStateAvailable: true }; + } + return { + kind: "state", + taskId: "task", + state: { + schema: "paperclip.runner.durable.state.v1", + ...requirements.identity, + runId: "different-run", + lifecycle: "failed", + outbox: [], + }, + }; + }); + const caughtMismatch = await verifyPluginRunnerTaskReattachment(mismatchedTask, requirements.identity).catch(error => error); + expect(caughtMismatch).toBeInstanceOf(RemoteRunnerRecoveryError); + expect(readRemoteRunnerRecoveryError(caughtMismatch)).toEqual({ + stage: "process_verification", + reason: "process_not_running", + }); + }); + + it.each([ + ["non-status response", { kind: "accepted", taskId: "task" }], + ["non-running phase without executionStopped", { kind: "status", taskId: "task", phase: "completed", executionStopped: false }], + ["malformed status payload", { kind: "status", taskId: "" }], + ])("reports probe_failed instead of process_not_running for %s", async (_label, response) => { + const task = vi.fn(async (_operation: any): Promise => response); + const caught = await verifyPluginRunnerTaskReattachment(task, requirements.identity).catch(error => error); + expect(caught).toBeInstanceOf(RemoteRunnerRecoveryError); + expect(readRemoteRunnerRecoveryError(caught)).toEqual({ + stage: "process_verification", + reason: "probe_failed", + }); + expect(task.mock.calls.map(([op]) => op.kind)).toEqual(["status"]); + }); + + it("attaches probe_transport_failed when the status RPC rejects", async () => { + const rpcError = new Error("plugin rpc transport timeout"); + const task = vi.fn(async (): Promise => { + throw rpcError; + }); + const caught = await verifyPluginRunnerTaskReattachment(task, requirements.identity).catch(error => error); + expect(caught).toBe(rpcError); + expect(readRemoteRunnerRecoveryError(caught)).toEqual({ + stage: "process_verification", + reason: "probe_transport_failed", + }); + }); + + it("maps adoption activation reattachment errors through mapReattachmentError", async () => { + const task = vi.fn(async (operation: any): Promise => { + if (operation.kind === "status") { + return { kind: "status", taskId: "task", phase: "completed", executionStopped: true, sessionStateAvailable: false }; + } + throw new Error(`unexpected operation: ${operation.kind}`); + }); + const mapped = new RemoteRunnerRecoveryError({ + stage: "process_verification", + reason: "process_not_running", + providerTurnIssued: false, + }); + const mapReattachmentError = vi.fn(() => mapped); + const owner = createPluginRunnerTaskOwner({ + taskId: "task", + task, + projectIds: [], + harness: "codex", + adoptIdentity: requirements.identity, + mapReattachmentError, + }); + const registration = await owner.registration({} as never, "run"); + registration.activate(); + const caught = await registration.ready().catch(error => error); + await registration.release("detach"); + expect(mapReattachmentError).toHaveBeenCalledOnce(); + expect(caught).toBe(mapped); + expect(readRemoteRunnerRecoveryError(caught)).toEqual({ + stage: "process_verification", + reason: "process_not_running", + providerTurnIssued: false, + }); + }); +}); diff --git a/server/src/services/native-runtime/plugin-runner-task.ts b/server/src/services/native-runtime/plugin-runner-task.ts index eeffbd87f49..685c1dd303c 100644 --- a/server/src/services/native-runtime/plugin-runner-task.ts +++ b/server/src/services/native-runtime/plugin-runner-task.ts @@ -7,22 +7,73 @@ import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparati type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerReleaseResumeOutcome, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent, } from "../../vendor/paperclip-runner/index.js"; import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js"; +import { redactSensitiveText } from "../../redaction.js"; import type { NativeExecutionContext } from "./native-execution-context.js"; +import { + RemoteRunnerRecoveryError, + attachRemoteRunnerRecoveryDiagnostic, + describeExitedRemoteRunner, + describeExitedRemoteRunnerReason, + readRemoteRunnerRecoveryError, + type RemoteRunnerRecoveryDiagnostic, +} from "./remote-runner-recovery-diagnostics.js"; const RELAUNCH_TICKET_TTL_MS = 60_000; +function pluginRunnerStateMatchesIdentity( + state: Record, + identity: Record, +): boolean { + return state.schema === "paperclip.runner.durable.state.v1" + && Object.entries(identity).every(([key, value]) => state[key] === value); +} + export async function verifyPluginRunnerTaskReattachment( task: (operation: unknown) => Promise, identity: unknown, ): Promise { const operation = environmentTaskOperationSchema.parse({ kind: "read_state", identity }); if (operation.kind !== "read_state") throw new Error("Plugin Runner recovery identity unavailable"); - const status = environmentTaskResultSchema.parse(await task({ kind: "status" })); - if (status.kind !== "status" || status.executionStopped || status.phase !== "running") { - throw new Error("Plugin Runner is not running"); + let rawStatus: unknown; + try { + rawStatus = await task({ kind: "status" }); + } catch (error) { + if (readRemoteRunnerRecoveryError(error)) throw error; + throw attachRemoteRunnerRecoveryDiagnostic(error, { + stage: "process_verification", + reason: "probe_transport_failed", + }); + } + const parsedStatus = environmentTaskResultSchema.safeParse(rawStatus); + if (!parsedStatus.success || parsedStatus.data.kind !== "status") { + throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "probe_failed" }); + } + const status = parsedStatus.data; + if (status.executionStopped === true) { + let exitedDiagnostics: Partial = {}; + if (status.sessionStateAvailable === true) { + try { + const result = environmentTaskResultSchema.parse(await task(operation)); + if (result.kind === "state" && pluginRunnerStateMatchesIdentity(result.state, operation.identity)) { + exitedDiagnostics = { + ...describeExitedRemoteRunner(result.state), + ...describeExitedRemoteRunnerReason(result.state, redactSensitiveText), + }; + } + } catch { + // Best-effort diagnostics: keep process_not_running even if state read fails. + } + } + throw new RemoteRunnerRecoveryError({ + stage: "process_verification", + reason: "process_not_running", + ...exitedDiagnostics, + }); + } + if (status.phase !== "running") { + throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "probe_failed" }); } const result = environmentTaskResultSchema.parse(await task(operation)); - if (result.kind !== "state" || result.state.schema !== "paperclip.runner.durable.state.v1" - || Object.entries(operation.identity).some(([key, value]) => result.state[key] !== value)) { + if (result.kind !== "state" || !pluginRunnerStateMatchesIdentity(result.state, operation.identity)) { throw new Error("Plugin Runner adoption identity mismatch"); } } @@ -64,6 +115,7 @@ export function createPluginRunnerTaskOwner(input: { configuredEnvironmentVersion?: 1; configuredEnvironment?: Readonly>; adoptIdentity?: DurableRecoveryIdentity; + mapReattachmentError?: (error: unknown) => unknown; }) { const taskId = input.taskId; if (!taskId) throw new Error("Plugin Runner physical task unavailable"); @@ -417,7 +469,11 @@ export function createPluginRunnerTaskOwner(input: { if (desired && Object.entries(input.adoptIdentity).some(([key, value]) => desired[key as keyof DurableRecoveryIdentity] !== value)) { throw new Error("Plugin Runner adoption identity mismatch"); } - await verifyPluginRunnerTaskReattachment(input.task, input.adoptIdentity); + try { + await verifyPluginRunnerTaskReattachment(input.task, input.adoptIdentity); + } catch (error) { + throw input.mapReattachmentError ? input.mapReattachmentError(error) : error; + } } else if (!preparedIdentity || Object.entries(preparedIdentity).some(([key, value]) => desired[key as keyof DurableRecoveryIdentity] !== value) || ["runnerInstanceId", "environmentLeaseId", "normalizedSessionId"].some(key => desired[key as keyof DurableRecoveryIdentity] !== input.adoptIdentity![key as keyof DurableRecoveryIdentity])) { throw new Error("Plugin Runner adoption identity mismatch");