diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index c516aa2ddc4..e1dd0f06fdb 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -201,13 +201,17 @@ 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. +- Return `runner: { version, digest }` on the `resumed` result. A provider may + also return `archivedState`, the archived Runner state; Core does not read it. -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 +The provider is the authority on whether a park exists. It relaunches only from +the source's settled cut, and Core does not check that cut again. That cut is the +`suspended` lifecycle, or the `ready` lifecycle with an empty outbox, every event +acknowledged and no command in progress. Core resumes on the assumption that the +source parked. When the task has no park of that source, return `unavailable` +once nothing runs for the task, and Core starts a fresh task from the saved +session. Otherwise Core 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. @@ -274,18 +278,14 @@ turn replay. A known `unavailable` result still requires ordinary physical cleanup. Transparent cold fallback remains a separate qualification requirement. A normal Core cache timeout detaches only Core's quiet local owner. The host -keeps its retained resources under its own retention policy. Core's existing -completed-session record stores only the confirmed source, physical task and a -digest of the selected account, credential revision and workspace scope. The -transport returns the exact source after the host's release receipt; Core does -not infer it from a local checkpoint marker, which may still name an older run. -An invalid source receipt or failed proof write keeps cleanup under the same -owner until physical retirement finishes. Later -cache adoption validates that Core-authored proof before claiming or -reconnecting. A stale or missing proof never licenses a claim. A changed -selection remains blocked until guarded retirement/recovery; it does not imply -that a cold launch is safe. Confirmed claim or physical cleanup clears only the -matching proof. Raw tickets are never stored in this record. +keeps its retained resources under its own retention policy. Core keeps no +record of a release beyond that owner. The transport returns the exact source +after the host's release receipt. Core checks it against the attached run, +session, Runner and lease, and only then marks its owner released. An invalid +source receipt keeps cleanup under the same owner until physical retirement +finishes. A later run resumes the source Core restores from its controller +checkpoint, on the lease's current task only, and the provider answers from its +own park record. Raw tickets are never stored. When graceful host eviction has saved a suspended session and Core has recorded physical stop, a later allocation can use ordinary `resumeFrom` recovery. Core 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 a8ca08fbd6b..1a36b623f6d 100644 --- a/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts +++ b/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts @@ -11,7 +11,7 @@ import type { DurableRecoveryIdentity } from "../contracts/durable-recovery.js"; export type RunnerReleaseResumeOutcome = | "resumed" | "unavailable" - | { outcome: "resumed"; runner: { version: string; digest: string }; settled?: () => Promise }; + | { outcome: "resumed"; runner: { version: string; digest: string } }; export interface RunnerExecutionDriver { /** The driver verifies a stopped, idle Codex App Server source before launch. */ diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index 381f2f3846f..1fa4eeb1d26 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -101,7 +101,6 @@ export { resolveGrokEffort } from "./drivers/acpx/grok-effort.js"; export * from "./drivers/runner-tool-bridge.js"; export { createRunnerdCodexTransport, - isSettledReleasedRunnerCut, revertUnattachedRelaunchRotation, probeNativeRunnerEnvironment, NativeEnvironmentProbeCleanupError, diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-release-resume.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-release-resume.test.ts index a653e5a8553..2bd44b6e156 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport-release-resume.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-release-resume.test.ts @@ -122,7 +122,6 @@ it.skipIf(process.platform === "win32").each(["cached", "lost claim reply", "cac const measuredTurn = new Promise(resolve => { enterMeasuredTurn = resolve; }); const heldMeasuredTurn = new Promise(resolve => { finishMeasuredTurn = resolve; }); const sockets = new Set(); - const relaunchSettled = vi.fn(async () => { expect(authority!.store.state.identity.runId).toBe(identity.runId); }); const registration = async (core: DurablePrpControlPlane, source = core.store.state.identity) => { if ((mode === "late claim reply" || mode === "held past deadline" || mode === "early claim expired") && claimAccepted) throw new Error("Fixture source authentication started after expiry"); authority = core; @@ -184,7 +183,7 @@ it.skipIf(process.platform === "win32").each(["cached", "lost claim reply", "cac if (mode === "relaunched flush retry" && pair.resume.mock.calls.length === 1) { vi.spyOn(authority!, "flushCheckpoint").mockRejectedValueOnce(new Error("Fixture checkpoint write failed")); } - return { outcome: "resumed", runner: { version, digest: runnerDigest }, settled: relaunchSettled }; + return { outcome: "resumed", runner: { version, digest: runnerDigest } }; } return "resumed"; }), @@ -438,9 +437,7 @@ it.skipIf(process.platform === "win32").each(["cached", "lost claim reply", "cac await bundle.transport.close(); } else await attaching; expect(new Set(claimTicketDigests).size).toBe(1); - if (mode === "relaunched same build" || mode === "relaunched flush retry") expect(relaunchSettled).toHaveBeenCalledOnce(); if (mode === "relaunched incompatible build") { - expect(relaunchSettled).not.toHaveBeenCalled(); expect(pair.resume).toHaveBeenCalledOnce(); expect(authority!.store.state.identity.runId).toBe(identity.runId); return; 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 cf2bf64f793..56e0721f2ba 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, isSettledReleasedRunnerCut, revertUnattachedRelaunchRotation, RUNNER_MAX_STOPPED_CREDIT_MS, RUNNER_POST_STOP_GRACE_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js"; +import { coldAdmissionTimeoutMs, describeRunnerCommandStall, 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"; @@ -2211,26 +2211,6 @@ describe("a rotation for a released Runner that the host starts again", () => { } } }); - - 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", () => { diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 758f1f2d628..713a0203b1b 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -237,22 +237,6 @@ 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()) { @@ -5067,7 +5051,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { assertPending(); let outcome: "resumed" | "unavailable" | undefined; let relaunched: { version: string; digest: string } | undefined; - let settled: (() => Promise) | undefined; try { if (!episode.ticket) { episode.ticket = core.issueBootstrapTicket(RUNNER_BOOTSTRAP_TICKET_TTL_MS); @@ -5081,7 +5064,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { const result = await Promise.race([pair.resume(episode.source, episode.ticket), deadline, closed]); outcome = typeof result === "string" ? result : result.outcome; relaunched = typeof result === "string" ? undefined : result.runner; - settled = typeof result === "string" ? undefined : result.settled; } catch (error) { // A generic RPC error cannot prove refusal. Keep this exact pending claim quiet. assertPending(); @@ -5096,7 +5078,6 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { core.acceptRelaunchedRunner(episode.ticket!, relaunched, episode.parked); this.#relaunchedRunnerArtifact = structuredClone(relaunched); await Promise.race([core.flushCheckpoint(), deadline, closed]); - await Promise.race([settled?.(), deadline, closed]); } catch (error) { if (error instanceof Error && error.message === "native_runner_relaunched_build_unaccepted") { throw new Error("native_runner_reuse_unavailable"); diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index 5557e21415c..9e288a2eb9d 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -308,7 +308,7 @@ export function parseEnvironmentTaskResult(operation: PluginEnvironmentTaskOpera 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)) { + ? result.outcome === "resumed" && !result.runner : 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 5f72f05c980..81f3ed7cb8f 100644 --- a/packages/plugins/sdk/tests/environment-task-release-resume.test.ts +++ b/packages/plugins/sdk/tests/environment-task-release-resume.test.ts @@ -107,7 +107,8 @@ describe("release and resume task contract", () => { 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(); + const { archivedState: _archivedState, ...withoutState } = resumed; + expect(parseEnvironmentTaskResult(relaunch, "task", withoutState)).toEqual(withoutState); expect(() => parseEnvironmentTaskResult(relaunch, "task", { ...resumed, runner: undefined })).toThrow(); expect(() => parseEnvironmentTaskResult(resume, "task", resumed)).toThrow(); expect(parseEnvironmentTaskResult(relaunch, "task", { kind: "resume", taskId: "task", outcome: "unavailable" })) 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 d4847d5e6bc..771954a5413 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -15147,10 +15147,12 @@ describe("native warm session supervision", () => { async ({ name, firstEnvironment = {}, secondEnvironment = {}, refreshTools, unsupportedRefresh = false, managedGitHub = false, reuse, adoptionReuse = reuse }) => { const decisions: Record = {}; - for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : [])] as const) { + for (const path of ["warm", "adoption", ...(refreshTools ? ["portable", "portable-bootstrap", "legacy-plugin"] as const : []), + ...(refreshTools && !unsupportedRefresh ? ["released-unavailable"] as const : [])] as const) { const portable = path === "portable" || path === "portable-bootstrap"; const bootstrap = path === "portable-bootstrap"; - const pluginRecovery = portable || path === "legacy-plugin"; + const releasedUnavailable = path === "released-unavailable"; + const pluginRecovery = portable || path === "legacy-plugin" || releasedUnavailable; githubAccess.create.mockReset().mockImplementation(async () => ({ env: {}, ready: true, duplexRequested: false, activate: githubAccess.activate.mockReset().mockImplementation(() => vi.fn()), stop: githubAccess.stop.mockReset().mockResolvedValue(undefined) })); const stateBase = await mkdtemp(join(tmpdir(), "paperclip-runnerd-reuse-key-")); @@ -15228,7 +15230,7 @@ describe("native warm session supervision", () => { const projection = vi.spyOn(controllerRecovery, "resolveNativeControllerRecovery").mockResolvedValue({ kind: "no_prior_execution" }); const restore = path === "legacy-plugin" ? vi.spyOn(runnerCheckpoint, "restoreNativeRunnerCheckpoint") .mockImplementation(async (_db, binding) => binding.runId === first.binding.runId && recoveredSession.close.mock.calls.length ? {} as never : null) : undefined; - const issueProjection = path === "legacy-plugin" ? vi.spyOn(issueServiceModule, "issueService") + const issueProjection = path === "legacy-plugin" || releasedUnavailable ? vi.spyOn(issueServiceModule, "issueService") .mockReturnValue({ update: vi.fn(async () => null) } as never) : undefined; try { await executePaperclipNativeSession({ db: leaseDb(first), execution: first, runnerInstanceId: "runner-reuse-key", @@ -15261,14 +15263,26 @@ describe("native warm session supervision", () => { }); } if (pluginRecovery) state.createBackend.mockReturnValueOnce({ - kind: "test", recoverSession: async () => ({ recovered: true, session: recoveredSession }), + kind: "test", recoverSession: async () => { + if (releasedUnavailable) throw new Error("native_runner_reuse_unavailable"); + return { recovered: true, session: recoveredSession }; + }, } as never); + const createOwner = pluginTaskRuntime.createPluginRunnerTaskOwner; + const owners = releasedUnavailable ? vi.spyOn(pluginTaskRuntime, "createPluginRunnerTaskOwner") + .mockImplementation(ownerInput => Object.assign(createOwner(ownerInput), { retiredBeforeClaim: () => true })) : undefined; + const resumeFrom = releasedUnavailable ? vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockResolvedValue("target-task") : undefined; const pluginTaskDescription = { kind: "description", taskId: "target-task", warmTaskVersion: 1, launchPreparationVersion: 1, projectAuthCheckVersion: 1, releaseResumeVersion: 1, + ...(releasedUnavailable ? { executionContextVersion: 1 as const } : {}), runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } } as const; const portableTarget = { ...target, runner: undefined, leaseId: "target-lease", - sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" ? "resumed" : "created", providerLeaseId: "target-task" }, - runnerTask: vi.fn(async (operation: { kind: string }) => { + sandboxLeaseAcquisition: { outcome: path === "legacy-plugin" || releasedUnavailable ? "resumed" : "created", providerLeaseId: "target-task" }, + runnerTask: vi.fn(async (operation: { kind: string }, options?: { executionContext?: unknown }) => { + if (releasedUnavailable && operation.kind === "describe") { + if (options?.executionContext) throw new Error("fixture replacement bound to the old task context"); + return { ...pluginTaskDescription, taskId: "fresh-task" }; + } if (path === "legacy-plugin") { expect(recoveredSession.close).toHaveBeenCalledOnce(); expect(operation.kind).toBe("describe"); @@ -15313,6 +15327,16 @@ describe("native warm session supervision", () => { expect(portableTarget.runnerTask).toHaveBeenCalledOnce(); continue; } + if (releasedUnavailable) { + try { + await continuation; + delete decisions[path]; + expect(portableTarget.runnerTask.mock.calls.map(([operation]) => operation.kind)).toContain("describe"); + expect(state.execute).toHaveBeenCalledTimes(2); + expect(recoveredSession.close).not.toHaveBeenCalled(); + } finally { owners?.mockRestore(); resumeFrom?.mockRestore(); } + continue; + } if (path === "adoption") await expect(continuation).rejects.toThrow("fixture adoption decision recorded"); else await continuation; expect(decisions[path]).toBe(portable ? true : path === "adoption" ? adoptionReuse : reuse); @@ -19598,12 +19622,12 @@ describe("runnerd provider runtime wiring", () => { }); it.each((["codex", "claude"] as const).flatMap(provider => [ - ...[[false, false, false, false], [true, false, false, false], [false, true, false, false], [false, false, true, false], ...(provider === "codex" ? [[false, false, false, true]] : [])] - .map(([unknown, shutdown, journalFailure, deadline]) => [provider, unknown, shutdown, journalFailure, deadline, "idle timeout"] as const), + ...[[false, false, false], [true, false, false], [false, true, false], ...(provider === "codex" ? [[false, false, true]] : [])] + .map(([unknown, shutdown, deadline]) => [provider, unknown, shutdown, deadline, "idle timeout"] as const), ...(["controller restart", "detach failure", "environment deletion", "replacement hand-off"] as const) - .map(retirement => [provider, false, false, false, false, retirement] as const), + .map(retirement => [provider, false, false, false, retirement] as const), ]))( - "releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, journalFailure=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, journalFailure, deadline, retirement) => { + "releases settled %s only under its current owner and retires its cache (unknown=%s, shutdown=%s, deadline=%s, retirement=%s)", async (provider, unknown, shutdown, deadline, retirement) => { await closeIdleWarmNativeSessionsForRestart(); expect(readNativeSessionIdleWork()).toBe("none"); const previousHome = process.env.PAPERCLIP_HOME; @@ -19639,7 +19663,7 @@ describe("runnerd provider runtime wiring", () => { }); let allowPhysicalStop!: () => void; const physicalStop = new Promise(resolve => { allowPhysicalStop = resolve; }); - const close = vi.fn(async () => { if (shutdown || deadline || journalFailure) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {}); + const close = vi.fn(async () => { if (shutdown || deadline) await physicalStop; }), detachControllerForRestart = vi.fn(async () => {}); const session = { release, close, detachControllerForRestart }; const validated = validatePrpStructuredRunResult({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: "Completed", completionClaim: { contractRevision: current.completionContract.contract.revision, @@ -19668,7 +19692,7 @@ describe("runnerd provider runtime wiring", () => { runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true, runnerExecutionTarget: { ...target, runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy"); expect(nextTask).not.toHaveBeenCalled(); - if (provider === "codex" && !unknown && !shutdown && !journalFailure && !deadline) { + if (provider === "codex" && !unknown && !shutdown && !deadline) { await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true, runnerExecutionTarget: { ...target, environmentId: "competing-environment", runnerTask: nextTask, @@ -19699,33 +19723,6 @@ describe("runnerd provider runtime wiring", () => { expect(JSON.parse(await readFile(join(directory, (await readdir(directory))[0]!), "utf8")).releasedRunner).toBeUndefined(); return; } - if (journalFailure) { - const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions"); - const path = join(directory, (await readdir(directory))[0]!); - await rename(path, `${path}.saved`); - await mkdir(path); - let finished = false; - void execute.finally(() => { finished = true; }).catch(() => undefined); - allowRelease(); - await new Promise(resolve => setImmediate(resolve)); - expect(finished).toBe(false); - await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next, - runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true, - managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account", - runnerExecutionTarget: { ...target, remoteCwd: "different-workspace", runnerTask: nextTask } })).rejects.toThrow("native_session_supervisor_busy"); - expect(nextTask).not.toHaveBeenCalled(); - await vi.waitFor(() => expect(close).toHaveBeenCalledOnce()); - expect(readNativeSessionIdleWork()).toBe("present"); - expect(finished).toBe(false); - await rm(path, { recursive: true }); - await rename(`${path}.saved`, path); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined(); - allowPhysicalStop(); - await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId }); - expect(readNativeSessionIdleWork()).toBe("none"); - expect(detachControllerForRestart).not.toHaveBeenCalled(); - return; - } allowRelease(); await expect(execute).resolves.toMatchObject({ sessionId: source.normalizedSessionId }); expect(readNativeSessionIdleWork()).toBe("none"); @@ -19733,21 +19730,20 @@ describe("runnerd provider runtime wiring", () => { const files = await readdir(directory); const path = join(directory, files[0]!); const envelope = JSON.parse(await readFile(path, "utf8")); - expect(envelope.releasedRunner).toMatchObject({ source, taskId: "retained-task", scopeDigest: expect.any(String) }); + expect(envelope.releasedRunner).toBeUndefined(); expect(JSON.stringify(envelope)).not.toContain("synthetic-fixture"); if (!unknown) { const calls = owners.mock.calls.length; - for (const changed of [{ remoteCwd: "different-workspace" }, { runnerTaskProjectIds: ["different-project"] }]) { - await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next, - runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true, - managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account", - runnerExecutionTarget: { ...target, ...changed, runnerTask: nextTask }, - runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch"); - } + await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next, + runnerInstanceId: source.runnerInstanceId, useRunnerd: true, runnerIngressAuthorized: true, + managedAiCredentialHome: home, managedAiCredentialIdentity: "selected-revision", managedAiAccountIdentity: "selected-account", + runnerExecutionTarget: { ...target, runnerTask: nextTask, + sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } }, + runnerEnvironment: provider === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {} })).rejects.toThrow("released_owner_scope_mismatch"); expect(owners).toHaveBeenCalledTimes(calls); expect(nextTask).not.toHaveBeenCalled(); expect(state.execute).toHaveBeenCalledTimes(1); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner); + expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined(); } if (retirement === "environment deletion") { expect(await closeWarmNativeSessionsForEnvironment({ environmentId: target.environmentId, reason: "environment deleted" })) @@ -19762,7 +19758,7 @@ describe("runnerd provider runtime wiring", () => { expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, busy: 0, failed: 1 }); expect(close).not.toHaveBeenCalled(); expect(readNativeSessionIdleWork()).toBe("present"); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner); + expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined(); } detachControllerForRestart.mockResolvedValue(undefined); } @@ -19773,7 +19769,7 @@ describe("runnerd provider runtime wiring", () => { expect(readNativeSessionIdleWork()).toBe("none"); expect(close).not.toHaveBeenCalled(); expect(task.mock.calls.map(([operation]) => (operation as { kind: string }).kind)).toEqual(["describe"]); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(envelope.releasedRunner); + expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined(); if (provider === "codex" && !unknown) { const inspected = vi.spyOn(remoteWarmRecoveryRuntime, "inspectRemoteWarmSessionRecovery").mockImplementation(async request => { request.loadCheckpoint(current); @@ -19790,18 +19786,15 @@ describe("runnerd provider runtime wiring", () => { { runnerExecutionTarget: { ...target, runnerTaskProjectIds: ["different-project"] } }, { runnerExecutionTarget: { ...target, remoteCwd: "different-workspace" } }, { runnerExecutionTarget: { ...target, sandboxLeaseAcquisition: { ...target.sandboxLeaseAcquisition, providerLeaseId: "different-task" } } }, - ]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("released_owner_scope_mismatch"); + ]) await expect(executePaperclipNativeSession({ ...base, ...changed })).rejects.toThrow("fixture completed-source proof checked"); + await writeFile(path, JSON.stringify({ ...envelope, + releasedRunner: { source, taskId: "retained-task", scopeDigest: `sha256:${"0".repeat(64)}` } })); + await expect(executePaperclipNativeSession(base)).rejects.toThrow("fixture completed-source proof checked"); + expect(inspected.mock.calls.at(-1)![0].loadCheckpoint(current)).toMatchObject({ identity: envelope.snapshot.identity }); expect(owners).toHaveBeenCalledTimes(calls); expect(state.execute).toHaveBeenCalledTimes(1); } finally { inspected.mockRestore(); } } - await owners.mock.calls.at(-1)![0].onResumed!(source); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined(); - const replacement = { ...envelope, snapshot: { ...envelope.snapshot, identity: { ...envelope.snapshot.identity, runId: "new-owner" } }, - releasedRunner: { ...envelope.releasedRunner, source: { ...source, runId: "new-owner" } } }; - await writeFile(path, JSON.stringify(replacement)); - await expect(owners.mock.calls.at(-1)![0].onResumed!(source)).rejects.toThrow("released_source_mismatch"); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toEqual(replacement.releasedRunner); } finally { detachControllerForRestart.mockResolvedValue(undefined); registerRunStartHandover(null); @@ -19812,7 +19805,7 @@ describe("runnerd provider runtime wiring", () => { it.each((["codex", "claude"] as const).flatMap(provider => (["current", "stale", ...(provider === "codex" ? ["foreign runner", "foreign lease"] : [])] as const) .map(receipt => [provider, receipt] as const)))( - "records the confirmed %s source after external checkpoint registration and attachment (receipt=%s)", async (provider, receipt) => { + "accepts only the attached %s source's release receipt after external checkpoint registration (receipt=%s)", async (provider, receipt) => { const invalidReceipt = receipt !== "current"; await closeIdleWarmNativeSessionsForRestart(); const previousHome = process.env.PAPERCLIP_HOME; @@ -19884,7 +19877,6 @@ describe("runnerd provider runtime wiring", () => { .toBe("paperclip.runner.external-control-plane-state.v1"); } else { expect(options.existingSession).toBe(session); - await owners.mock.calls[0]![0].onResumed!(source); authority.rotateRunIdentity(successor); await register!(authority, successor); await writeFile(join(root, "runner/runner-state.json"), JSON.stringify(durableRunnerState(successor, "ready"))); @@ -19916,7 +19908,7 @@ describe("runnerd provider runtime wiring", () => { expect(release).toHaveBeenCalledOnce(); const directory = join(resolvePaperclipInstanceRoot(), "runtime/paperclip-runner/sessions"); const path = join(directory, (await readdir(directory))[0]!); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(source); + expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined(); following = run(next); void following.catch(() => undefined); if (invalidReceipt) { @@ -19929,7 +19921,7 @@ describe("runnerd provider runtime wiring", () => { } else { await expect(following).resolves.toMatchObject({ sessionId: source.normalizedSessionId }); expect(release).toHaveBeenCalledTimes(2); - expect(JSON.parse(await readFile(path, "utf8")).releasedRunner.source).toEqual(successor); + expect(JSON.parse(await readFile(path, "utf8")).releasedRunner).toBeUndefined(); expect(close).not.toHaveBeenCalled(); } } finally { diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index d2beb2a39c3..c5d076f232c 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -8746,49 +8746,23 @@ function legacyNativeSessionCheckpointPath( ); } -type ReleasedWarmRunner = { source: DurableRecoveryIdentity; taskId: string; scopeDigest: string }; +const RELEASED_SOURCE_KEYS = ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"] as const; -function releasedWarmScope(input: Parameters[0]): string { - const target = input.runnerExecutionTarget; - return nativeSha256({ companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId, - environmentId: target?.kind === "remote" ? target.environmentId ?? null : null, workspace: nativeSessionWorkspaceScope(input.execution), - cwd: input.execution.workspace.cwd, remoteCwd: target?.kind === "remote" ? target.remoteCwd : null, - projectIds: target?.kind === "remote" && target.transport === "sandbox" ? target.runnerTaskProjectIds ?? [] : [], - accountIdentity: input.managedAiAccountIdentity ?? null, credentialIdentity: input.managedAiCredentialIdentity ?? null }); +function releasedDurableIdentity(identity: Record | null): DurableRecoveryIdentity | undefined { + if (!identity || RELEASED_SOURCE_KEYS.some(key => typeof identity[key] !== "string" || !identity[key])) return undefined; + const field = (key: typeof RELEASED_SOURCE_KEYS[number]) => identity[key] as string; + return { runnerInstanceId: field("runnerInstanceId"), environmentLeaseId: field("environmentLeaseId"), runId: field("runId"), + normalizedSessionId: field("normalizedSessionId"), turnId: field("turnId"), itemId: field("itemId") }; } -function requireReleasedWarmScope(input: Parameters[0], - proof: ReleasedWarmRunner | undefined, identity: unknown): DurableRecoveryIdentity { +function releasedWarmSource(input: Parameters[0], taskId: string | null): DurableRecoveryIdentity { const target = input.runnerExecutionTarget; - if (!proof || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask - || proof.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId - || proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)) { + const source = releasedDurableIdentity(readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))); + if (!source || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask + || taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) { throw new Error("native_session_released_owner_scope_mismatch"); } - return proof.source; -} - -function readWarmNativeEnvelope(execution: NativeExecutionInput): Record | null { - const path = nativeSessionCheckpointPath(execution); - if (!existsSync(path)) return null; - const envelope = record(JSON.parse(readBoundedNativeFile(path, NATIVE_WARM_CHECKPOINT_MAX_BYTES, - "native_session_supervisor_checkpoint_too_large").toString("utf8"))); - if (envelope.schema !== "paperclip.native-session-supervisor.v1") throw new Error("native_session_supervisor_checkpoint_mismatch"); - return envelope; -} - -function releasedWarmRunner(envelope: Record | null): ReleasedWarmRunner | undefined { - if (!envelope || envelope.releasedRunner === undefined) return undefined; - const proof = record(envelope.releasedRunner), source = record(proof.source); - const snapshot = record(envelope.snapshot), identity = record(snapshot.identity); - for (const key of ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"]) { - if (typeof source[key] !== "string" || !source[key]) throw new Error("native_session_released_source_mismatch"); - } - if (typeof proof.taskId !== "string" || !proof.taskId || typeof proof.scopeDigest !== "string" - || identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId) { - throw new Error("native_session_released_source_mismatch"); - } - return proof as ReleasedWarmRunner; + return source; } function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Record): void { @@ -8799,38 +8773,15 @@ function writeWarmNativeEnvelope(execution: NativeExecutionInput, envelope: Reco chmodSync(path, 0o600); } -function updateReleasedWarmRunner(execution: NativeExecutionInput, source: DurableRecoveryIdentity, - taskId: string, proof: ReleasedWarmRunner | null): void { - const envelope = readWarmNativeEnvelope(execution); - const previous = releasedWarmRunner(envelope); - if (!envelope) { - if (proof) throw new Error("native_session_supervisor_checkpoint_missing"); - return; - } - if (!proof && !previous) return; - const identity = record(record(envelope.snapshot).identity); - if (identity.companyId !== execution.binding.companyId || identity.agentId !== execution.binding.agentId - || identity.runId !== source.runId || identity.sessionId !== source.normalizedSessionId - || (previous && (previous.taskId !== taskId || canonicalJson(previous.source) !== canonicalJson(source)))) { - throw new Error("native_session_released_source_mismatch"); - } - if (proof) envelope.releasedRunner = proof; - else delete envelope.releasedRunner; - writeWarmNativeEnvelope(execution, envelope); -} - function persistWarmNativeCheckpoint( execution: NativeExecutionInput, configDigest: string, snapshot: PersistedNativeSession, processConfigDigest?: string, ): void { - const previous = releasedWarmRunner(readWarmNativeEnvelope(execution)); writeWarmNativeEnvelope(execution, { schema: "paperclip.native-session-supervisor.v1", configDigest, processConfigDigest, updatedAt: new Date().toISOString(), snapshot, - ...(previous && previous.source.runId === snapshot.identity.runId - && previous.source.normalizedSessionId === snapshot.identity.sessionId ? { releasedRunner: previous } : {}), }); } @@ -11192,10 +11143,11 @@ async function executePaperclipNativeSessionAttempt( } const cachedReleasedOwner = warmNativeSessions.get(nativeSessionScopeKey(input.execution)); if (cachedReleasedOwner?.released) { - const proof = portableSource ? undefined : releasedWarmRunner(readWarmNativeEnvelope(input.execution)); const identity = readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution)); + const durable = portableSource ? undefined : releasedDurableIdentity(identity); const target = input.runnerExecutionTarget; - const source = portableSource ?? (proof && { taskId: proof.taskId, identity: proof.source }); + const source = portableSource ?? (durable && cachedReleasedOwner.pluginTaskId + ? { taskId: cachedReleasedOwner.pluginTaskId, identity: durable } : undefined); if (source && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId && (portableSource || target.sandboxLeaseAcquisition?.outcome === "created") && source.taskId !== target.sandboxLeaseAcquisition?.providerLeaseId) { @@ -11205,8 +11157,7 @@ async function executePaperclipNativeSessionAttempt( || cachedReleasedOwner.preparingRunId && cachedReleasedOwner.preparingRunId !== input.execution.binding.runId || cachedReleasedOwner.instructionPreparationRunId && !ownInstructionPreparation || cachedReleasedOwner.closeOnReleaseReason) throw new Error("native_session_supervisor_busy"); - if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId || - (proof && (proof.scopeDigest !== releasedWarmScope(input) || canonicalJson(proof.source) !== canonicalJson(identity)))) { + if (source.taskId !== cachedReleasedOwner.pluginTaskId || cachedReleasedOwner.runId !== identity?.runId) { throw new Error("native_session_released_owner_scope_mismatch"); } const wasBusy = cachedReleasedOwner.busy; @@ -11224,7 +11175,7 @@ async function executePaperclipNativeSessionAttempt( } forgetWarmNativeSession(nativeSessionScopeKey(input.execution), cachedReleasedOwner); } finally { cachedReleasedOwner.busy = wasBusy; } - } else requireReleasedWarmScope(input, proof, identity); + } else releasedWarmSource(input, cachedReleasedOwner.pluginTaskId ?? null); } if (input.useRunnerd && canRecoverWarmOwner && !input.backend && input.runnerExecutionTarget?.kind === "remote" && @@ -11260,7 +11211,6 @@ async function executePaperclipNativeSessionAttempt( } if (durableIdentityMatchesSession(identity, input.execution) && identity.runId !== input.execution.binding.runId && runnerdAuthorityLifecycleWithVerifiedBackup({ root, identity, execution: input.execution, allowVerifiedBackup: true }) !== "suspended") { - let releasedSource = portableSource?.identity; remoteWarmRecovery = await inspectRemoteWarmSessionRecovery({ db: input.db, execution: input.execution, target: input.runnerExecutionTarget, identity, portableSourceTaskId: portableSource?.taskId, @@ -11268,19 +11218,15 @@ async function executePaperclipNativeSessionAttempt( resolve(root, "control-plane", "control-plane-state.json"), NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "runner_durable_identity_too_large").toString("utf8"))), matchesExecution: previous => matchesRemoteWarmExecution(previous, input.execution, input.toolRefreshOnResume), - loadCheckpoint: previous => { - if (!portableSource) { - const proof = releasedWarmRunner(readWarmNativeEnvelope(previous)); - if (proof) releasedSource = requireReleasedWarmScope(input, proof, identity); - } - return loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote"); - }, + loadCheckpoint: previous => loadWarmNativeCheckpoint(previous, nativeSessionConfigDigest(previous, "remote"), "remote"), canReuseProcess: previous => !portableSource && !needsCoreGitHubAccess(input) && nativeSessionConfigDigest(previous, "remote") === nativeSessionConfigDigest(input.execution, "remote") && canReuseNativeProcess(input, record(JSON.parse(readBoundedNativeFile(nativeSessionCheckpointPath(previous), NATIVE_WARM_CHECKPOINT_MAX_BYTES, "native_session_supervisor_checkpoint_too_large").toString("utf8"))).processConfigDigest), }) ?? undefined; if (remoteWarmRecovery) { + const releasedSource = portableSource?.identity + ?? (pluginTaskDescription?.releaseResumeVersion === 1 ? releasedDurableIdentity(identity) : undefined); remoteWarmRecovery.releasedSource = releasedSource; if (releasedSource) { const header = await loadNativeRunnerCheckpointHeader(input.db, remoteWarmRecovery.previousExecution.binding).catch((error: unknown) => { @@ -12258,6 +12204,7 @@ async function executePaperclipNativeSessionAttempt( let reusingReleasedRunner = false; let relaunchReleased: { owner?: ReturnType; source: DurableRecoveryIdentity; runner: { version: string; digest: string }; published?: true } | undefined; + let releasedRecoveryOwner: ReturnType | undefined; let managedCredentialSession: NativeSession | undefined; let githubAccess: NativeGitHubAccess | undefined; let releaseGitHubRun: (() => void) | undefined; @@ -12280,8 +12227,7 @@ async function executePaperclipNativeSessionAttempt( const registered = warmNativeSessions.get(warmSessionId); const entry = registered && forgetUnretiredOwnerOnOtherSandbox(warmSessionId, registered, input.runnerExecutionTarget) ? undefined : registered; - const releasedSource = entry?.released ? requireReleasedWarmScope(input, releasedWarmRunner(readWarmNativeEnvelope(input.execution)), - readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))) : undefined; + const releasedSource = entry?.released ? releasedWarmSource(input, entry.pluginTaskId ?? null) : undefined; if (entry || remoteWarmRecovery?.releasedSource) { if (input.execution.provider.kind === "codex" || (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude")) { @@ -12584,7 +12530,10 @@ async function executePaperclipNativeSessionAttempt( pluginTaskDescription, retainedPluginTaskOwner: existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner, relaunchReleased: relaunchReleased ? { source: relaunchReleased.source, runner: relaunchReleased.runner } : undefined, - onPluginTaskOwner: owner => { if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner; }, + onPluginTaskOwner: owner => { + if (relaunchReleased && !relaunchReleased.owner) relaunchReleased.owner = owner; + else if (remoteWarmRecovery?.releasedSource && !releasedRecoveryOwner) releasedRecoveryOwner = owner; + }, beginRetainedRunAttachment: existingWarmSession && reusingReleasedRunner ? beginRetainedRunAttachment(existingWarmSession) : undefined, durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId, remoteWarmRecovery: remoteWarmRecovery ? (recovery => ({ @@ -12618,13 +12567,22 @@ async function executePaperclipNativeSessionAttempt( input.useRunnerd && input.backend === undefined ? await timeController("backend_setup", () => executionContext ? executionContext.wait(createExecutionBackend) : createExecutionBackend()) : null; + let releasedRecoveryUnavailable: Error | undefined; + let recovered: Awaited["recoverSession"]>>> | undefined; if (remoteWarmRecovery) { const recovery = remoteWarmRecovery; if (executionContext) await executionContext.wait(() => recovery.revalidate(leaseOwner)); else await recovery.revalidate(leaseOwner); - const recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, { - signal: executionContext?.signal ?? new AbortController().signal, - }); + try { + recovered = await runnerdBackend?.recoverSession?.(remoteWarmRecovery.checkpoint, { + signal: executionContext?.signal ?? new AbortController().signal, + }); + } catch (error) { + if (!recovery.releasedSource || !(error instanceof Error) || error.message !== "native_runner_reuse_unavailable") throw error; + releasedRecoveryUnavailable = error; + } + } + if (remoteWarmRecovery && !releasedRecoveryUnavailable) { if (!recovered?.recovered || !recovered.session) throw new Error("runner_state_identity_mismatch: remote_warm_session_unproven"); const movedSession = remoteWarmRecovery.portableSourceTaskId !== undefined; // A portable resume already starts a new Runner. Its run attachment @@ -12673,12 +12631,14 @@ async function executePaperclipNativeSessionAttempt( )).then(rows => rows[0]) : null; let remoteCleanupLease = await readRemoteCleanupLease(); - const continueAfterUnavailableReuse = async (error: unknown) => { + const continueAfterUnavailableReuse = async (error: unknown, recovering = false) => { const target = input.runnerExecutionTarget; - const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) : relaunchReleased?.owner; + const releasedRecovery = recovering && remoteWarmRecovery?.releasedSource ? remoteWarmRecovery : undefined; + const retainedOwner = existingWarmSession ? pluginTaskSessionOwners.get(existingWarmSession) + : relaunchReleased?.owner ?? (releasedRecovery ? releasedRecoveryOwner : undefined); if (!(error instanceof Error) || error.message !== "native_runner_reuse_unavailable" || !retainedOwner || retainedOwner.retiredBeforeClaim() !== true - || remoteWarmRecovery || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox" + || (remoteWarmRecovery && !releasedRecovery) || warmConfigDigest === null || target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask || runnerdBackend === null) return false; const retainedTaskId = target.sandboxLeaseAcquisition?.providerLeaseId; if (existingWarmSession) await existingWarmSession.close({ reason: "retained Runner was unavailable for reuse" }); @@ -12690,6 +12650,16 @@ async function executePaperclipNativeSessionAttempt( } } relaunchReleased = undefined; + if (releasedRecovery) { + if (remoteWarmRecoveryPending) { + if (executionContext) await executionContext.wait(() => releasedRecovery.revalidate(leaseOwner)); + else await releasedRecovery.revalidate(leaseOwner); + } + remoteWarmRecovery = undefined; + remoteWarmRecoveryPending = false; + releasedRecoveryOwner = undefined; + await finishStartupContextForFallback(); + } 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; @@ -12701,6 +12671,7 @@ async function executePaperclipNativeSessionAttempt( remoteCleanupLease = await readRemoteCleanupLease(); return true; }; + if (releasedRecoveryUnavailable && !await continueAfterUnavailableReuse(releasedRecoveryUnavailable, true)) throw releasedRecoveryUnavailable; const portTarget = input.runnerExecutionTarget; if (input.useRunnerd && !input.backend && !existingWarmSession && portTarget?.kind === "remote" && portTarget.transport === "sandbox" && portTarget.runner && !portTarget.runnerTask && portTarget.sandboxLeaseAcquisition?.outcome === "resumed" @@ -14121,11 +14092,8 @@ async function executePaperclipNativeSessionAttempt( || entry.pluginTaskId !== target.sandboxLeaseAcquisition?.providerLeaseId) { throw new Error("native_session_released_source_mismatch"); } - const source = operation.identity; - updateReleasedWarmRunner(input.execution, source, entry.pluginTaskId, - { source, taskId: entry.pluginTaskId, scopeDigest: releasedWarmScope(input) }); } catch { - entry.closeOnReleaseReason = "released Runner source proof could not be verified or saved"; + entry.closeOnReleaseReason = "released Runner source could not be verified"; await closeWarmNativeSession(entry, entry.closeOnReleaseReason); forgetWarmNativeSession(scope, entry); return; @@ -16998,8 +16966,6 @@ async function createRunnerdBackendWithinSessionClaim( releasedSource: input.remoteWarmRecovery?.releasedSource, releasedSourceRunner: input.remoteWarmRecovery?.releasedSourceRunner, sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId, - onResumed: async source => updateReleasedWarmRunner(input.execution, source, input.remoteWarmRecovery?.portableSourceTaskId ?? description.taskId, null), - onRetired: async source => updateReleasedWarmRunner(input.execution, source, description.taskId, null), adoptIdentity: adoptionIdentity ?? (adopting && prior ? { runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId, runId: prior.runId, normalizedSessionId: prior.normalizedSessionId, 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 794f42e1498..1cacf5ebcd6 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 @@ -311,7 +311,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false }); await waitForCondition("automatic release A", () => releases.length === 1); expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } }); - expect(await proof()).toMatchObject({ source: releases[0], taskId: taskA }); + expect(await proof()).toBeUndefined(); const providerSessionId = (await supervisor()).snapshot.providerSessionId; expect(providerSessionId).toEqual(expect.any(String)); if (detached) await new Promise(done => setTimeout(done, detachedIdleTimeoutMs + 200)); @@ -401,7 +401,7 @@ describeEmbeddedPostgres("plugin Runner eviction through the Core execution entr const runB = await admitNext(); if (denied || mode === "bare unavailable") return; await waitForCondition("automatic release B", () => releases.length === 2); - expect(await proof()).toMatchObject({ source: releases[1], taskId: taskB }); + expect(await proof()).toBeUndefined(); expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId); const methods = (await readFile(calls, "utf8")).trim().split(/\r?\n/); expect(submissions).toBe(2); 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 4600c8aaa75..91ee51fe91b 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 @@ -310,7 +310,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false }); await waitForCondition("automatic release A", () => releases.length === 1); expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)))[0]).toMatchObject({ schemaStatus: "accepted", resultJson: { result: { reportedWorkDisposition: "done" } } }); - expect(await proof()).toMatchObject({ source: releases[0], taskId }); + expect(await proof()).toBeUndefined(); const providerSessionId = (await supervisor()).snapshot.providerSessionId; expect(providerSessionId).toEqual(expect.any(String)); const pid = handle!.child.pid; @@ -324,7 +324,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] }); } else await new Promise(done => setTimeout(done, adoptedIdleTimeoutMs + 200)); expect(stops).toBe(0); expect(handle!.isExitConfirmed?.()).toBe(false); - expect(await proof()).toMatchObject({ source: releases[0], taskId }); + expect(await proof()).toBeUndefined(); } expect(readNativeSessionIdleWork()).toBe("none"); await reconcileNativeFinalizations(db, [runId]); @@ -358,7 +358,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio expect(handle!.isExitConfirmed!()).toBe(true); expect((await readFile(calls, "utf8")).split(/\r?\n/).filter(method => method === "turn/start")).toHaveLength(1); expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runB)))).toHaveLength(0); - expect(releases).toHaveLength(1); expect((await proof())?.source.runId).not.toBe(runB); + expect(releases).toHaveLength(1); expect(await proof()).toBeUndefined(); return runB; } expect(await pendingFollowup).toMatchObject({ exitCode: 0, timedOut: false }); @@ -369,7 +369,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio const runB = await admitNext(); if (cancellation) return; await waitForCondition("automatic release B", () => releases.length === 2); - expect(await proof()).toMatchObject({ source: releases[1], taskId }); + expect(await proof()).toBeUndefined(); 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 } } }); @@ -377,7 +377,7 @@ describeEmbeddedPostgres("plugin Runner release/resume through the Core executio if (adopted) { 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(releases[2]!.runId).toBe(runC); expect(await proof()).toBeUndefined(); expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId); expect(adoption).toHaveBeenCalledTimes(1); } 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 2f8bb99a885..4225721a1d4 100644 --- a/server/src/services/native-runtime/plugin-runner-task.test.ts +++ b/server/src/services/native-runtime/plugin-runner-task.test.ts @@ -615,17 +615,11 @@ describe("plugin Runner release/resume facade", () => { it.each([ ["the parked build", undefined], ["a relaunched build", { version: "0.4.1", digest: `sha256:${"b".repeat(64)}` }], - ])("clears the released Runner proof after a resume on %s, once Core saved a relaunched build", async (_label, runner) => { + ])("passes the provider's resume outcome through on %s", async (_label, runner) => { const task = vi.fn(async (): Promise => ({ kind: "resume", taskId: "task", outcome: "resumed", ...(runner ? { runner } : {}) })); - const onResumed = vi.fn(async () => {}); - const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, onResumed, resumeRelaunchedRunnerVersion: 1 }); + const owner = createPluginRunnerTaskOwner({ ...input("codex"), task, resumeRelaunchedRunnerVersion: 1 }); const outcome = await owner.driver.releaseResume!.resume(requirements.identity, "transient-ticket"); - if (runner) { - expect(outcome).toEqual({ outcome: "resumed", runner, settled: expect.any(Function) }); - expect(onResumed).not.toHaveBeenCalled(); - if (typeof outcome === "object") await outcome.settled?.(); - } else expect(outcome).toBe("resumed"); - expect(onResumed).toHaveBeenCalledExactlyOnceWith(requirements.identity); + expect(outcome).toEqual(runner ? { outcome: "resumed", runner } : "resumed"); }); it("resumes with the credential resolved for the rebound claimant run", async () => { @@ -814,14 +808,14 @@ describe("plugin Runner relaunch as the claimant run", () => { 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; fresh?: true } = { resumeIdentityVersion: 1 }) { + options: { resumeIdentityVersion?: 1; fresh?: true } = { 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 relaunchInput = { ...base, task, authorityRunId: next.runId, resumeRelaunchedRunnerVersion: 1 as const, - resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked }, onResumed: options.onResumed }; + resumeIdentityVersion: options.resumeIdentityVersion, relaunch: { source, runner: parked } }; const owner = createPluginRunnerTaskOwner(options.fresh ? relaunchInput : { ...base, task, adoptIdentity: source, authorityRunId: source.runId }); if (!options.fresh) owner.rebind(relaunchInput); await prepare(owner, { ...requirements, identity: next }); @@ -831,10 +825,8 @@ describe("plugin Runner relaunch as the claimant run", () => { } 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 }); + () => ({ kind: "resume", taskId: "task", outcome: "resumed", runner: build, archivedState: settledCut })); expect(owner.driver.relaunchReleasedRunner).toEqual(source); expect(owner.driver.adoptExistingRunner).toBeUndefined(); expect(owner.relaunchMayHaveStarted()).toBe(false); @@ -848,7 +840,6 @@ describe("plugin Runner relaunch as the claimant run", () => { }]); 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, @@ -897,19 +888,14 @@ describe("plugin Runner relaunch as the claimant run", () => { } 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 })); + it("takes the provider's resumed answer without re-checking its archived state", async () => { + const { authority, registration, owner } = await relaunchOwner(() => ({ kind: "resume", taskId: "task", outcome: "resumed", + runner: build, archivedState: { ...settledCut, outbox: [{ sourceSeq: 4 }] } })); 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(); + await registration.ready(); + expect(authority.acceptRelaunchedRunner).toHaveBeenCalledExactlyOnceWith("synthetic-ticket", build, parked); } finally { await registration.release("detach"); } }); diff --git a/server/src/services/native-runtime/plugin-runner-task.ts b/server/src/services/native-runtime/plugin-runner-task.ts index fe2fb1fe526..a578b9bd246 100644 --- a/server/src/services/native-runtime/plugin-runner-task.ts +++ b/server/src/services/native-runtime/plugin-runner-task.ts @@ -5,7 +5,7 @@ import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvir 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, - isSettledReleasedRunnerCut } from "../../vendor/paperclip-runner/index.js"; +} from "../../vendor/paperclip-runner/index.js"; import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js"; import type { NativeExecutionContext } from "./native-execution-context.js"; @@ -60,8 +60,6 @@ export function createPluginRunnerTaskOwner(input: { launchDigestVersion?: 1; releasedSource?: DurableRecoveryIdentity; sessionHandoff?: boolean; - onResumed?: (identity: DurableRecoveryIdentity) => Promise; - onRetired?: (identity: DurableRecoveryIdentity) => Promise; githubBroker?: { url: string; token: string }; githubCredentialBrokerVersion?: 1; configuredEnvironmentVersion?: 1; @@ -262,11 +260,8 @@ export function createPluginRunnerTaskOwner(input: { 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"); - } + if (!result.runner) throw new Error("native_runner_released_state_unsettled"); authority.acceptRelaunchedRunner(native.ticket, result.runner, relaunch.runner); - await input.onResumed?.(source); markReady(); return; } @@ -429,8 +424,6 @@ export function createPluginRunnerTaskOwner(input: { if (submitted) { await call({ kind: "complete" }); completed = true; - const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity; - if (identity) await input.onRetired?.(identity); } }, // The Runner is about to exit (its close suspend completed), as on release. @@ -469,10 +462,7 @@ export function createPluginRunnerTaskOwner(input: { if (activeOutbound === outbound) activeOutbound = null; }, resume: async (identity: DurableRecoveryIdentity, ticket: string) => { - const outcome = await resume(identity, ticket); - if (typeof outcome === "object") return { ...outcome, settled: async () => { await input.onResumed?.(identity); } }; - if (outcome === "resumed") await input.onResumed?.(identity); - return outcome; + return await resume(identity, ticket); }, }; }, @@ -555,8 +545,6 @@ export function createPluginRunnerTaskOwner(input: { } await call({ kind: "complete" }); completed = true; - const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity; - if (identity) await input.onRetired?.(identity); } return stoppedState?.executionStopped === true && completed && !detached; }; diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index f12c6ca28c8..aecf56079dc 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -101,7 +101,6 @@ 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; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index a849307dc1c..36e0f356584 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": "5557e21415c67aca5c2dff7e06e8ea590f6c582e", + "packages/plugins/sdk/src/environment-tasks.ts": "9e288a2eb9d5c396244feb247f09c570b5b0f621", "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",