fix(native-runtime): classify exited plugin Runner on restart reattachment (#23769)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native remote runs use restart recovery (`reattach_remote_runner`)
to reattach to an existing Runner after a Core restart or deploy
> - For `plugin_task` Runners, `verifyPluginRunnerTaskReattachment`
threw a raw `Error("Plugin Runner is not running")` when the Runner
exited before reattachment, and `migrateRunnerdStateRoot` did not wrap
that error with `withRemoteRunnerTurnProof`
> - Without a structured `RemoteRunnerRecoveryError`, the executor never
emitted `native.remote_runner_recovery_failed` and
`requestRestartInterruptedTurnRetry` could not recognize the exited
Runner, leaving the run permanently failed
> - This pull request updates `verifyPluginRunnerTaskReattachment` to
throw structured `RemoteRunnerRecoveryError` diagnostics (distinguishing
proven `executionStopped === true` exits from `probe_failed`) and wraps
the call in `migrateRunnerdStateRoot` with `withRemoteRunnerTurnProof`
> - The benefit is that stopped `plugin_task` Runners record consistent
exit diagnostics and turn-proof evidence during restart reattachment so
recovery policy can classify and retry them accurately

## Linked Issues or Issue Description

**What happened?**
When Core restarts while a `per_turn` `plugin_task` Runner is active and
the Runner exits before `reattach_remote_runner` runs,
`verifyPluginRunnerTaskReattachment` throws a raw `Error("Plugin Runner
is not running")`. The executor does not emit
`native.remote_runner_recovery_failed`, does not attach
`providerTurnIssued: false` from the controller journal, and
`requestRestartInterruptedTurnRetry` fails to recognize the exited
Runner.

**Expected behavior**
When `status.executionStopped === true`,
`verifyPluginRunnerTaskReattachment` throws a
`RemoteRunnerRecoveryError` with `stage: "process_verification"` and
`reason: "process_not_running"`, attaches best-effort redacted
exited-runner diagnostics from `read_state` when
`status.sessionStateAvailable === true`, and `migrateRunnerdStateRoot`
wraps the error with `withRemoteRunnerTurnProof(error, scoped)`. When
the status probe returns a non-status result or a non-running phase
without `executionStopped === true`, it throws
`RemoteRunnerRecoveryError` with `reason: "probe_failed"` instead of
falsely proving exit.

**Steps to reproduce**
1. Start a native run backed by a `plugin_task` Runner with a controller
journal that proves no turn was issued.
2. Restart Core and trigger `reattach_remote_runner` after the plugin
task reports `executionStopped: true`.
3. Observe that `verifyPluginRunnerTaskReattachment` throws a raw
`Error("Plugin Runner is not running")` and
`executePaperclipNativeSession` does not emit
`native.remote_runner_recovery_failed`.

**Paperclip version or commit**
`f4baaa4f48` (`master`)

**Deployment mode**
Self-hosted server

**Installation method**
Built from source (pnpm dev / pnpm build)

## What Changed

- Updated `verifyPluginRunnerTaskReattachment` in
`server/src/services/native-runtime/plugin-runner-task.ts` to:
- Throw `RemoteRunnerRecoveryError({ stage: "process_verification",
reason: "probe_failed" })` when the status probe does not return `kind:
"status"` or reports `phase !== "running"` without `executionStopped ===
true`.
- Throw `RemoteRunnerRecoveryError({ stage: "process_verification",
reason: "process_not_running", ... })` when `status.executionStopped ===
true`, attaching best-effort redacted `describeExitedRemoteRunner` and
`describeExitedRemoteRunnerReason` diagnostics from `read_state` when
`status.sessionStateAvailable === true` and the identity matches.
- Wrapped `verifyPluginRunnerTaskReattachment(...)` in
`migrateRunnerdStateRoot`
(`server/src/services/native-runtime/native-session-executor.ts`) with
`withRemoteRunnerTurnProof(error, scoped)`, matching non-plugin sandbox
reattachment.
- Added unit tests in
`server/src/services/native-runtime/plugin-runner-task.test.ts` covering
stopped tasks with and without `sessionStateAvailable`, best-effort
`read_state` failure/mismatch, and `probe_failed` responses.
- Added an integration-style executor test in
`server/src/services/native-runtime/native-session-executor.test.ts`
verifying `providerTurnIssued: false` and
`native.remote_runner_recovery_failed` emission on
`reattach_remote_runner` for a stopped `plugin_task`.

## Verification

- Verified red-before-fix failures on both new test suites (`expected
Error: Plugin Runner is not running to be an instance of
RemoteRunnerRecoveryError`).
- `pnpm --dir server exec vitest run
src/services/native-runtime/plugin-runner-task.test.ts` — 120/120
passed.
- `pnpm --dir server exec vitest run
src/services/native-runtime/native-session-executor.test.ts -t
"classifies a stopped plugin_task on reattach_remote_runner|reattaches a
surviving plugin task through its owner"` — 6/6 passed.
- `pnpm --dir server typecheck` — passed.

## Risks

- Low risk. The change is scoped to `verifyPluginRunnerTaskReattachment`
and its `plugin_task` reattachment caller in `migrateRunnerdStateRoot`.
- Any caller or log parser that previously matched the unstructured
`"Plugin Runner is not running"` string now receives the standard
`RemoteRunnerRecoveryError`
(`runner_remote_process_identity_unavailable`) used by other remote
Runner reattachment paths. No existing tests or code in the repository
matched that string.
- Terminal phases without `executionStopped === true` report `reason:
"probe_failed"` rather than `process_not_running`, preserving the
invariant that only explicit `executionStopped === true` proves the task
and descendants stopped.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-04 14:09:30 -06:00
1 parent 244e20a293
commit 596bb8a512
4 files changed
+315 -9

No files matched your search

@@ -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" } };
@@ -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");
@@ -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<unknown> => {
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<unknown> => {
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<unknown> => {
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<unknown> => {
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<unknown> => 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<unknown> => {
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<unknown> => {
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,
});
});
});
@@ -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<string, unknown>,
identity: Record<string, unknown>,
): 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<unknown>, identity: unknown,
): Promise<void> {
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<RemoteRunnerRecoveryDiagnostic> = {};
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<Record<string, string>>;
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");