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 272976eb92d..d40cf055daa 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1,4 +1,4 @@ -import { nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js"; +import { compareAndSealRetiredComputerCheckpoint, retiredComputerCheckpointIsSettled, retireUnlaunchedComputerAttempt, nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js"; import { prepareHeartbeatGitHubLaunchers } from "../heartbeat-github-launchers.js"; import { gunzipSync } from "node:zlib"; import { configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js"; @@ -7698,7 +7698,7 @@ describe("native warm session supervision", () => { const name = `computer-owner-${suffix}`; const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name, executionWorkspaceId: name }, session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; - const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async () => true); + const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); const target = { kind: "remote" as const, transport: "computer" as const, environmentId: "shared-computer", remoteCwd: `/home/user/${name}`, listenerPort: suffix === "a" ? 45001 : 45002, resourceAuthority: { kind: "computer-owner", computerId: "computer", ownerId: name, generation: 1 }, @@ -7731,7 +7731,7 @@ describe("native warm session supervision", () => { const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name, executionWorkspaceId: name }, session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; const firstClose = vi.fn(async () => undefined), secondClose = vi.fn(async () => undefined); - const firstRetire = vi.fn(async () => true), secondRetire = vi.fn(async () => true); + const firstRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }), secondRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`, resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: "prior-owner", generation: 1 }, retainWarm: vi.fn(async () => undefined), retire: firstRetire }; @@ -7768,7 +7768,7 @@ describe("native warm session supervision", () => { const detachControllerForRestart = vi.fn(async () => undefined); const session = { close, detachControllerForRestart }; let generation = 1; - const retire = vi.fn(async () => generation === 1); + const retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { if (generation !== 1) return false; await options?.beforeStop?.(); return true; }); const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`, resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, retainWarm: vi.fn(async () => undefined), retire }; @@ -7796,14 +7796,14 @@ describe("native warm session supervision", () => { expect(close).not.toHaveBeenCalled(); expect(detachControllerForRestart).not.toHaveBeenCalled(); const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } }; - const nextRetire = vi.fn(async () => true); + const nextRetire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { await options?.beforeStop?.(); return true; }); await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: name, runnerEnvironment: await environmentForRun(next.binding.runId), runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, generation: 2 }, retire: nextRetire } as never }); await closeWarmNativeSessionsForRun({ runId: next.binding.runId, reason: "fixture cleanup" }); expect(nextRetire).toHaveBeenCalledOnce(); - expect(detachControllerForRestart).toHaveBeenCalledOnce(); - expect(close).not.toHaveBeenCalled(); + expect(detachControllerForRestart).not.toHaveBeenCalled(); + expect(close).toHaveBeenCalledOnce(); } finally { vi.useRealTimers(); } }); @@ -13512,6 +13512,49 @@ describe("runnerd provider runtime wiring", () => { } finally { await rm(root, { recursive: true, force: true }); } }); + it("keeps computer checkpoints remote through close and the next session preparation", async () => { + const remoteRoot = "/remote/persistent-agent"; + const runnerId = "persistent-computer-runner"; + const runnerState = { schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended", runnerInstanceId: runnerId, + normalizedSessionId: execution.session.normalizedSessionId, runId: execution.binding.runId }; + const providerState = { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "durable-thread", + activeProviderTurnId: null, config: { provider: "codex", driver: "codex_app_server" } }; + const syncOut = vi.fn(async () => { throw new Error("persistent checkpoint must not copy back"); }); + const syncIn = vi.fn(async () => { throw new Error("persistent checkpoint must not restore host history"); }); + const remoteExecute = vi.fn(async (command: { command: string; args?: string[] }) => { + const script = command.args?.[1] ?? ""; + let stdout = ""; + if (command.args?.[0] === "--build-metadata") stdout = JSON.stringify({ + schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", packageName: "@paperclipai/paperclip-runner", + binaryContractVersion: 2, durableSessionCapabilities: ["unlimited_runtime", "connection_lease_renewal"], prpTransportModes: ["listen_ws"], + }); + else if (command.args?.[0] === "--version") stdout = "codex-cli 0.160.0"; + else if (script.includes("command -v paperclip-runnerd")) stdout = "/usr/bin/paperclip-runnerd\n"; + else if (script.includes("command -v codex")) stdout = "/usr/bin/codex\n"; + else if (script.includes("base64 <")) stdout = Buffer.from(JSON.stringify(script.endsWith("codex-provider-state.json'") ? providerState : runnerState)).toString("base64"); + if (script.includes("tar ")) throw new Error("persistent checkpoint must not archive"); + return { exitCode: 0, timedOut: false, signal: null, stdout, stderr: "" }; + }); + const target = { kind: "remote", transport: "computer", environmentId: "environment", leaseId: "lease", providerKey: "boat", + remoteCwd: remoteRoot, listenerPort: 43127, effectiveCapabilities: { runnerWebSocketIngress: true }, + fileAuthority: { kind: "remote-persistent", root: remoteRoot, agentHome: remoteRoot, placementId: "placement" }, + runner: { execute: remoteExecute, syncIn, syncOut }, processRunner: { execute: remoteExecute, syncIn, syncOut }, + getRunnerIngressEndpoint: async () => ({ url: "wss://example.test/runner", close: async () => undefined }) }; + await createRunnerdBackend({ db: leaseDb(execution), execution, runnerInstanceId: runnerId, + runnerIngressAuthorized: true, runnerExecutionTarget: target as never }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const transport = state.createTransport.mock.calls.at(-1)![0] as RunnerTransportOptions & { + controlPlaneRegistration: (authority: unknown) => Promise<{ checkpoint: (settlement: string) => Promise }>; + prepareExternalRunnerState: () => Promise; + }; + const registration = await transport.controlPlaneRegistration({}); + await expect(registration.checkpoint("settled")).resolves.toBeUndefined(); + expect(remoteExecute.mock.calls.some(([command]) => command.args?.[1]?.endsWith("codex-provider-state.json'"))).toBe(true); + await expect(transport.prepareExternalRunnerState()).resolves.toBeUndefined(); + expect(syncOut).not.toHaveBeenCalled(); expect(syncIn).not.toHaveBeenCalled(); + await expect(access(join(transport.stateDirectory!, "failover-backups", "current"))).rejects.toThrow(); + }); + it.each([ { override: undefined, expected: "@openai/codex@0.160.0" }, { override: "@openai/codex@0.159.0", expected: "@openai/codex@0.159.0" }, @@ -13792,3 +13835,145 @@ describe("computer provider-pack bootstrap policy", () => { expect(nativeSessionBootstrapTimeoutMs(provider, target)).toBe(expected); }); }); + +describe("computer idle authority transition", () => { + function settled() { + const identity = { runId: execution.binding.runId, normalizedSessionId: execution.session.normalizedSessionId!, + runnerInstanceId: "prior-runner", environmentLeaseId: "prior-lease", turnId: "turn", itemId: "item" }; + const current = { ...execution, binding: { ...execution.binding, runId: "next-run" } }; + const checkpoint = { driverKind: "codex_app_server", providerSessionId: "thread", activeTurnId: null, + pendingRuntimeRequests: [], identity: { ...execution.binding, sessionId: execution.session.normalizedSessionId } }; + return { identity, execution: current, priorExecution: execution, + runner: { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready", outbox: [], pendingTerminalDelivery: null }, + control: { identity, commands: [{ status: "completed" }], committedEvents: [{ eventType: "run.terminal", envelope: identity }] }, + provider: { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "thread", + config: { provider: "codex", driver: "codex_app_server" }, activeProviderTurnId: null, completedTurnAuthoritative: true }, + checkpoint, currentCheckpoint: { ...checkpoint, identity: { ...checkpoint.identity, runId: current.binding.runId } } }; + } + + it("requires a terminal provider checkpoint with matching prior and successor scope", () => { + expect(retiredComputerCheckpointIsSettled(settled())).toBe(true); + }); + it.each(["pending-command", "pending-event", "unsettled-provider", "wrong-run", "wrong-thread", "active-turn", "config-change", "acpx"])( + "does not manufacture suspension from %s evidence", (condition) => { + const input = settled(); + if (condition === "pending-command") input.control.commands[0]!.status = "pending"; + if (condition === "pending-event") (input.runner.outbox as unknown[]).push({ event: "unacked" }); + if (condition === "unsettled-provider") input.provider.completedTurnAuthoritative = false; + if (condition === "wrong-run") input.currentCheckpoint.identity.runId = "foreign"; + if (condition === "wrong-thread") input.currentCheckpoint.providerSessionId = "foreign"; + if (condition === "active-turn") Object.assign(input.currentCheckpoint, { activeTurnId: "active" }); + if (condition === "config-change") input.execution = { ...input.execution, provider: { ...input.execution.provider, model: "changed" } }; + if (condition === "acpx") input.execution = { ...input.execution, provider: { ...input.execution.provider, kind: "acpx" } } as typeof input.execution; + expect(retiredComputerCheckpointIsSettled(input)).toBe(false); + }); + + it.each(["unchanged", "runner-changed", "provider-changed", "symlink", "interrupted"])( + "atomically seals only the unchanged remote bytes (%s)", async (condition) => { + const root = await mkdtemp(join(tmpdir(), "computer-retired-cas-")); + const runnerPath = join(root, "runner.json"), providerPath = join(root, "provider.json"); + const runnerBytes = Buffer.from(JSON.stringify(settled().runner)), providerBytes = Buffer.from(JSON.stringify(settled().provider)); + await writeFile(runnerPath, runnerBytes); await writeFile(providerPath, providerBytes); + const runner = { execute: async (command: { command: string; args?: string[] }) => { + if (condition === "runner-changed") await writeFile(runnerPath, JSON.stringify({ lifecycle: "active" })); + if (condition === "provider-changed") await writeFile(providerPath, JSON.stringify({ activeTurn: "new" })); + if (condition === "symlink") { await rm(runnerPath); await symlink(providerPath, runnerPath); } + if (condition === "interrupted") return { exitCode: null, signal: "SIGTERM", timedOut: true, stdout: "", stderr: "" }; + try { return { exitCode: 0, signal: null, timedOut: false, stderr: "", stdout: execFileSync(command.command, command.args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; } + catch { return { exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "CAS refused" }; } + } }; + try { + const action = compareAndSealRetiredComputerCheckpoint({ runner: runner as never, runnerPath, providerPath, runnerBytes, providerBytes }); + if (condition === "unchanged") { + await expect(action).resolves.toBeUndefined(); + expect(JSON.parse(await readFile(runnerPath, "utf8"))).toEqual({ ...settled().runner, lifecycle: "suspended" }); + } else { + await expect(action).rejects.toThrow("runner_remote_retirement_checkpoint_cas_failed"); + expect(JSON.parse(await readFile(runnerPath, "utf8")).lifecycle).not.toBe("suspended"); + } + expect((await readdir(root)).filter(name => name.startsWith(".retired-checkpoint-"))).toEqual([]); + } finally { await rm(root, { recursive: true, force: true }); } + }); + + it.each(["unlaunched", "launched", "claimed", "unknown", "superseded"])( + "permits same-run admission retry only after exact prelaunch retirement (%s)", async condition => { + let active = true; + const retire = vi.fn(async () => { if (condition === "superseded") return false; active = false; return true; }); + const inspectProcess = vi.fn(async () => { + if (condition === "unknown") throw new Error("inspection unavailable"); + return { running: false, claim: condition === "claimed" ? { nonce: "prior-process" } : null }; + }); + const target = { kind: "remote", transport: "computer", inspectProcess, retire } as never; + const action = retireUnlaunchedComputerAttempt(target, condition === "launched"); + if (["unknown", "superseded"].includes(condition)) await expect(action).rejects.toThrow(); + else await expect(action).resolves.toBeUndefined(); + const admitSameRun = () => { if (active) throw new Error("Computer session already has an active turn"); }; + if (condition === "unlaunched") expect(admitSameRun).not.toThrow(); + else expect(admitSameRun).toThrow("active turn"); + if (["launched", "claimed", "unknown"].includes(condition)) expect(retire).not.toHaveBeenCalled(); + }); +}); + +describe("computer graceful idle reservation", () => { + it.each(["codex", "acpx"])("suspends %s before retiring descendants and admits the next idle turn", async kind => { + const name = `graceful-idle-${kind}`; + const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name }, + provider: kind === "codex" ? execution.provider : { kind: "acpx", agent: "claude", model: null }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; + let phase = "active"; + let checkpoint = "ready"; + const close = vi.fn(async () => { expect(phase).toBe("retiring"); checkpoint = "suspended"; }); + const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent", + resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, + retainWarm: async () => { phase = "warm"; }, + retire: vi.fn(async (options?: { beforeStop?: () => Promise }) => { + phase = "retiring"; + await options?.beforeStop?.(); + expect(checkpoint).toBe("suspended"); + phase = "retired"; + return true; + }) }; + const result = { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name, + normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1, + highestContiguousSourceSeq: 1, usage: null }; + state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close }); return result; }) + .mockImplementationOnce(async options => { expect(options.existingSession).toBeUndefined(); expect(checkpoint).toBe("suspended"); return result; }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, runnerExecutionTarget: target as never }); + await vi.advanceTimersByTimeAsync(60_000); + expect(phase).toBe("retired"); expect(close).toHaveBeenCalledOnce(); + const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } }; + await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: `${name}-fresh`, + runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, ownerId: "new-owner" } } as never }); + } finally { vi.useRealTimers(); } + }); + + it.each(["failed-close", "expired-reservation", "superseded"])("does not report clean close when %s", async condition => { + const name = `graceful-${condition}`; + const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name }, + session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1; + const close = vi.fn(async () => { throw new Error("protocol close failed"); }); + const detach = vi.fn(async () => undefined); + let retired = false; + const retire = vi.fn(async (options?: { beforeStop?: () => Promise }) => { + if (condition === "superseded") return false; + if (condition === "failed-close") await options?.beforeStop?.().catch(() => undefined); + retired = true; + return true; + }); + state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close, detachControllerForRestart: detach }); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name, + normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1, + highestContiguousSourceSeq: 1, usage: null }; }); + await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, + runnerExecutionTarget: { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent", + resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 }, + retainWarm: async () => undefined, retire } as never }); + const result = await closeWarmNativeSessionsForRun({ runId: name, reason: "cancel exact task" }); + expect(result.failed).toBe(1); + expect(retired).toBe(condition !== "superseded"); + if (condition === "superseded") { expect(close).not.toHaveBeenCalled(); expect(detach).not.toHaveBeenCalled(); } + else expect(detach).toHaveBeenCalledOnce(); + }); +}); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 2129dc862b8..fb970884ff3 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -473,35 +473,51 @@ type WarmNativeSession = { lastActivityAt: string; }; +/** A scoped preparation failure is retryable only after exact retirement fences + * queued commands. A process claim or invoked launcher keeps normal recovery. */ +export async function retireUnlaunchedComputerAttempt( + target: AdapterExecutionTarget | null | undefined, + launchAttempted: boolean, +): Promise { + if (target?.kind !== "remote" || target.transport !== "computer" || launchAttempted) return; + const process = await target.inspectProcess(); + if (process.running || process.claim !== null) return; + if (!(await target.retire())) throw new NativeSessionCleanupQuarantinedError(); +} + class ComputerOwnerSupersededError extends Error { constructor() { super("computer_owner_retirement_superseded"); } } async function closeWarmNativeSession(entry: WarmNativeSession, reason: string, preserveInstructionsForRunId?: string) { - // Computer admission can advance while an old idle timer is firing. Only - // the exact durable owner may stop the runner or its controller transport. - if (entry.computerTarget && !(await entry.computerTarget.retire())) { + let closeFailure: unknown; + let closeCompleted = false; + const close = async () => { + try { await entry.session.close({ reason }); closeCompleted = true; } + catch (error) { closeFailure = error; throw error; } + }; + // Reserve the exact generation before protocol close. A winning admission + // must never receive a stale controller's suspend/kill command. The module + // always hard-retires descendants after the bounded graceful window. + if (entry.computerTarget && !(await entry.computerTarget.retire({ beforeStop: close }))) { throw new ComputerOwnerSupersededError(); } - // Revoke before awaiting process retirement/checkpoint IO. const stopping = entry.githubAccess?.stop(); try { try { - if (entry.computerTarget && entry.session.detachControllerForRestart) { - await entry.session.detachControllerForRestart(); - } else { - await entry.session.close({ reason }); + if (!entry.computerTarget) await close(); + if (closeFailure || !closeCompleted) { + await entry.session.detachControllerForRestart?.(); + throw closeFailure ?? new NativeSessionCleanupQuarantinedError(); } - } - catch (error) { + } catch (error) { try { await entry.instructionWorkingCopy?.retirementFailed?.(); } catch (receiptError) { throw new AggregateError([error, receiptError], "Warm instruction retirement and receipt both failed"); } throw error; } await entry.instructionWorkingCopy?.collectStopped(); if (entry.instructionCopy?.runId !== preserveInstructionsForRunId) await entry.instructionCopy?.collectStopped(); - } - finally { await stopping; } + } finally { await stopping; } } const warmNativeSessions = new Map(); @@ -8746,6 +8762,8 @@ async function executePaperclipNativeSessionWithinScope( }, } : input.execution; + let remoteLaunchAttempted = false; + let remoteBackendPreparationStarted = false; const leaseRenewal = startNativeSessionExecutionLeaseRenewal({ db: input.db, runId: input.execution.binding.runId, @@ -8773,6 +8791,7 @@ async function executePaperclipNativeSessionWithinScope( input.db, input.execution.binding, ); + remoteBackendPreparationStarted = input.useRunnerd === true && input.backend === undefined; const runnerdBackend = input.useRunnerd && input.backend === undefined ? await createRunnerdBackend({ @@ -8783,6 +8802,7 @@ async function executePaperclipNativeSessionWithinScope( execution: input.execution, runnerInstanceId: effectiveRunnerInstanceId, durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId, + onRemoteLaunchAttempt: () => { remoteLaunchAttempted = true; }, trace, toolTrace, }) @@ -9168,6 +9188,15 @@ async function executePaperclipNativeSessionWithinScope( // with a retry or release the still-live runner's lease. throw new NativeControllerDetachedForRestartError(); } + if (remoteBackendPreparationStarted) { + try { + await retireUnlaunchedComputerAttempt(input.runnerExecutionTarget, remoteLaunchAttempted); + } catch { + // Failure to establish the exact tombstone leaves queued commands or + // a lost launch acknowledgement ambiguous. Never retry that owner. + error = new NativeSessionCleanupQuarantinedError(); + } + } const protocolIntegrityFailure = error instanceof NativeSessionProtocolIntegrityError ? error : null; const ownershipUnverified = @@ -10823,6 +10852,134 @@ export async function syncRemoteRunnerDirectoryOut(input: { } } +/** A dead computer runner may retain a ready checkpoint after controller loss. + * Match the local quiescent-recovery proof before sealing it for normal rotation. + */ +export function retiredComputerCheckpointIsSettled(input: { + execution: NativeExecutionInput; + priorExecution: NativeExecutionInput; + identity: RunnerdDurableIdentity; + runner: Record; + control: Record; + provider: Record; + checkpoint: Record; + currentCheckpoint: Record; +}): boolean { + const { execution, priorExecution, identity, runner, control, provider, checkpoint, currentCheckpoint } = input; + if (execution.provider.kind !== "codex" || priorExecution.provider.kind !== "codex") return false; + const events = control.committedEvents; + const commands = control.commands; + const terminal = record(record(Array.isArray(events) ? events.at(-1) : null).envelope); + const fields = ["runId", "normalizedSessionId", "runnerInstanceId", "environmentLeaseId", "turnId", "itemId"] as const; + if (runner.schema !== RUNNERD_STATE_SCHEMA || runner.lifecycle !== "ready" || + fields.some(key => runner[key] !== identity[key] || record(control.identity)[key] !== identity[key]) || + !Array.isArray(runner.outbox) || runner.outbox.length !== 0 || runner.pendingTerminalDelivery !== null || + !Array.isArray(commands) || commands.some(command => record(command).status !== "completed") || + !Array.isArray(events) || record(events.at(-1)).eventType !== "run.terminal" || + terminal.runId !== identity.runId || terminal.normalizedSessionId !== identity.normalizedSessionId || + provider.completedTurnAuthoritative !== true || priorExecution.binding.runId !== identity.runId || + priorExecution.binding.issueId !== execution.binding.issueId || + nativeSessionScopeKey(priorExecution) !== nativeSessionScopeKey(execution) || + nativeSessionConfigDigest(priorExecution) !== nativeSessionConfigDigest(execution)) return false; + const providerIdentity = providerSessionIdentityFromDurableProviderState({ execution: priorExecution, providerState: provider }); + if (!providerIdentity.providerSessionId) return false; + return [checkpoint, currentCheckpoint].every((value, index) => { + const binding = record(value.identity); + return value.providerSessionId === providerIdentity.providerSessionId && + value.driverKind === priorExecution.session.driverKind && value.activeTurnId === null && + Array.isArray(value.pendingRuntimeRequests) && value.pendingRuntimeRequests.length === 0 && + binding.runId === (index === 0 ? identity.runId : execution.binding.runId) && + binding.sessionId === identity.normalizedSessionId && binding.companyId === execution.binding.companyId && + binding.agentId === execution.binding.agentId && binding.issueId === execution.binding.issueId; + }); +} + +async function sealRetiredComputerRunnerState(input: { + db: Db; execution: NativeExecutionInput; root: string; + target: Extract; + runner: CommandManagedRuntimeRunner; stateDirectory: string; +}): Promise { + const identity = readRunnerdDurableIdentity(input.root); + if (!identity || identity.runId === input.execution.binding.runId || input.execution.provider.kind !== "codex") return; + if (!durableIdentityMatchesSession(identity, input.execution)) throw new Error("runner_remote_retirement_scope_mismatch"); + const controlPath = resolve(input.root, "control-plane", "control-plane-state.json"); + const controlBytes = readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large"); + const runnerPath = posix.join(input.stateDirectory, "runner-state.json"); + const providerPath = posix.join(input.stateDirectory, runnerProviderStateFilename(input.execution)); + const read = await input.runner.execute({ command: "python3", args: ["-c", String.raw` +import sys,os,stat,json,base64 +rows=[] +for p in sys.argv[1:]: + s=os.lstat(p) + if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state') + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217) + if len(data)>16777216:raise RuntimeError('unsafe recovery state') + rows.append(base64.b64encode(data).decode()) +print(json.dumps(rows))`, runnerPath, providerPath], bypassSession: true, timeoutMs: 10_000 }); + if (read.exitCode !== 0 || read.timedOut) throw new Error("runner_remote_retirement_state_unavailable"); + const [runnerBytes, providerBytes] = (JSON.parse(read.stdout) as string[]).map(value => Buffer.from(value, "base64")); + const runner = record(JSON.parse(runnerBytes!.toString("utf8"))); + if (runner.lifecycle === "suspended") return; + const runs = await input.db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, runnerProfileJson: heartbeatRuns.runnerProfileJson }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.execution.binding.companyId), + eq(heartbeatRuns.agentId, input.execution.binding.agentId), + inArray(heartbeatRuns.id, [identity.runId, input.execution.binding.runId]))); + const prior = runs.find(run => run.id === identity.runId); + const current = runs.find(run => run.id === input.execution.binding.runId); + if (!prior || !current || !TERMINAL_HEARTBEAT_RUN_STATUSES.has(prior.status)) + throw new Error("runner_remote_retirement_authority_unverified"); + const profile = record(prior.runnerProfileJson); + const previous = parseNativeExecutionInput(profile.nativeExecutionInput); + if (!retiredComputerCheckpointIsSettled({ execution: input.execution, priorExecution: previous, identity, runner, + control: record(JSON.parse(controlBytes.toString("utf8"))), provider: record(JSON.parse(providerBytes!.toString("utf8"))), + checkpoint: record(profile.sessionCheckpoint), currentCheckpoint: record(record(current.runnerProfileJson).sessionCheckpoint) }) || + await verifyPriorRunnerdStateForSessionScope({ db: input.db, root: input.root, identity, execution: input.execution, + allowVerifiedBackup: false, allowRetainedWarmRunner: false, remoteRunnerState: true, runnerExecutionTarget: input.target }) !== "verified") + throw new Error("runner_remote_retirement_checkpoint_unsettled"); + // Recheck exact durable retirement after all awaited reads; never infer death + // from a missing PID or turn status. The compare-and-swap preserves ambiguity. + const workspace = readNativeComputerWorkspaceReference(profile.nativeComputerWorkspace); + if (!workspace || !input.target.environmentId || !(await computerService(input.db).isRetired({ + companyId: input.execution.binding.companyId, environmentId: input.target.environmentId, + owner: workspace.computerOwner, agentId: input.execution.binding.agentId, runId: identity.runId, + })) || !controlBytes.equals(readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large"))) + throw new Error("runner_remote_retirement_evidence_changed"); + await compareAndSealRetiredComputerCheckpoint({ runner: input.runner, runnerPath, providerPath, + runnerBytes: runnerBytes!, providerBytes: providerBytes! }); +} + +/** Exact retirement is checked by the caller; publication must still compare + * the complete bytes so a changed or interrupted checkpoint is never rotated. */ +export async function compareAndSealRetiredComputerCheckpoint(input: { + runner: CommandManagedRuntimeRunner; runnerPath: string; providerPath: string; + runnerBytes: Buffer; providerBytes: Buffer; +}): Promise { + const result = await input.runner.execute({ command: "python3", args: ["-c", String.raw` +import sys,os,stat,json,hashlib,tempfile +runner,provider,expected_runner,expected_provider=sys.argv[1:] +for p,digest in [(runner,expected_runner),(provider,expected_provider)]: + s=os.lstat(p) + if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state') + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217) + if len(data)>16777216:raise RuntimeError('unsafe recovery state') + if hashlib.sha256(data).hexdigest()!=digest:raise RuntimeError('recovery evidence changed') + if p==runner:state=json.loads(data) +state['lifecycle']='suspended' +fd,tmp=tempfile.mkstemp(prefix='.retired-checkpoint-',dir=os.path.dirname(runner)) +try: + with os.fdopen(fd,'w') as f:json.dump(state,f,separators=(',',':'));f.flush();os.fsync(f.fileno()) + # Recheck immediately before publication, including the provider checkpoint. + for p,digest in [(runner,expected_runner),(provider,expected_provider)]: + with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:current=f.read(16777217) + if hashlib.sha256(current).hexdigest()!=digest:raise RuntimeError('recovery evidence changed') + os.replace(tmp,runner) +finally: + if os.path.exists(tmp):os.unlink(tmp) +`, input.runnerPath, input.providerPath, createHash("sha256").update(input.runnerBytes).digest("hex"), createHash("sha256").update(input.providerBytes).digest("hex")], + bypassSession: true, timeoutMs: 10_000 }); + if (result.exitCode !== 0 || result.timedOut) throw new Error("runner_remote_retirement_checkpoint_cas_failed"); +} + async function readRemoteRunnerState(input: { runner: CommandManagedRuntimeRunner; stateDirectory: string; @@ -11100,9 +11257,11 @@ export function createRemoteRunnerProcessLauncher(input: { onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise; trace?: NativeRunTrace; onRunnerProcessSpawned?: () => void; + onLaunchAttempt?: () => void; }): (spec: RunnerProcessLaunchSpec) => RunnerProcessHandle { const runner = input.runner; return (spec) => { + input.onLaunchAttempt?.(); let launchedIdentity: { nonce: string; pid: number; @@ -11404,6 +11563,7 @@ export async function createRunnerdBackend(input: { chatAttachmentReadScope?: NativeChatAttachmentReadScope; restartRecovery?: NativeRestartRecoveryClaim; durableEnvironmentLeaseId?: string; + onRemoteLaunchAttempt?: () => void; onSpawn?: (meta: { pid: number; processGroupId: number | null; @@ -13064,6 +13224,10 @@ async function createRunnerdBackendWithinSessionClaim( if (incompleteFailure) throw incompleteFailure; return; } + // The computer ledger and exact remote placement are the recovery authority. + // Its durable provider state stays on the persistent machine; importing the + // sandbox archive would create a second authority and delay bounded shutdown. + if (remoteTarget?.transport === "computer") return; const backupSpanAttributes = { provider: input.execution.provider.kind, harness: input.execution.session.driverKind, @@ -13207,6 +13371,10 @@ async function createRunnerdBackendWithinSessionClaim( runnerIngressAuthorized: input.runnerIngressAuthorized === true, }); await ensureRemoteRunner(false); + if (remoteTarget.transport === "computer" && remoteStateDirectory) { + await sealRetiredComputerRunnerState({ db: input.db, execution: input.execution, root, + target: remoteTarget, runner: remoteCommandRunner, stateDirectory: remoteStateDirectory }); + } } : undefined; const archiveExternalRunnerState = @@ -13277,6 +13445,7 @@ async function createRunnerdBackendWithinSessionClaim( onLog: input.onLog, trace: input.trace, onRunnerProcessSpawned: () => resolveRemoteRunnerProcessSpawned?.(), + onLaunchAttempt: input.onRemoteLaunchAttempt, }) : undefined; const runnerExecution: NativeExecutionInput = remoteTarget