diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index f996214e8c3..027e3595e38 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -154,6 +154,32 @@ again only on the parked build, and do not add `runner` to the result. Older strict Core schemas reject `resumeRelaunchedRunnerVersion` in a description, so advertise it only to a Core version that supports it. +A provider can return `resumeIdentityVersion: 1` from `describe`. Use it only +for a provider that stops a released Runner, so that every `resume` starts the +Runner again. Core then rotates the session to the claimant run before it calls +`resume`, and adds `runner: { runId, turnId, itemId }` to `resume`. These are the +claimant run's identity fields. The other identity fields do not change. With +this field, the provider must: + +- Move the source Runner state (`runner-state.json`) out of the Runner state + directory into an archive, so that the Runner creates new state. +- Start the Runner as the claimant identity with the fresh `bootstrapTicket`. +- Return `runner: { version, digest }` and `archivedState` (the archived Runner + state) on the `resumed` result. + +Core accepts the archived state only when it is the source's settled cut: the +`suspended` lifecycle, or the `ready` lifecycle with an empty outbox, every +event acknowledged and no command in progress. Core then sends one ordinary +`run.attach` with no authority hand-off. A retry with the same source, ticket +and `runner` must return the original result and must not start a second +Runner. Without `runner` on `resume`, keep the claimant handover above. + +While a released task can still be resumed, its `status` must report +`executionStopped: false`, even when its Runner process is stopped. Core +replaces a reused task whose `status` reports a stop, and then cannot resume +the released session on it. Report the stop only when the task can no longer +resume. + The `resume` result has a closed `outcome`: - `resumed`: the same logical session is exclusively reserved for this claimant, diff --git a/packages/paperclip-runner/src/backends/harness-driver-backend.ts b/packages/paperclip-runner/src/backends/harness-driver-backend.ts index 899106d04e5..a98fc96b50a 100644 --- a/packages/paperclip-runner/src/backends/harness-driver-backend.ts +++ b/packages/paperclip-runner/src/backends/harness-driver-backend.ts @@ -537,6 +537,11 @@ class HarnessNativeSession implements NativeSession { return this.#session.release?.() ?? false; } + async retireReleasedController(): Promise<{ source: DurableRecoveryIdentity; runner: { version: string; digest: string } } | null> { + this.#assertProtocolIntegrity(); + return this.#session.retireReleasedController?.() ?? null; + } + async detachControllerForRestart(): Promise { if (this.#session.detachControllerForRestart === undefined) return; await this.#session.detachControllerForRestart(); diff --git a/packages/paperclip-runner/src/contracts/harness-driver.ts b/packages/paperclip-runner/src/contracts/harness-driver.ts index 494fc7da83f..1f019d523f7 100644 --- a/packages/paperclip-runner/src/contracts/harness-driver.ts +++ b/packages/paperclip-runner/src/contracts/harness-driver.ts @@ -672,6 +672,7 @@ export interface HarnessSession { boundarySnapshot?(sourceSeq: number): PersistedHarnessSession | null; /** Return the confirmed released source, or false when active use was not released. */ release?(): Promise; + retireReleasedController?(): Promise<{ source: DurableRecoveryIdentity; runner: { version: string; digest: string } } | null>; /** Relinquish controller authority without semantically closing the session. */ detachControllerForRestart?(): Promise; close(input: { reason: string; force?: boolean; retainUnsettledRemoteRunner?: boolean }): Promise; diff --git a/packages/paperclip-runner/src/contracts/native-session-backend.ts b/packages/paperclip-runner/src/contracts/native-session-backend.ts index 2973f95d232..d7a69878dc8 100644 --- a/packages/paperclip-runner/src/contracts/native-session-backend.ts +++ b/packages/paperclip-runner/src/contracts/native-session-backend.ts @@ -245,6 +245,7 @@ export interface NativeSession { beginRunAttachment?(input: { identity: NativeRunIdentity }): boolean; /** Return the confirmed released source, or false when active use was not released. */ release?(): Promise; + retireReleasedController?(): Promise<{ source: DurableRecoveryIdentity; runner: { version: string; digest: string } } | null>; /** Relinquish controller authority without suspending provider execution. */ detachControllerForRestart?(): Promise; events(input?: { afterCursor?: string | null }): AsyncIterable; diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts index 552b76897ac..c44db971979 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts @@ -220,7 +220,9 @@ it("resumes a checkpoint saved for the parked build on a relaunched newer build, expectedRunnerVersion: checkpoint.runnerVersion, expectedRunnerDigest: checkpoint.runnerDigest }); claiming.setCheckpointPersistence(async value => { checkpoint = value; }); const ticket = claiming.issueBootstrapTicket(); + expect(claiming.expectedRunner()).toEqual({ version: expectedRunnerVersion, digest: expectedRunnerDigest }); claiming.acceptRelaunchedRunner(ticket, relaunched); + expect(claiming.expectedRunner()).toEqual(relaunched); await claiming.flushCheckpoint(); expect(checkpoint).toMatchObject({ runnerVersion: relaunched.version, runnerDigest: relaunched.digest }); await claiming.stop(); diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index b73c8bb00b9..e621888be18 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -2861,6 +2861,10 @@ export class DurablePrpControlPlane { ); } + expectedRunner(): { version: string; digest: string } { + return { version: this.#expectedRunnerVersion, digest: this.#expectedRunnerDigest }; + } + acceptRelaunchedRunner( bootstrapTicket: string, runner: { version: string; digest: string }, diff --git a/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts b/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts index 591621100c9..a8ca08fbd6b 100644 --- a/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts +++ b/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts @@ -27,6 +27,7 @@ export interface RunnerExecutionDriver { releasedSource?: DurableRecoveryIdentity; releasedSourceRunner?: { version: string; digest: string }; }; + relaunchReleasedRunner?: DurableRecoveryIdentity; /** Current authenticated lease/checkpoint-writer owner; may change during warm reuse. */ authorityRunId?: string; /** Own provider configuration and file preparation in the execution environment. */ diff --git a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts index b9ed3faba50..b20f2c9f4a8 100644 --- a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts +++ b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts @@ -81,6 +81,7 @@ export interface CodexAppServerTransport { runnerExitConfirmed?(): boolean; /** Return the confirmed released source, or false when active use was not released. */ release?(): Promise; + retireReleasedController?(): Promise<{ source: DurableRecoveryIdentity; runner: { version: string; digest: string } } | null>; /** Relinquish controller authority while leaving durable runner work alive. */ detachControllerForRestart?(): Promise; /** True when this transport recovers a session only to stop it. */ 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 2f763b1d92e..451f7e68eb1 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 @@ -800,6 +800,7 @@ export class CodexAppServerDriver implements HarnessDriver { } catch (error) { await cancellation.close(isTransientRunnerRecoveryFailure(error)).catch(() => {}); if (error instanceof NativeSessionProtocolIntegrityError) throw error; + if (error instanceof Error && error.message === "native_runner_reuse_unavailable") throw error; if (options.signal.aborted) options.signal.throwIfAborted(); // 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 diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts index 4c6660624ef..dc41ec4b194 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.provider-turn.test.ts @@ -578,3 +578,19 @@ describe("Codex app-server driver boundary snapshots for provider-started turns" await session.close({ reason: "fixture complete" }); }); }); + +it("keeps a refused relaunch as its own error so the caller can start ordinary recovery", async () => { + const first = new FakeCodexTransport(); + const second = new FakeCodexTransport(); + const third = new FakeCodexTransport(); + const driver = makeDriver([first, second, third]); + const original = await driver.openSession({ + runId: "provider-turn", normalizedSessionId: "provider-turn-session", workingDirectory: WORKSPACE, + }); + const checkpoint = await original.snapshot(); + await original.close({ reason: "released" }); + second.rejectMethods.set("thread/resume", new Error("native_runner_reuse_unavailable")); + await expect(driver.recoverSession!(checkpoint)).rejects.toThrow(/^native_runner_reuse_unavailable$/); + third.rejectMethods.set("thread/resume", new Error("native_runner_other_failure")); + await expect(driver.recoverSession!(checkpoint)).resolves.toMatchObject({ recovered: false, reason: expect.stringContaining("native_runner_other_failure") }); +}); diff --git a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts index 97f64423f94..3cd5ca8efee 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts @@ -980,6 +980,11 @@ export class CodexHarnessSession return this.transport.release?.() ?? false; } + async retireReleasedController(): Promise<{ source: DurableRecoveryIdentity; runner: { version: string; digest: string } } | null> { + this.assertProtocolIntegrity(); + return this.transport.retireReleasedController?.() ?? null; + } + async detachControllerForRestart(): Promise { if (this.transport.detachControllerForRestart === undefined) return; await this.transport.detachControllerForRestart(); diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index 9431ee4330d..247ccd5ead8 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -98,6 +98,8 @@ export { resolveGrokEffort } from "./drivers/acpx/grok-effort.js"; export * from "./drivers/runner-tool-bridge.js"; export { createRunnerdCodexTransport, + isSettledReleasedRunnerCut, + revertUnattachedRelaunchRotation, probeNativeRunnerEnvironment, NativeEnvironmentProbeCleanupError, runnerCodexDynamicToolsFit, diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index 92b0d34f86d..cf2bf64f793 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -4,7 +4,7 @@ import { runnerLaunchRequirementsDigest, type RunnerProviderLaunchRequirements, } from "./runner-provider-launch.js"; -import { coldAdmissionTimeoutMs, describeRunnerCommandStall, RUNNER_MAX_STOPPED_CREDIT_MS, RUNNER_POST_STOP_GRACE_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js"; +import { coldAdmissionTimeoutMs, describeRunnerCommandStall, isSettledReleasedRunnerCut, revertUnattachedRelaunchRotation, RUNNER_MAX_STOPPED_CREDIT_MS, RUNNER_POST_STOP_GRACE_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js"; import { configuredEnvironmentProjection } from "../configured-environment.js"; import { chmod, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, truncate, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; @@ -2149,6 +2149,90 @@ it.each(["before", "after"] as const)( }, ); +describe("a rotation for a released Runner that the host starts again", () => { + const priorIdentity = { + runnerInstanceId: "runner-relaunch-rotation", environmentLeaseId: "lease-relaunch-rotation", + runId: "run-relaunch-prior", normalizedSessionId: "session-relaunch-rotation", + turnId: "turn-relaunch-prior", itemId: "item-relaunch-prior", + }; + const desiredIdentity = { ...priorIdentity, runId: "run-relaunch-next", turnId: "turn-relaunch-next", itemId: "item-relaunch-next" }; + const settled = { + schema: "paperclip.runner.durable.state.v1", ...priorIdentity, lifecycle: "ready", nextSourceSeq: 8, ackedSourceSeq: 7, + outbox: [], pendingTerminalDelivery: null, processedCommands: { "command-a": { status: "completed" } }, + }; + + it("moves only the control plane, and resumes the same archive on a retry", async () => { + const root = await mkdtemp(join(tmpdir(), "paperclip-relaunch-rotation-")); + const controlPlaneState = { schema: "paperclip.runner.durable.control-plane-state.v1", identity: priorIdentity }; + const unavailable = vi.fn(async () => { throw new Error("the host archives this state"); }); + try { + await mkdir(join(root, "control-plane"), { recursive: true }); + await writeFile(join(root, "control-plane", "control-plane-state.json"), JSON.stringify(controlPlaneState)); + const archive = { archivedByLaunch: true as const, read: unavailable, archive: unavailable }; + await expect(runnerdRecoveryInternals.rotateAuthorityEpoch(root, controlPlaneState, desiredIdentity, archive)) + .resolves.toEqual(controlPlaneState); + await expect(stat(join(root, "control-plane"))).rejects.toMatchObject({ code: "ENOENT" }); + const epochs = await readdir(join(root, "authority-epochs")); + expect(epochs).toHaveLength(1); + expect(await readdir(join(root, "authority-epochs", epochs[0]!))).toEqual(["control-plane"]); + await expect(runnerdRecoveryInternals.rotateAuthorityEpoch(root, controlPlaneState, desiredIdentity, archive)) + .resolves.toEqual(controlPlaneState); + expect(unavailable).not.toHaveBeenCalled(); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("puts the source authority back only when no Runner attached to the rotated run", async () => { + for (const target of [ + { state: { schema: "paperclip.runner.external-control-plane-state.v1", identity: desiredIdentity }, reverted: true }, + { state: { schema: "paperclip.runner.durable.control-plane-state.v1", identity: desiredIdentity, connectionCount: 0, ackedSourceSeq: 0, + committedEvents: [], leases: {}, tickets: { ticket: { usedAt: null } } }, reverted: true }, + { state: { schema: "paperclip.runner.durable.control-plane-state.v1", identity: desiredIdentity, connectionCount: 1, ackedSourceSeq: 3, + committedEvents: [], leases: {}, tickets: { ticket: { usedAt: "2099-01-01T00:00:00.000Z" } } }, reverted: false }, + { state: { schema: "paperclip.runner.external-control-plane-state.v1", identity: priorIdentity }, reverted: false }, + ]) { + const root = await mkdtemp(join(tmpdir(), "paperclip-relaunch-revert-")); + const source = { schema: "paperclip.runner.durable.control-plane-state.v1", identity: priorIdentity }; + try { + await mkdir(join(root, "control-plane"), { recursive: true }); + await writeFile(join(root, "control-plane", "control-plane-state.json"), JSON.stringify(source)); + const unavailable = async () => { throw new Error("the host archives this state"); }; + await runnerdRecoveryInternals.rotateAuthorityEpoch(root, source, desiredIdentity, + { archivedByLaunch: true, read: unavailable, archive: unavailable }); + await mkdir(join(root, "control-plane"), { recursive: true }); + await writeFile(join(root, "control-plane", "control-plane-state.json"), JSON.stringify(target.state)); + expect(revertUnattachedRelaunchRotation(root, priorIdentity)).toBe(target.reverted); + const active = JSON.parse(await readFile(join(root, "control-plane", "control-plane-state.json"), "utf8")); + expect(active.identity).toEqual(target.reverted ? priorIdentity : target.state.identity); + expect(await readdir(join(root, "authority-epochs"))).toHaveLength(target.reverted ? 0 : 1); + } finally { + await rm(root, { recursive: true, force: true }); + } + } + }); + + it("accepts a stopped Runner's ready cut only when nothing is left in flight", () => { + expect(isSettledReleasedRunnerCut(settled, priorIdentity)).toBe(true); + expect(isSettledReleasedRunnerCut({ schema: settled.schema, ...priorIdentity, lifecycle: "suspended" }, priorIdentity)).toBe(true); + for (const changed of [ + { outbox: [{ sourceSeq: 8 }] }, + { ackedSourceSeq: 6 }, + { nextSourceSeq: undefined }, + { processedCommands: { "command-a": { status: "pending" } } }, + { processedCommands: { "command-a": { status: "indeterminate" } } }, + { warmTransition: { transitionId: "transition" } }, + { pendingTerminalDelivery: { turnId: "turn" } }, + { pendingProviderCleanup: { turnId: "turn" } }, + { lifecycle: "connecting" }, + { schema: "paperclip.runner.durable.state.v0" }, + { runId: desiredIdentity.runId }, + ]) { + expect(isSettledReleasedRunnerCut({ ...settled, ...changed }, priorIdentity)).toBe(false); + } + }); +}); + describe("authority rotation after the prior controller state is restored", () => { const priorIdentity = { runnerInstanceId: "runner-restored-rotation", diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index ab98fa86a33..fdae1e47985 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -40,6 +40,7 @@ import { readFileSync, readdirSync, renameSync, + rmdirSync, rmSync, statSync, writeFileSync, @@ -235,6 +236,22 @@ function assertSuspendedRunnerState( } } +export function isSettledReleasedRunnerCut( + state: Record, + expected: DurableRecoveryIdentity, +): boolean { + if (state.schema !== "paperclip.runner.durable.state.v1" || !recoveryIdentityMatches(state, expected)) return false; + if (state.lifecycle === "suspended") return true; + return state.lifecycle === "ready" + && Array.isArray(state.outbox) && state.outbox.length === 0 + && Number.isSafeInteger(state.nextSourceSeq) && state.ackedSourceSeq === Math.max(0, Number(state.nextSourceSeq) - 1) + && state.warmTransition === undefined + && (state.pendingTerminalDelivery ?? null) === null + && (state.pendingProviderCleanup ?? null) === null + && Object.values(record(state.processedCommands)).every(command => + !["pending", "indeterminate"].includes(String(record(command).status))); +} + function assertRealDirectory(path: string): void { const metadata = lstatSync(path); if (metadata.isSymbolicLink() || !metadata.isDirectory()) { @@ -401,6 +418,7 @@ function latestArchivedControlPlaneState( * placement shares one rotation path. */ interface RunnerStateArchive { + archivedByLaunch?: true; /** Read the live Runner state before its control plane is archived. */ read: () => Promise>; /** @@ -501,13 +519,14 @@ async function rotateAuthorityEpoch( priorIdentity, ); } else { - assertSuspendedRunnerState(await runnerState.read(), priorIdentity); + if (!runnerState.archivedByLaunch) assertSuspendedRunnerState(await runnerState.read(), priorIdentity); if (!existsSync(activeControlPlane)) { throw new Error("native_runner_authority_archive_incomplete"); } assertRealDirectory(activeControlPlane); renameSync(activeControlPlane, archivedControlPlane); } + if (runnerState.archivedByLaunch) return resumedState ?? controlPlaneState; const archivedRunnerState = await runnerState.archive({ archiveKey: basename(archive).replace(/^epoch-/, ""), priorIdentity, @@ -516,6 +535,31 @@ async function rotateAuthorityEpoch( return resumedState ?? controlPlaneState; } +export function revertUnattachedRelaunchRotation(root: string, source: DurableRecoveryIdentity): boolean { + const epoch = authorityArchiveDirectory(root, source); + const archived = resolve(epoch, "control-plane"); + const active = resolve(root, "control-plane"); + if (!existsSync(resolve(archived, "control-plane-state.json")) || !existsSync(resolve(active, "control-plane-state.json"))) return false; + assertRealDirectory(epoch); + assertRealDirectory(archived); + assertRealDirectory(active); + if (existsSync(resolve(epoch, "runner-state.json"))) return false; + if (!recoveryIdentityMatches(controlPlaneIdentity(readControlPlaneState(archived)), source)) return false; + const target = readControlPlaneState(active); + const identity = controlPlaneIdentity(target); + const externallyPersisted = target.schema === "paperclip.runner.external-control-plane-state.v1"; + if (identity.runnerInstanceId !== source.runnerInstanceId || identity.normalizedSessionId !== source.normalizedSessionId + || identity.runId === source.runId) return false; + if (!externallyPersisted && (target.connectionCount !== 0 || target.ackedSourceSeq !== 0 + || !Array.isArray(target.committedEvents) || target.committedEvents.length !== 0 + || Object.keys(record(target.leases)).length !== 0 + || Object.values(record(target.tickets)).some(ticket => record(ticket).usedAt !== null))) return false; + rmSync(active, { recursive: true }); + renameSync(archived, active); + if (readdirSync(epoch).length === 0) rmdirSync(epoch); + return true; +} + function projectCopilotRunGrant( grant: NativeRunRuntimeGrant, runnerFilesystemRoot?: string, @@ -4954,6 +4998,28 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { return operation.finally(() => { if (this.#attachmentOperation === pending) this.#attachmentOperation = null; }); } + retireReleasedController(): Promise<{ source: DurableRecoveryIdentity; runner: { version: string; digest: string } } | null> { + const episode = this.#releaseEpisode; + if (this.#detachPromise || this.#closePromise || this.#closed || this.#attachmentOperation !== null + || !episode?.confirmed || episode.claimed || episode.ticket !== undefined || !this.#core + || !recoveryIdentityMatches(episode.source, this.#core.store.state.identity)) return Promise.resolve(null); + const source = structuredClone(episode.source); + const runner = this.#core.expectedRunner(); + const operation = (async () => { + const deadline = Date.now() + runnerCloseGraceMs(this.options); + this.#controllerDetachedForRestart = true; + this.#closed = true; + this.#resolveClosedSignal(); + this.#turnStartAdmission?.resolve(false); + this.#controlPlaneCheckpoint = null; + await this.#retireControllerForRecovery(deadline, "keep_task"); + this.#handle = null; + this.#diagnostic("released controller retired; the host keeps the stopped runner's task"); + })(); + this.#detachPromise = operation; + return operation.then(() => ({ source, runner })); + } + async #claimReleasedRunner(claimantRunId: string): Promise { const episode = this.#releaseEpisode; const pair = this.options.releaseResume; @@ -5675,7 +5741,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ); } - async #retireControllerForRecovery(deadline: number): Promise { + async #retireControllerForRecovery(deadline: number, route: "detach" | "keep_task" = "detach"): Promise { this.#stopPump(); if (this.#adoptedRunnerMonitor !== null) clearInterval(this.#adoptedRunnerMonitor); @@ -5683,7 +5749,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#core?.disconnectActiveRunner(); const release = this.#controlPlaneRelease; this.#controlPlaneRelease = null; - await Promise.resolve(release?.("detach")).catch((error: unknown) => { + await Promise.resolve(route === "detach" ? release?.("detach") : release?.()).catch((error: unknown) => { this.#diagnostic( `controller route release failed during retirement: ${String(error)}`, ); @@ -6486,7 +6552,15 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } /** Runner state held by an external Runner host (a plugin task or a sandbox). */ - #externalRunnerStateArchive(): RunnerStateArchive { + #externalRunnerStateArchive(source: Record): RunnerStateArchive { + const relaunched = this.options.relaunchReleasedRunner; + if (relaunched) { + if (!this.options.runnerProcessLauncher || !recoveryIdentityMatches(controlPlaneIdentity(source), relaunched)) { + throw new Error("native_runner_released_source_mismatch"); + } + const unavailable = () => Promise.reject(new Error("native_runner_released_state_archived_by_launch")); + return { archivedByLaunch: true, read: unavailable, archive: unavailable }; + } const { readRunnerState, prepareExternalRunnerState, archiveExternalRunnerState } = this.options; if (readRunnerState === undefined || archiveExternalRunnerState === undefined) { throw new Error("native_runner_prp_run_rotation_unavailable"); @@ -7003,7 +7077,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#root, rotationSource, desiredIdentity, - localStateOwner ? localRunnerStateArchive(this.#root) : this.#externalRunnerStateArchive(), + localStateOwner ? localRunnerStateArchive(this.#root) : this.#externalRunnerStateArchive(rotationSource), ); } catch (error) { // Locally owned state is preserved aside for operator recovery. diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index 09594ed7328..e4c952039c7 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -151,6 +151,7 @@ export const environmentTaskOperationSchema = z.discriminatedUnion("kind", [ credential: environmentTaskCredentialSchema.optional(), configuredEnvironment: environmentTaskConfiguredEnvironmentSchema.optional(), relaunchedRunnerVersion: z.literal(1).optional(), + runner: z.object({ runId: runnerIdentity, turnId: runnerIdentity, itemId: runnerIdentity }).strict().optional(), }).strict(), z.object({ kind: z.literal("ensure_ownership"), @@ -172,7 +173,8 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [ 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"]), runner: runnerArtifact.optional() }).strict(), + z.object({ kind: z.literal("resume"), taskId: providerId, outcome: z.enum(["resumed", "unavailable"]), runner: runnerArtifact.optional(), + archivedState: z.record(z.string(), z.unknown()).optional() }).strict(), z.object({ kind: z.literal("ownership"), taskId: providerId, @@ -212,6 +214,7 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [ configuredEnvironmentVersion: z.literal(1).optional(), resumeLaunchInputsVersion: z.literal(1).optional(), resumeRelaunchedRunnerVersion: z.literal(1).optional(), + resumeIdentityVersion: z.literal(1).optional(), launchDigestVersion: z.literal(1).optional(), }).strict(), z.object({ @@ -283,5 +286,9 @@ export function parseEnvironmentTaskResult(operation: PluginEnvironmentTaskOpera const expected = operation.kind === "release" ? "released" : operation.kind === "resume" ? "resume" : operation.kind === "read_file" ? "file" : operation.kind === "describe" ? "description" : operation.kind === "prepare" ? "prepared" : operation.kind === "check_project_auth" ? "project_auth" : ["read_state", "archive_state"].includes(operation.kind) ? "state" : ["status", "connection", "credentials", "copilot_metadata"].includes(operation.kind) ? operation.kind : "accepted"; const rejectedSubmit = operation.kind === "submit" && result.kind === "admission_rejected"; if (result.taskId !== taskId || (result.kind !== expected && !rejectedSubmit)) throw new Error("Invalid plugin-provided Runner execution response"); + if (operation.kind === "resume" && result.kind === "resume" && (operation.runner + ? result.outcome === "resumed" && (!result.runner || !result.archivedState) : result.archivedState !== undefined)) { + throw new Error("Invalid plugin-provided Runner execution response"); + } return result; } diff --git a/packages/plugins/sdk/tests/environment-task-release-resume.test.ts b/packages/plugins/sdk/tests/environment-task-release-resume.test.ts index 5e85245c9b0..60e47256303 100644 --- a/packages/plugins/sdk/tests/environment-task-release-resume.test.ts +++ b/packages/plugins/sdk/tests/environment-task-release-resume.test.ts @@ -75,6 +75,26 @@ describe("release and resume task contract", () => { expect(environmentTaskResultSchema.safeParse({ ...result, runner: { ...runner, extra: true } }).success).toBe(false); }); + it("relaunches as the claimant's identity only when asked, and reports the archived state", () => { + expect(environmentTaskResultSchema.parse({ ...description, resumeIdentityVersion: 1 })).toEqual({ ...description, resumeIdentityVersion: 1 }); + expect(environmentTaskResultSchema.safeParse({ ...description, resumeIdentityVersion: 2 }).success).toBe(false); + const runner = { runId: "claimant-run", turnId: "turn-claimant-run", itemId: "item-claimant-run" }; + const relaunch = { ...resume, runner }; + expect(environmentTaskOperationSchema.parse(relaunch)).toEqual(relaunch); + for (const changed of [{ ...runner, sessionId: "other" }, { ...runner, runId: undefined }, { ...runner, turnId: "" }]) { + expect(environmentTaskOperationSchema.safeParse({ ...resume, runner: changed }).success).toBe(false); + } + const build = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` }; + const archivedState = { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready" }; + const resumed = { kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState }; + expect(parseEnvironmentTaskResult(relaunch, "task", resumed)).toEqual(resumed); + expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, archivedState: undefined })).toThrow(); + expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, runner: undefined })).toThrow(); + expect(() => parseEnvironmentTaskResult(resume, "task", resumed)).toThrow(); + expect(parseEnvironmentTaskResult(relaunch, "task", { kind: "resume", taskId: "task", outcome: "unavailable" })) + .toEqual({ kind: "resume", taskId: "task", outcome: "unavailable" }); + }); + it.each(credentials)("validates %s on resume as on submit", (_label, credential, valid) => { expect(environmentTaskOperationSchema.safeParse({ ...submit, credential }).success).toBe(valid); expect(environmentTaskOperationSchema.safeParse({ ...resume, credential }).success).toBe(valid); 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 4b50f3e284f..dc8015649b8 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -19347,7 +19347,7 @@ describe("runnerd provider runtime wiring", () => { state.toolAuthorityDefinitions.mockImplementation(async binding => binding.readRemoteTaskFile ? [{ name: "register_deliverable" }] as never : []); const readWorkspaceFile = vi.fn(async () => Buffer.from("proof")); const release = vi.fn(async () => {}), resume = vi.fn(async () => "resumed" as const); - const owner = vi.spyOn(pluginTaskRuntime, "createPluginRunnerTaskOwner").mockReturnValue({ launcher, registration, driver, readWorkspaceFile, release, resume, isRetired: () => false, retireSupersededTask: async () => false, retiredBeforeClaim: () => false, configuredEnvironmentDelivered: () => false, credentialsUpdated: vi.fn(), rebind:vi.fn() }); + const owner = vi.spyOn(pluginTaskRuntime, "createPluginRunnerTaskOwner").mockReturnValue({ launcher, registration, driver, readWorkspaceFile, release, resume, isRetired: () => false, retireSupersededTask: async () => false, retiredBeforeClaim: () => false, relaunchMayHaveStarted: () => false, configuredEnvironmentDelivered: () => false, credentialsUpdated: vi.fn(), rebind:vi.fn() }); const description = { kind: "description" as const, launchPreparationVersion: 1 as const, projectAuthCheckVersion: 1 as const, releaseResumeVersion: 1 as const, resumeLaunchInputsVersion: 1 as const, ...(kind === "codex" ? { workspaceFileReadVersion: 1 as const } : {}), taskId: "task", runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } }; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index d676b2f2d8b..b6c01ff75ee 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -224,6 +224,7 @@ import { inspectStagedRunAttachment, inspectDurablePrpCheckpointHeader, inspectDurablePrpCheckpointRunner, + revertUnattachedRelaunchRotation, inspectStagedRunAttachmentHeader, inspectRetainedRunInstructions, inspectWarmRunTransition, @@ -12230,6 +12231,8 @@ async function executePaperclipNativeSessionAttempt( ); let existingWarmSession: NativeSession | undefined; let reusingReleasedRunner = false; + let relaunchReleased: { owner: ReturnType; source: DurableRecoveryIdentity; + runner: { version: string; digest: string }; published?: true } | undefined; let managedCredentialSession: NativeSession | undefined; let githubAccess: NativeGitHubAccess | undefined; let releaseGitHubRun: (() => void) | undefined; @@ -12252,8 +12255,8 @@ async function executePaperclipNativeSessionAttempt( const registered = warmNativeSessions.get(warmSessionId); const entry = registered && forgetUnretiredOwnerOnOtherSandbox(warmSessionId, registered, input.runnerExecutionTarget) ? undefined : registered; - if (entry?.released) requireReleasedWarmScope(input, releasedWarmRunner(readWarmNativeEnvelope(input.execution)), - readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))); + const releasedSource = entry?.released ? requireReleasedWarmScope(input, releasedWarmRunner(readWarmNativeEnvelope(input.execution)), + readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))) : undefined; if (entry || remoteWarmRecovery?.releasedSource) { if (input.execution.provider.kind === "codex" || (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude")) { @@ -12337,8 +12340,28 @@ async function executePaperclipNativeSessionAttempt( if (entry.idleTimer !== null) clearTimeout(entry.idleTimer); entry.idleTimer = null; existingWarmSession = entry.session; + const relaunchOwner = reusingReleasedRunner && pluginTaskDescription?.resumeIdentityVersion === 1 + ? pluginTaskSessionOwners.get(entry.session) : undefined; + if (relaunchOwner?.driver.releaseResume && releasedSource) { + try { + const checkpoint = loadWarmNativeCheckpoint(input.execution, warmConfigDigest, input.runnerExecutionTarget?.kind ?? "local"); + const retired = checkpoint ? await entry.session.retireReleasedController?.() : null; + if (retired) { + if (canonicalJson(retired.source) !== canonicalJson(releasedSource)) throw new Error("native_session_released_source_mismatch"); + relaunchReleased = { owner: relaunchOwner, ...retired }; + existingWarmSession = undefined; + persistedWarmSession = checkpoint; + } + } catch (error) { + if (lifecyclePolicy.mode === "warm") { + await releaseWarmNativeSession(warmSessionId, warmSessionOwnerToken, lifecyclePolicy.idleTimeoutMs, true).catch(() => undefined); + } + throw error; + } + } const emitReuse = async () => { - await emitStartupReuse(input.onEvent, "runner", { state: "reused", reason: "verified_reuse" }); + await emitStartupReuse(input.onEvent, "runner", relaunchReleased + ? { state: "fresh", reason: "replacement" } : { state: "reused", reason: "verified_reuse" }); executionContext?.assertOpen(); await emitStartupReuse(input.onEvent, "provider_session", { state: "reused", reason: "verified_reuse" }); trace.setBudgetStart("warm"); @@ -12534,7 +12557,8 @@ async function executePaperclipNativeSessionAttempt( execution: input.execution, runnerInstanceId: effectiveRunnerInstanceId, pluginTaskDescription, - retainedPluginTaskOwner: existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : undefined, + retainedPluginTaskOwner: existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner, + relaunchReleased: relaunchReleased ? { source: relaunchReleased.source, runner: relaunchReleased.runner } : undefined, beginRetainedRunAttachment: existingWarmSession && reusingReleasedRunner ? beginRetainedRunAttachment(existingWarmSession) : undefined, durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId, remoteWarmRecovery: remoteWarmRecovery ? { @@ -12606,12 +12630,21 @@ async function executePaperclipNativeSessionAttempt( let remoteCleanupLease = await readRemoteCleanupLease(); const continueAfterUnavailableReuse = async (error: unknown) => { const target = input.runnerExecutionTarget; - if (!(error instanceof Error) || error.message !== "native_runner_reuse_unavailable" || !existingWarmSession - || pluginTaskSessionOwners.get(existingWarmSession)?.retiredBeforeClaim() !== true + const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner; + if (!(error instanceof Error) || error.message !== "native_runner_reuse_unavailable" || !retainedOwner + || retainedOwner.retiredBeforeClaim() !== true || remoteWarmRecovery || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask || runnerdBackend === null) return false; const retainedTaskId = target.sandboxLeaseAcquisition?.providerLeaseId; - await existingWarmSession.close({ reason: "retained Runner was unavailable for reuse" }); + if (existingWarmSession) await existingWarmSession.close({ reason: "retained Runner was unavailable for reuse" }); + else if (warmSessionId !== null) { + const retired = warmNativeSessions.get(warmSessionId); + if (retired?.ownerToken === warmSessionOwnerToken) { + if (retired.idleTimer !== null) clearTimeout(retired.idleTimer); + forgetWarmNativeSession(warmSessionId, retired); + } + } + relaunchReleased = undefined; const inspect = () => target.runnerTask!({ kind: "describe" }, executionContext ? { executionContext } : undefined); const description = environmentTaskResultSchema.parse(await (executionContext ? executionContext.wait(inspect) : inspect())); if (description.kind !== "description" || description.taskId === retainedTaskId) return false; @@ -12835,6 +12868,7 @@ async function executePaperclipNativeSessionAttempt( }, onSession: async (session) => { if (session) settleReattachRun(input.execution.binding.runId, "reached"); + if (session && relaunchReleased) relaunchReleased.published = true; input.bindAttachmentSession?.(session); if (session) runnerdBackend?.bindDiagnosticSession?.(session); if (session && input.runnerExecutionTarget?.kind === "remote" @@ -13074,6 +13108,9 @@ async function executePaperclipNativeSessionAttempt( try { result = await trace.run(runnerSessionStartupScope, runExecution); } catch (error) { + if (relaunchReleased && !relaunchReleased.published && !relaunchReleased.owner.relaunchMayHaveStarted()) { + revertUnattachedRelaunchRotation(scopedRunnerdStateRoot(input.execution), relaunchReleased.source); + } if (!await continueAfterUnavailableReuse(error)) throw error; result = await trace.run(runnerSessionStartupScope, runExecution); } @@ -16360,6 +16397,7 @@ export async function createRunnerdBackend(input: { durableEnvironmentLeaseId?: string; remoteWarmRecovery?: Omit & { revalidate: () => Promise }; retainedPluginTaskOwner?: ReturnType; + relaunchReleased?: { source: DurableRecoveryIdentity; runner: { version: string; digest: string } }; beginRetainedRunAttachment?: () => void; pluginTaskDescription?: PluginTaskDescription; onSpawn?: (meta: { @@ -16904,6 +16942,8 @@ async function createRunnerdBackendWithinSessionClaim( releaseResumeVersion: description.releaseResumeVersion, resumeLaunchInputsVersion: description.resumeLaunchInputsVersion, resumeRelaunchedRunnerVersion: description.resumeRelaunchedRunnerVersion, + resumeIdentityVersion: description.resumeIdentityVersion, + relaunch: input.relaunchReleased, launchDigestVersion: description.launchDigestVersion, authorityRunId: description.releaseResumeVersion === 1 ? input.execution.binding.runId : undefined, releasedSource: input.remoteWarmRecovery?.releasedSource, diff --git a/server/src/services/native-runtime/plugin-runner-eviction.integration.test.ts b/server/src/services/native-runtime/plugin-runner-eviction.integration.test.ts index cbf3d63b58c..794f42e1498 100644 --- a/server/src/services/native-runtime/plugin-runner-eviction.integration.test.ts +++ b/server/src/services/native-runtime/plugin-runner-eviction.integration.test.ts @@ -67,13 +67,15 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr }); const nativeIt = process.platform === "win32" ? it.skip : realProcessIt; nativeIt.for([...(["codex", "claude"] as const).flatMap(harness => (["cached", "detached", "reused lease", "after inspection", "bare unavailable", "prepared copy", "missing stop", "missing state", "foreign state", "working state"] as const).flatMap(mode => - (["retired", "abrupt"] as const).map(exit => [harness, mode, exit] as const)))])("continues %s with a %s Core owner after its Runner exit is %s", { timeout: 60_000 }, async ([harness, mode, exit], context) => { + (["retired", "abrupt"] as const).map(exit => [harness, mode, exit] as const))), + ...(["codex", "claude"] as const).map(harness => [harness, "relaunch after inspection", "retired"] as const)])("continues %s with a %s Core owner after its Runner exit is %s", { timeout: 60_000 }, async ([harness, mode, exit], context) => { if (harness === "claude" && !existsSync(fakeAcpxSidecar)) context.skip(); const thisCase: { teardown?: () => Promise } = {}; currentCase = thisCase; const detached = mode === "detached" || mode === "missing state" || mode === "foreign state"; const denied = mode.startsWith("missing") || mode.endsWith("state"); - const unavailableResume = mode === "after inspection" || mode === "bare unavailable"; + const relaunch = mode === "relaunch after inspection"; + const unavailableResume = mode === "after inspection" || mode === "bare unavailable" || relaunch; const reusesLease = mode === "reused lease" || unavailableResume; const instructionCopy = (id: string) => ({ runId: id, root: workspace, preparationKey: "unchanged-fixture-instructions", hasChanges: async () => false, collectStopped: async () => {} }); const first = await environment.seedRun(`RELEASE-ENTRY-${harness}-${mode}-${exit}-${randomUUID().slice(0, 8)}`); @@ -179,7 +181,8 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr inspectedLive = true; } return { kind: "description", taskId, launchPreparationVersion: 1, - projectAuthCheckVersion: 1, executionContextVersion: 1, warmTaskVersion: 1, releaseResumeVersion: 1, runner: artifact }; + projectAuthCheckVersion: 1, executionContextVersion: 1, warmTaskVersion: 1, releaseResumeVersion: 1, runner: artifact, + ...(relaunch ? { resumeIdentityVersion: 1, resumeRelaunchedRunnerVersion: 1 } : {}) }; } if (operation.kind === "prepare") { expect(operation.requirements.identity.runId).toBe(authorityRunId); @@ -249,8 +252,9 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr if (operation.kind === "resume" && unavailableResume) { resumeAttempts++; expect(inspectedLive).toBe(true); - if (mode === "after inspection") await evictRetained!(); - expect(handles.get(taskA)?.isExitConfirmed?.()).toBe(mode === "after inspection"); + expect(operation.runner?.runId).toBe(relaunch ? authorityRunId : undefined); + if (mode === "after inspection" || relaunch) await evictRetained!(); + expect(handles.get(taskA)?.isExitConfirmed?.()).toBe(mode !== "bare unavailable"); return { kind: "resume", taskId, outcome: "unavailable" }; } if (operation.kind === "resume") { @@ -401,7 +405,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId); const methods = (await readFile(calls, "utf8")).trim().split(/\r?\n/); expect(submissions).toBe(2); - if (mode === "after inspection") expect({ resumeAttempts, acquisitions }).toEqual({ resumeAttempts: 1, acquisitions: 1 }); + if (mode === "after inspection" || relaunch) expect({ resumeAttempts, acquisitions }).toEqual({ resumeAttempts: 1, acquisitions: 1 }); expect(releases[1]!.runId).toBe(runB); expect(claims).toEqual([]); if (harness === "codex") { diff --git a/server/src/services/native-runtime/plugin-runner-release-resume.integration.test.ts b/server/src/services/native-runtime/plugin-runner-release-resume.integration.test.ts index fddf3099c5c..1ce8a9f4f9d 100644 --- a/server/src/services/native-runtime/plugin-runner-release-resume.integration.test.ts +++ b/server/src/services/native-runtime/plugin-runner-release-resume.integration.test.ts @@ -1,7 +1,7 @@ import { execFileSync } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; import { existsSync } from "node:fs"; -import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises"; import https, { createServer } from "node:https"; import { createServer as createTcpServer } from "node:net"; import { join, resolve } from "node:path"; @@ -67,12 +67,13 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio const nativeIt = process.platform === "win32" ? it.skip : realProcessIt; nativeIt.for([...(["codex", "claude"] as const).flatMap(harness => (["cached", "adopted", "adopted restart"] as const).map(mode => [harness, mode] as const)), ["codex", "adopted cancellation"] as const, ["codex", "adopted legacy cancellation"] as const, ["codex", "cached cancellation"] as const, ["codex", "cached held claim"] as const, ["claude", "cached held claim"] as const, + ["codex", "cached relaunch"] as const, ["claude", "cached relaunch"] as const, ["codex", "adopted relaunch"] as const, ["codex", "cached managed GitHub"] as const, ["codex", "adopted managed GitHub"] as const, ["codex", "adopted restart managed GitHub"] as const])("completes %s runs through a retained %s process", { timeout: 60_000 }, async ([harness, mode], context) => { if (harness === "claude" && !existsSync(fakeAcpxSidecar)) context.skip(); const thisCase: { teardown?: () => Promise } = {}; currentCase = thisCase; const adopted = mode.startsWith("adopted"), cancellation = mode.includes("cancellation"), heldClaimMode = mode === "cached held claim"; - const restart = mode.includes("restart"); + const restart = mode.includes("restart"), relaunch = mode.includes("relaunch"); const qualifiedCancellation = mode === "adopted cancellation" || mode === "cached cancellation"; const managedGitHub = mode.endsWith("managed GitHub"), brokerUrl = "https://core.example.test/api", brokerToken = (runId: string) => `fixture-broker-${runId}`; const preparedBrokers: Array<{ runId: string; token?: string }> = []; @@ -142,7 +143,8 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio }); await new Promise(done => tls.listen(0, "127.0.0.1", done)); const tlsAddress = tls.address(); if (!tlsAddress || typeof tlsAddress === "string") throw new Error("Fixture TLS unavailable"); - const host = createPrivateHostControlFixture(), runnerRoot = join(root, "native"), binary = defaultCapabilityRunnerdBinary(); + let host = createPrivateHostControlFixture(); + const hosts = [host], runnerRoot = join(root, "native"), binary = defaultCapabilityRunnerdBinary(); const artifact = readRunnerdArtifactBinding(binary), preparations = new Map; launch: { configurationId: string } }>(); const releases: DurableRecoveryIdentity[] = [], claims: DurableRecoveryIdentity[] = []; const operationsDuringClaim: string[] = []; @@ -157,6 +159,8 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio const processStartRequested = async (id: string) => (await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents) .where(and(eq(heartbeatRunEvents.runId, id), eq(heartbeatRunEvents.eventType, PROCESS_START_REQUESTED)))).length > 0; let handle: RunnerProcessHandle | undefined, submissions = 0, stops = 0, completes = 0; + let submittedLaunch: Extract | undefined; + const relaunches: Array<{ source: DurableRecoveryIdentity; runId: string; archivedRunId: string }> = []; let releaseClaimReply!: () => void, observeHeldClaim!: () => void; const claimReply = new Promise(done => { releaseClaimReply = done; }); const heldClaim = new Promise(done => { observeHeldClaim = done; }); @@ -165,7 +169,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio thisCase.teardown = async () => { releaseClaimReply(); try { - const cleanup = await Promise.allSettled([closeIdleWarmNativeSessionsForRestart(), host.close()]); + const cleanup = await Promise.allSettled([closeIdleWarmNativeSessionsForRestart(), ...hosts.map(entry => entry.close())]); for (const socket of sockets) socket.terminate(); websocket.close(); await new Promise(done => tls.close(() => done())); const failures = cleanup.filter((result): result is PromiseRejectedResult => result.status === "rejected"); @@ -183,6 +187,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio if (claimHeld) operationsDuringClaim.push(operation.kind); if (operation.kind === "describe") return { kind: "description", taskId, launchPreparationVersion: 1, projectAuthCheckVersion: 1, warmTaskVersion: 1, releaseResumeVersion: 1, runner: artifact, ...(qualifiedCancellation ? { executionContextVersion: 1 } : {}), + ...(relaunch ? { resumeIdentityVersion: 1, resumeRelaunchedRunnerVersion: 1 } : {}), ...(managedGitHub ? { githubCredentialBrokerVersion: 1 } : {}) }; if (operation.kind === "prepare") { expect(operation.requirements.identity.runId).toBe(authorityRunId); @@ -196,14 +201,14 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio const requirements = { ...operation.requirements, runtimeContext: operation.requirements.runtimeContext ? parseNativeRuntimeContext(operation.requirements.runtimeContext) : null, settings: { ...operation.requirements.settings, acpxAgent: harness === "claude" ? "claude" as const : undefined, managedProfile: undefined, agentCoreProfile: undefined } }; const launch = { configurationId: `configuration-${operation.requirements.identity.runId}`, requirementsDigest: runnerLaunchRequirementsDigest(requirements), provider: createRunnerProviderLaunch(requirements, { options: { codexArgs: ["--state-file", join(root, "provider.json"), "--terminal-result-file", resultFile, - "--call-log", calls, "--record-process-start"] }, root, cwd: workspace, codexHome: home, codexCommand: fakeCodexAppServer, + "--call-log", calls, "--record-process-start", ...(relaunch ? ["--durable-turn-ids"] : [])] }, root, cwd: workspace, codexHome: home, codexCommand: fakeCodexAppServer, providerNodeCommand: harness === "claude" ? sidecar : process.execPath, opencodeProxyPath: "", acpxSidecarPath: harness === "claude" ? sidecarScript : "" }) }; preparations.set(launch.configurationId, { operation, launch }); return { kind: "prepared", taskId, launch }; } if (operation.kind === "check_project_auth") return { kind: "project_auth", taskId, configurationId: operation.configurationId, provider: operation.provider, allowed: true }; if (operation.kind === "submit") { if (!operation.preparedLaunchId || !operation.launch) throw new Error("Fixture structured launch unavailable"); - const prepared = preparations.get(operation.preparedLaunchId)!; submissions++; + const prepared = preparations.get(operation.preparedLaunchId)!; submissions++; submittedLaunch = operation; expect(operation.runner).toMatchObject({ runnerId: prepared.operation.requirements.identity.runnerInstanceId, leaseId: prepared.operation.requirements.identity.environmentLeaseId, runId: authorityRunId, sessionId: prepared.operation.requirements.identity.normalizedSessionId, turnId: prepared.operation.requirements.identity.turnId, @@ -233,7 +238,32 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio if (reply.status !== "parked") throw new Error("Fixture native release refused"); releases.push(operation.identity); return { kind: "released", taskId }; } + if (operation.kind === "resume" && operation.runner) { + expect(relaunch).toBe(true); + expect(operation.identity).toEqual(releases.at(-1)); + expect(operation.runner.runId).toBe(authorityRunId); + expect(operation.relaunchedRunnerVersion).toBe(1); + await host.close(); + await waitForCondition("parked Runner stopped", () => handle!.isExitConfirmed?.() === true); + const identity = { ...operation.identity, ...operation.runner }; + const archived = join(runnerRoot, `archived-${operation.identity.runId}.json`); + const archivedState = await state(); + await rename(join(runnerRoot, "runner-state.json"), archived); + const launch = submittedLaunch!.launch!; + listenPath = `/api/runner/v1/connect/${identity.runId}`; + host = createPrivateHostControlFixture(); hosts.push(host); + handle = spawnRunner({ ...launch, stateDirectory: runnerRoot, identity, ticket: operation.bootstrapTicket, + runnerBinaryPath: binary, maxOutboxBytes: launch.maxOutboxBytes, p0ReserveBytes: launch.p0ReserveBytes, + connection: { mode: "listen", listenAddress: "0.0.0.0", listenPort: runnerPort, listenPath }, processLauncher: host.launch, + environment: { PATH: process.env.PATH }, + ...(harness === "claude" ? { acpxLaunchProfile: { authorityDigest: `sha256:${sha("fixture authority")}`, command: sidecar, + commandSha256: `sha256:${sha(await readFile(sidecar, "utf8"))}`, sidecarScript, + sidecarScriptSha256: `sha256:${sha(await readFile(sidecarScript, "utf8"))}` } } : {}) }); + relaunches.push({ source: operation.identity, runId: identity.runId, archivedRunId: archivedState.runId }); + return { kind: "resume", taskId, outcome: "resumed", runner: artifact, archivedState }; + } if (operation.kind === "resume") { + expect(relaunch && !adopted).toBe(false); const retainedProviderCount = await providerStarts(); const reply = await host.request({ op: "claim", id: `claim_${sha(operation.bootstrapTicket)}`, parkId: parkId(operation.identity), bootstrapTicket: operation.bootstrapTicket }); if (reply.status !== "claimed") throw new Error("Fixture native claim refused"); @@ -342,24 +372,39 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId); expect(adoption).toHaveBeenCalledTimes(adopted ? 1 : 0); if (adopted) expect(adoption.mock.calls[0]![0]).toMatchObject({ identity: releases[0], execution: { binding: { runId: runB } } }); + let runC: string | undefined; if (adopted) { - const runC = await admitNext(); + runC = await admitNext(); await waitForCondition("automatic release C", () => releases.length === 3); expect(releases[2]!.runId).toBe(runC); expect(await proof()).toMatchObject({ source: releases[2], taskId }); expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId); expect(adoption).toHaveBeenCalledTimes(1); } - expect(claims).toEqual(releases.slice(0, -1)); expect(releases[1]!.runId).toBe(runB); + expect(claims).toEqual(releases.slice(0, -1).filter(source => !relaunches.some(entry => entry.source.runId === source.runId))); + expect(releases[1]!.runId).toBe(runB); if (heldClaimMode) expect({ claimedDuringPreparation, operationsDuringClaim }).toEqual({ claimedDuringPreparation: true, operationsDuringClaim: [] }); - expect(releases[1]!.environmentLeaseId).toBe(leaseA); expect(handle!.child.pid).toBe(pid); expect(submissions).toBe(1); + expect(releases[1]!.environmentLeaseId).toBe(leaseA); expect(submissions).toBe(1); + if (relaunch) { + expect(handle!.child.pid).not.toBe(pid); + const relaunched = adopted ? releases[1]! : releases[0]!; + expect(relaunches).toEqual([{ source: relaunched, runId: adopted ? runC : runB, archivedRunId: relaunched.runId }]); + expect((await state()).runId).toBe(releases.at(-1)!.runId); + expect(JSON.parse(await readFile(join(runnerRoot, `archived-${relaunched.runId}.json`), "utf8"))).toMatchObject(relaunched); + } else expect(handle!.child.pid).toBe(pid); expect([...new Set(preparedBrokers.map(prepared => prepared.runId))]).toEqual(releases.map(release => release.runId)); const methods = (await readFile(calls, "utf8")).trim().split(/\r?\n/); if (harness === "codex") { - expect(methods.filter(method => method === "process-start")).toHaveLength(1); + expect(methods.filter(method => method === "process-start")).toHaveLength(relaunch ? 2 : 1); expect(methods.filter(method => method === "turn/start")).toHaveLength(adopted ? 3 : 2); } else { const journal = methods.map(line => JSON.parse(line)); - expect(journal.filter(entry => entry.processStart)).toHaveLength(adopted ? 4 : 3); + expect(journal.filter(entry => entry.processStart)).toHaveLength(adopted || relaunch ? 4 : 3); + if (relaunch) { + const attach = journal.findIndex(entry => entry.command === "run.attach" && entry.params?.runId === runB); + const turn = journal.findIndex((entry, index) => index > attach && entry.command === "turn.start"); + expect(journal[attach - 3]?.processStart).toEqual(expect.any(Number)); + expect(journal.slice(attach - 2, turn).filter(entry => entry.processStart)).toHaveLength(0); + } expect(journal.filter(entry => entry.command === "turn.start")).toHaveLength(adopted ? 3 : 2); } } catch (error) { 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 124d6f1bdc4..59257116a55 100644 --- a/server/src/services/native-runtime/plugin-runner-task.test.ts +++ b/server/src/services/native-runtime/plugin-runner-task.test.ts @@ -800,6 +800,112 @@ describe("plugin Runner release/resume facade", () => { }); }); +describe("plugin Runner relaunch as the claimant run", () => { + const source = requirements.identity; + const next = { ...source, runId: "next-run", turnId: "turn-next-run", itemId: "item-next-run" }; + const parked = { version: "0.4.0", digest: `sha256:${"c".repeat(64)}` }; + const build = { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` }; + const settledCut = { schema: "paperclip.runner.durable.state.v1", ...source, lifecycle: "ready", nextSourceSeq: 4, ackedSourceSeq: 3, + outbox: [], pendingTerminalDelivery: null, processedCommands: {} }; + const base = { taskId: "task", projectIds: ["00000000-0000-4000-8000-000000000001"], projectAuthCheckVersion: 1 as const, harness: "codex", warmTaskVersion: 1 as const, releaseResumeVersion: 1 as const, + accountIdentity: "selected-account", credentialIdentity: "selected-credential" }; + const relaunchSpec = (): RunnerProcessLaunchSpec => { + const spec = launchSpec(); + return { ...spec, nativeRunner: { ...spec.nativeRunner!, identity: next, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } }; + }; + async function relaunchOwner(resume: (operation: any) => unknown, options: { resumeIdentityVersion?: 1; onResumed?: () => Promise } = { resumeIdentityVersion: 1 }) { + const { task } = provider(); + const perform = task.getMockImplementation()!; + task.mockImplementation(async operation => operation.kind === "resume" ? resume(operation) : perform(operation)); + const close = vi.fn(async () => {}); + ingress.connect.mockReset().mockReturnValue({ ready: Promise.resolve(), quiesce: vi.fn(), close }); + const owner = createPluginRunnerTaskOwner({ ...base, task, adoptIdentity: source, authorityRunId: source.runId }); + owner.rebind({ ...base, task, authorityRunId: next.runId, resumeRelaunchedRunnerVersion: 1, + resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked }, onResumed: options.onResumed }); + await prepare(owner, { ...requirements, identity: next }); + const authority = { acceptRelaunchedRunner: vi.fn() }; + const registration = await owner.registration(authority as never, next.runId, undefined, next); + return { owner, task, authority, registration }; + } + + it("starts the stopped Runner again as the claimant run and accepts the reported build", async () => { + const onResumed = vi.fn(async () => {}); + const { owner, task, authority, registration } = await relaunchOwner( + () => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }), + { resumeIdentityVersion: 1, onResumed }); + expect(owner.driver.relaunchReleasedRunner).toEqual(source); + expect(owner.driver.adoptExistingRunner).toBeUndefined(); + expect(owner.relaunchMayHaveStarted()).toBe(false); + owner.launcher(relaunchSpec()); + registration.activate(); + try { + await registration.ready(); + expect(task.mock.calls.filter(([operation]) => operation.kind === "resume").map(([operation]) => operation)).toEqual([{ + kind: "resume", identity: source, bootstrapTicket: "synthetic-ticket", relaunchedRunnerVersion: 1, + runner: { runId: next.runId, turnId: next.turnId, itemId: next.itemId }, + }]); + expect(task.mock.calls.some(([operation]) => operation.kind === "submit")).toBe(false); + expect(authority.acceptRelaunchedRunner).toHaveBeenCalledExactlyOnceWith("synthetic-ticket", build, parked); + expect(onResumed).toHaveBeenCalledExactlyOnceWith(source); + expect(ingress.connect).toHaveBeenCalledOnce(); + expect(owner.relaunchMayHaveStarted()).toBe(true); + owner.rebind({ ...base, task, authorityRunId: "later-run", resumeRelaunchedRunnerVersion: 1, resumeIdentityVersion: 1, + relaunch: { source: next, runner: build } }); + expect(owner.relaunchMayHaveStarted()).toBe(false); + } finally { await registration.release("detach"); } + }); + + it("retries a lost reply with the same ticket and identity", async () => { + let attempts = 0; + const { task, registration, owner } = await relaunchOwner(() => { + if (attempts++ === 0) throw new Error("fixture resume reply lost"); + return { kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut }; + }); + owner.launcher(relaunchSpec()); + registration.activate(); + try { + await registration.ready(); + const resumes = task.mock.calls.filter(([operation]) => operation.kind === "resume").map(([operation]) => operation); + expect(resumes).toHaveLength(2); + expect(resumes[1]).toEqual(resumes[0]); + } finally { await registration.release("detach"); } + }); + + it.each([ + ["an unsettled cut", { ...settledCut, outbox: [{ sourceSeq: 4 }] }], + ["another source's cut", { ...settledCut, runId: "other-run" }], + ])("refuses %s before the Runner can connect", async (_label, archivedState) => { + const { authority, registration, owner } = await relaunchOwner( + () => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState })); + owner.launcher(relaunchSpec()); + registration.activate(); + try { + await expect(registration.ready()).rejects.toThrow("native_runner_released_state_unsettled"); + expect(authority.acceptRelaunchedRunner).not.toHaveBeenCalled(); + expect(owner.relaunchMayHaveStarted()).toBe(true); + expect(ingress.connect).not.toHaveBeenCalled(); + } finally { await registration.release("detach"); } + }); + + it("reports an unavailable relaunch for ordinary recovery", async () => { + const { registration, owner } = await relaunchOwner(() => ({ kind: "resume", taskId: "task", outcome: "unavailable" })); + owner.launcher(relaunchSpec()); + registration.activate(); + try { + await expect(registration.ready()).rejects.toThrow("native_runner_reuse_unavailable"); + expect(ingress.connect).not.toHaveBeenCalled(); + expect(owner.relaunchMayHaveStarted()).toBe(false); + } finally { await registration.release("detach"); } + }); + + it("keeps the claimant handover when the provider does not advertise relaunch", async () => { + const { owner, task } = await relaunchOwner(() => { throw new Error("unexpected resume"); }, {}); + expect(owner.driver.relaunchReleasedRunner).toBeUndefined(); + expect(() => owner.launcher(relaunchSpec())).toThrow("Plugin Runner replacement requires a new task lease"); + expect(task.mock.calls.some(([operation]) => operation.kind === "resume")).toBe(false); + }); +}); + describe("plugin task workspace file transfer", () => { it("reads only a submitted task, validates bytes, and rejects late responses after release", 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 b62f57b20aa..53022e2f414 100644 --- a/server/src/services/native-runtime/plugin-runner-task.ts +++ b/server/src/services/native-runtime/plugin-runner-task.ts @@ -4,10 +4,13 @@ import { setTimeout as delay } from "node:timers/promises"; import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskOperation, type PluginEnvironmentTaskResult, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk"; import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity"; import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec, - type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerReleaseResumeOutcome, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent } from "../../vendor/paperclip-runner/index.js"; + type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerReleaseResumeOutcome, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent, + isSettledReleasedRunnerCut } from "../../vendor/paperclip-runner/index.js"; import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js"; import type { NativeExecutionContext } from "./native-execution-context.js"; +const RELAUNCH_TICKET_TTL_MS = 60_000; + export async function verifyPluginRunnerTaskReattachment( task: (operation: unknown) => Promise, identity: unknown, ): Promise { @@ -51,6 +54,8 @@ export function createPluginRunnerTaskOwner(input: { releaseResumeVersion?: 1; resumeLaunchInputsVersion?: 1; resumeRelaunchedRunnerVersion?: 1; + resumeIdentityVersion?: 1; + relaunch?: { source: DurableRecoveryIdentity; runner: { version: string; digest: string } }; releasedSourceRunner?: { version: string; digest: string }; launchDigestVersion?: 1; releasedSource?: DurableRecoveryIdentity; @@ -67,6 +72,8 @@ export function createPluginRunnerTaskOwner(input: { if (!taskId) throw new Error("Plugin Runner physical task unavailable"); const pollMs = input.pollMs ?? 500; let registrationGeneration = 0; + let registeredAuthority: DurablePrpControlPlane | null = null; + let relaunchProgress: "none" | "sent" | "refused" = "none"; let activeOutbound: ReturnType | null = null; let preparedLaunchId: string | undefined; let preparedIdentity: DurableRecoveryIdentity | undefined = input.adoptIdentity; @@ -86,8 +93,12 @@ export function createPluginRunnerTaskOwner(input: { let rejectFailure!: (error: unknown) => void; const failure = new Promise((_resolve, reject) => { rejectFailure = reject; }); void failure.catch(() => undefined); - const running = new Promise((resolve, reject) => { markReady = resolve; failReady = reject; }); - void running.catch(() => undefined); + const pendingLaunch = () => { + const launch = new Promise((resolve, reject) => { markReady = resolve; failReady = reject; }); + void launch.catch(() => undefined); + return launch; + }; + let running = pendingLaunch(); if (input.adoptIdentity) markReady(); const configuredEnvironmentFields = (launchesRunner: boolean) => input.configuredEnvironmentVersion === 1 && launchesRunner ? { configuredEnvironment: { ...input.configuredEnvironment } } : {}; @@ -201,7 +212,71 @@ export function createPluginRunnerTaskOwner(input: { } while (Date.now() < deadline); throw new Error("Plugin Runner termination is unconfirmed; retain the lease for cleanup"); }; + const relaunchStopped = (spec: RunnerProcessLaunchSpec, relaunch: NonNullable): RunnerProcessHandle => { + const native = spec.nativeRunner; + const source = relaunch.source; + const authority = registeredAuthority; + if (!native || native.lifecyclePolicy?.mode !== "warm" || !authority || !preparedIdentity + || Object.entries(preparedIdentity).some(([key, value]) => native.identity[key as keyof DurableRecoveryIdentity] !== value) + || (["runnerInstanceId", "environmentLeaseId", "normalizedSessionId"] as const).some(key => native.identity[key] !== source[key]) + || native.identity.runId === source.runId) { + throw new Error("Plugin Runner relaunch identity mismatch"); + } + requireReleaseResume(); + relaunchProgress = "none"; + running = pendingLaunch(); + const operation = environmentTaskOperationSchema.parse({ kind: "resume", identity: source, bootstrapTicket: native.ticket, + ...resumeLaunchFields(), + runner: { runId: native.identity.runId, turnId: native.identity.turnId, itemId: native.identity.itemId } }); + launchIdentity = native.identity; + configuredEnvironmentDelivered = "configuredEnvironment" in operation; + const child: RunnerProcessHandle["child"] = { exitCode: null, signalCode: null, + kill: () => { stopRequested = true; void stopAndConfirm().catch(rejectFailure); return true; } }; + const completion = new Promise>(resolve => { + confirmStopped = (code, error) => { + if (child.exitCode !== null) return; + child.exitCode = code; + failReady(error ?? new Error("Plugin Runner stopped before connection")); + resolve({ code, signal: null, stdout: "", stderr: error?.message ?? "" }); + }; + }); + const deadline = Date.now() + RELAUNCH_TICKET_TTL_MS; + void (async () => { + await input.onDispatched?.(); + for (;;) { + if (released || stopRequested || detached) throw new Error("Plugin Runner startup cancelled"); + let result: PluginEnvironmentTaskResult; + try { + relaunchProgress = "sent"; + result = await call(operation); + } catch (error) { + if (Date.now() >= deadline) throw error; + await delay(250); + continue; + } + if (result.kind !== "resume") throw new Error("Plugin Runner resume result unavailable"); + if (result.outcome === "unavailable") { + relaunchProgress = "refused"; + const state = await call({ kind: "status" }).catch(() => undefined); + retiredBeforeClaim = state?.kind === "status" && state.executionStopped === true && state.sessionStateAvailable === true; + throw new Error("native_runner_reuse_unavailable"); + } + if (!result.archivedState || !result.runner || !isSettledReleasedRunnerCut(result.archivedState, source)) { + throw new Error("native_runner_released_state_unsettled"); + } + authority.acceptRelaunchedRunner(native.ticket, result.runner, relaunch.runner); + await input.onResumed?.(source); + markReady(); + return; + } + })().catch(error => { + failReady(error); + rejectFailure(error); + }); + return { child, completion, restart: null }; + }; const launcher = (spec: RunnerProcessLaunchSpec): RunnerProcessHandle => { + if (launched && input.relaunch && input.resumeIdentityVersion === 1) return relaunchStopped(spec, input.relaunch); if (launched || released) throw new Error("Plugin Runner replacement requires a new task lease"); const native = spec.nativeRunner; if (!preparedLaunchId) throw new Error("Plugin Runner launch requires preparation"); @@ -296,6 +371,7 @@ export function createPluginRunnerTaskOwner(input: { const registration = async (authority: DurablePrpControlPlane, runId: string, signal?: AbortSignal, expectedIdentity?: DurableRecoveryIdentity) => { const desired = expectedIdentity ? structuredClone(expectedIdentity) : undefined; const generation = ++registrationGeneration; + registeredAuthority = authority; let registrationReleased = false; let outbound: ReturnType | null = null; let activation: Promise | null = null; @@ -367,6 +443,16 @@ export function createPluginRunnerTaskOwner(input: { }, }; }; + const adoptedRunner: NonNullable = { + // Provider ownership is attested by Launcher, never by a controller-local PID. + pid: null, processGroupId: null, startedAt: null, + isAlive: async () => { + if (!adoptionVerified) { if ((await readStatus()).executionStopped === true) return false; adoptionVerified = true; } + // Authenticated PRP detects disconnects; this cache never asserts termination. + return stoppedState === undefined; + }, + signal: async () => { stopRequested = true; await stopAndConfirm(); return true; }, + }; const driver: RunnerExecutionDriver = { get releaseResume() { if (input.releaseResumeVersion !== 1 || input.warmTaskVersion !== 1 || !input.accountIdentity) return undefined; @@ -390,6 +476,7 @@ export function createPluginRunnerTaskOwner(input: { }; }, get authorityRunId() { return input.authorityRunId ?? input.executionContext?.execution.binding.runId; }, + get relaunchReleasedRunner() { return launched && input.resumeIdentityVersion === 1 ? input.relaunch?.source : undefined; }, get codexSourceRecoveryVersion() { return input.codexSourceRecoveryVersion; }, prepareLaunch, authorizeRunnerAdoption, readRunnerState, runnerProcessLauncher: launcher, // The provider resolves the authorized retained task before each state operation. @@ -401,16 +488,7 @@ export function createPluginRunnerTaskOwner(input: { return result.state; }, controlPlaneRegistration: (authority, identity, signal) => registration(authority, identity?.runId ?? "", signal, identity), - ...(input.adoptIdentity ? { adoptExistingRunner: { - // Provider ownership is attested by Launcher, never by a controller-local PID. - pid: null, processGroupId: null, startedAt: null, - isAlive: async () => { - if (!adoptionVerified) { if ((await readStatus()).executionStopped === true) return false; adoptionVerified = true; } - // Authenticated PRP detects disconnects; this cache never asserts termination. - return stoppedState === undefined; - }, - signal: async () => { stopRequested = true; await stopAndConfirm(); return true; }, - } } : {}), + get adoptExistingRunner() { return input.adoptIdentity ? adoptedRunner : undefined; }, }; const readWorkspaceFile = async (path: string, maxBytes: number): Promise => { if (!submitted || !preparedIdentity || released || stopRequested) throw new Error("Plugin Runner file access unavailable"); @@ -428,6 +506,18 @@ export function createPluginRunnerTaskOwner(input: { throw new Error("Plugin Runner release/resume unavailable"); } }; + const resumeLaunchFields = () => { + const handoffCredential = input.sessionHandoff && input.credential?.type === "claude-env" + ? { accountIdentity: input.accountIdentity, environment: input.credential.environment } + : undefined; + const launchInputs = input.resumeLaunchInputsVersion === 1; + return { + ...(handoffCredential ? { handoffCredential } : {}), + ...(launchInputs && input.credential ? { credential: input.credential } : {}), + ...configuredEnvironmentFields(!!input.sessionHandoff || launchInputs), + ...(input.resumeRelaunchedRunnerVersion === 1 ? { relaunchedRunnerVersion: 1 as const } : {}), + }; + }; // The caller owns settlement, connection quieting and exact-ticket retries. const release = async (identity: DurableRecoveryIdentity): Promise => { requireReleaseResume(); @@ -436,16 +526,7 @@ export function createPluginRunnerTaskOwner(input: { }; const resume = async (identity: DurableRecoveryIdentity, bootstrapTicket: string): Promise => { requireReleaseResume(); - const handoffCredential = input.sessionHandoff && input.credential?.type === "claude-env" - ? { accountIdentity: input.accountIdentity, environment: input.credential.environment } - : undefined; - const launchInputs = input.resumeLaunchInputsVersion === 1; - const result = await call(environmentTaskOperationSchema.parse({ kind: "resume", identity, bootstrapTicket, - ...(handoffCredential ? { handoffCredential } : {}), - ...(launchInputs && input.credential ? { credential: input.credential } : {}), - ...configuredEnvironmentFields(!!input.sessionHandoff || launchInputs), - ...(input.resumeRelaunchedRunnerVersion === 1 ? { relaunchedRunnerVersion: 1 as const } : {}), - })); + const result = await call(environmentTaskOperationSchema.parse({ kind: "resume", identity, bootstrapTicket, ...resumeLaunchFields() })); requireReleaseResume(); if (result.kind !== "resume") throw new Error("Plugin Runner resume result unavailable"); if (result.outcome === "resumed" && input.sessionHandoff) configuredEnvironmentDelivered = input.configuredEnvironmentVersion === 1; @@ -485,6 +566,7 @@ export function createPluginRunnerTaskOwner(input: { // stop request. Completion also proves credential/writeback obligations ran. isRetired: () => stoppedState?.executionStopped === true && completed && !detached, retiredBeforeClaim: () => retiredBeforeClaim, + relaunchMayHaveStarted: () => relaunchProgress === "sent", configuredEnvironmentDelivered: () => configuredEnvironmentDelivered, rebind(next: typeof input) { if (!launched || stopRequested || stoppedState || detached || next.taskId !== taskId || next.harness !== input.harness || @@ -492,6 +574,7 @@ export function createPluginRunnerTaskOwner(input: { JSON.stringify(input.projectIds) !== JSON.stringify(next.projectIds)) throw new Error("Plugin warm task cannot be rebound"); input = next; released = false; + relaunchProgress = "none"; bindStartupAbort(); }, }; diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 94de832ec95..c3c27e9fe83 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -101,6 +101,8 @@ export const decodeDurablePrpCheckpoint = runner.decodeDurablePrpCheckpoint; export const captureLegacyDurablePrpCheckpoint = runner.captureLegacyDurablePrpCheckpoint; export const inspectDurablePrpCheckpointHeader = runner.inspectDurablePrpCheckpointHeader; export const inspectDurablePrpCheckpointRunner = runner.inspectDurablePrpCheckpointRunner; +export const isSettledReleasedRunnerCut = runner.isSettledReleasedRunnerCut; +export const revertUnattachedRelaunchRotation = runner.revertUnattachedRelaunchRotation; export const inspectUnclaimedBootstrapCheckpoint = runner.inspectUnclaimedBootstrapCheckpoint; export const inspectUnauthenticatedBootstrapCheckpoint = runner.inspectUnauthenticatedBootstrapCheckpoint; export const inspectUnclaimedBootstrapState = runner.inspectUnclaimedBootstrapState; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 27b97e43424..cc160f2ffb3 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -13,7 +13,7 @@ "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": "09594ed73287ccc6e41fef0fdd969ea50dc78b55", + "packages/plugins/sdk/src/environment-tasks.ts": "e4c952039c74bcc3b206f34fa751e2a82d1a7cda", "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",