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 518e3d7ac65..377773da63d 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -20220,6 +20220,193 @@ describe("runnerd provider runtime wiring", () => { }, ); + it.each([ + "destroyed-after-turn", + "destroyed-after-turn-active-goal", + "failed-lease-cleanup-failed", + "failed-lease-cleanup-unverified", + "failed-lease-same-provider-task", + ] as const)( + "retires a finished per-turn plugin owner after a destroyed lease only when cleanup succeeded: %s", + async mode => { + const first = { + ...scopedNativeExecution(`plugin-destroyed-lease-${mode}`), + schema: "paperclip.native-execution-input.v5", executionMode: "default", planningContext: null, runtimeContext: nativeRuntimeContextFixture(), + provider: { kind: "codex", model: null, approvalPolicy: "never" }, + session: { + ...execution.session, driverKind: "codex_app_server", + normalizedSessionId: `plugin-destroyed-lease-${mode}`, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, + }, + } as NativeExecutionInput; + parseNativeExecutionInput(first); + const next = { ...first, binding: { ...first.binding, runId: `${first.binding.runId}-followup` } }; + const identity = { + runId: first.binding.runId, normalizedSessionId: first.session.normalizedSessionId!, + runnerInstanceId: "plugin-runner", environmentLeaseId: "old-lease", turnId: "old-turn", itemId: "old-item", + }; + const scoped = await initializeScopedRunnerRoot(first, identity.runnerInstanceId); + await mkdir(join(scoped, "control-plane"), { recursive: true }); + const journal = JSON.stringify({ + ...durableControlPlaneState(identity), + commands: [{ type: "turn.start", status: "completed" }], + committedEvents: [{ eventType: "run.terminal", envelope: { ...identity, payload: { reportedWorkDisposition: "done" } } }], + }); + await writeFile(join(scoped, "control-plane/control-plane-state.json"), journal); + + const nextSessionCheckpoint = { + sessionId: "driver-session-1", + providerSessionId: "provider-session-1", + cursor: null, + activeTurnId: null, + pendingRuntimeRequests: [], + terminalTurns: [], + semanticResult: null, + terminal: null, + dispositionOnlyRecoveryConsumed: false, + identity: { + companyId: next.binding.companyId, + issueId: next.binding.issueId, + runId: next.binding.runId, + agentId: next.binding.agentId, + sessionId: next.session.normalizedSessionId!, + }, + ...(mode === "destroyed-after-turn-active-goal" + ? { goal: { threadId: "thread-1", objective: "finish", status: "active", tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0 } } + : {}), + }; + const db = leaseDb(next, {}, {}, [], { sessionCheckpoint: nextSessionCheckpoint }); + const ordinarySelect = db.select.bind(db); + const { currentNativeControllerIdentity } = await import("./native-restart-recovery.js"); + const controller = await currentNativeControllerIdentity(); + const committedPrior = { + run: { + id: first.binding.runId, companyId: first.binding.companyId, agentId: first.binding.agentId, + nativeIssueId: first.binding.issueId, runtimeMode: "native", status: "succeeded", + runnerProfileJson: { nativeExecutionInput: first }, + processPid: null, processGroupId: null, processStartedAt: null, + }, + owner: { + runId: first.binding.runId, companyId: first.binding.companyId, issueId: first.binding.issueId, + phase: "committed", resultId: "result-1", leaseOwner: null, recoveryState: null, + controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt, + controllerBootId: controller.bootId, + }, + }; + const priorProviderLeaseId = mode === "failed-lease-same-provider-task" ? "created-task" : "old-task"; + const priorDestroyedLease = { + id: "old-lease", companyId: first.binding.companyId, heartbeatRunId: first.binding.runId, + status: "failed", + releasedAt: new Date(), + cleanupStatus: mode === "failed-lease-cleanup-failed" ? "failed" + : mode === "failed-lease-cleanup-unverified" ? null : "success", + failureReason: "paperclip_runner_destroy_after_turn", + provider: "plugin:test:tasks", providerLeaseId: priorProviderLeaseId, + metadata: { + driver: "plugin", + pluginLeaseCleanupMethod: "destroy", + runnerTaskExecutionStopped: true, + runnerTaskSessionRetained: false, + runnerTaskRetiring: true, + remoteExecutionTermination: { + schema: "paperclip.remote-termination.v1", + companyId: first.binding.companyId, + runId: first.binding.runId, + leaseId: "old-lease", + provider: "plugin:test:tasks", + providerLeaseId: priorProviderLeaseId, + state: "stopped", + confirmedAt: new Date().toISOString(), + }, + }, + }; + db.select = ((fields?: Record) => { + if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) { + return priorNativeRunDb(first, "succeeded").select(fields as never); + } + if (fields && "run" in fields && "owner" in fields) { + return { + from: () => ({ + innerJoin: () => ({ + where: () => ({ limit: async () => [committedPrior] }), + }), + }), + }; + } + if (fields && "providerLeaseId" in fields && "status" in fields) { + return { from: () => ({ where: async () => [priorDestroyedLease] }) }; + } + if (fields === undefined) { + return { + from: (table: unknown) => table === environmentLeases + ? { where: async () => [priorDestroyedLease] } + : ordinarySelect().from(table as never), + }; + } + return ordinarySelect(fields as never); + }) as Db["select"]; + + const resume = vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockResolvedValue(priorProviderLeaseId); + const task = vi.fn(async (operation: any) => { + environmentTaskOperationSchema.parse(operation); + if (operation.kind === "read_state") { + throw environmentTaskRuntime.createUnconfirmedPluginCheckpointError({ + executionStopped: true, + sessionStateAvailable: false, + }); + } + return { + kind: "description", taskId: "created-task", launchPreparationVersion: 1, projectAuthCheckVersion: 1, warmTaskVersion: 1, + runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` }, + }; + }); + state.createBackend.mockClear(); + state.execute.mockClear(); + const home = join(isolatedStateDirectory, `destroyed-lease-${mode}`); + await mkdir(home, { recursive: true }); + await writeFile(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: "synthetic-fixture" }), { mode: 0o600 }); + try { + const launch = { + db, execution: next, runnerInstanceId: "runner", runnerIngressAuthorized: true, + managedAiCredentialHome: home, managedAiCredentialIdentity: "revision", managedAiAccountIdentity: "account", + runnerEnvironment: { ANTHROPIC_API_KEY: "synthetic-fixture" }, + runnerExecutionTarget: { + kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "created-lease", runnerTask: task, + sandboxLeaseAcquisition: { outcome: "created", providerLeaseId: "created-task" }, + } as never, + }; + if (mode === "destroyed-after-turn" || mode === "destroyed-after-turn-active-goal") { + const validated = validatePrpStructuredRunResult({ + schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", summary: "done", + completionClaim: { contractRevision: next.completionContract.contract.revision, objectiveSatisfied: true, criteria: [], remainingWork: [] }, + evidence: [], verification: [], artifacts: [], attentionRequests: [], + }); + if (!validated.ok) throw new Error("Invalid completion fixture"); + state.execute.mockResolvedValueOnce({ + result: validated.result, terminal: { runTerminalState: "succeeded" }, turnId: "turn", + normalizedSessionId: next.session.normalizedSessionId, providerSessionId: "fresh-provider-session", + driverKind: next.session.driverKind, driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null, + }); + await expect(executePaperclipNativeSession({ ...launch, useRunnerd: true })).resolves.toBeDefined(); + expect(state.createBackend).toHaveBeenCalledOnce(); + expect(existsSync(join(scoped, "continuity-breaks"))).toBe(true); + expect(state.execute).toHaveBeenCalledWith(expect.objectContaining({ + replaceAfterConfirmedProviderStateLoss: mode === "destroyed-after-turn", + })); + } else if (mode === "failed-lease-same-provider-task") { + await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=prior_lease_active"); + expect(state.createBackend).not.toHaveBeenCalled(); + expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false); + } else { + await expect(createRunnerdBackend(launch)).rejects.toThrow("runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate"); + expect(state.createBackend).not.toHaveBeenCalled(); + expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false); + } + } finally { + resume.mockRestore(); + } + }, + ); + it.each(["verified", "wrong-state", "no-stop-proof", "disposition-retry", "disposition-wrong-state", "disposition-no-stop-proof"] as const)("admits only an authorized same-run plugin checkpoint: %s", async mode => { const current = scopedNativeExecution(`plugin-crash-${mode}`); const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!, diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 7c8b31b6801..36d351ea335 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -6414,11 +6414,19 @@ async function priorRemoteSandboxLeasesEnded(db: Db, input: { companyId: string; runId: string; currentProviderLeaseId?: string; }): Promise { try { - const leases = await db.select({ status: environmentLeases.status, releasedAt: environmentLeases.releasedAt, - providerLeaseId: environmentLeases.providerLeaseId }).from(environmentLeases) + const leases = await db.select({ + status: environmentLeases.status, + releasedAt: environmentLeases.releasedAt, + cleanupStatus: environmentLeases.cleanupStatus, + providerLeaseId: environmentLeases.providerLeaseId, + }).from(environmentLeases) .where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, input.runId))); - return leases.length > 0 && leases.every(lease => (lease.status === "released" || lease.status === "expired") - && lease.releasedAt !== null && lease.providerLeaseId !== input.currentProviderLeaseId); + return leases.length > 0 && leases.every(lease => + (lease.status === "released" || lease.status === "expired" + || (lease.status === "failed" && lease.cleanupStatus === "success")) + && lease.cleanupStatus !== "failed" + && lease.releasedAt !== null + && lease.providerLeaseId !== input.currentProviderLeaseId); } catch { return false; } @@ -12840,8 +12848,11 @@ async function executePaperclipNativeSessionAttempt( trace.activate(runnerSessionStartupScope); const providerTurnWait = nativeProviderStartedTurns(input.execution.provider) ? await nativeProviderTurnWaitOptions(input.db, input.execution.binding) : undefined; - const runExecution = () => - executeNativeSession({ + const runExecution = async () => { + const stateLossCheckpoint = pluginCheckpointRetired && !existingWarmSession + ? (persistedWarmSession ?? await controlPlane.loadSessionCheckpoint()) + : null; + return executeNativeSession({ resumeInterruptedTurn: input.restartRecovery?.kind === "resume_dead_runner" || input.restartRecovery?.kind === "reattach_remote_runner" || scheduledResumeContinuation, providerTurnWait, @@ -12951,8 +12962,8 @@ async function executePaperclipNativeSessionAttempt( }, existingSession: existingWarmSession, persistedSession: persistedWarmSession, - replaceAfterConfirmedProviderStateLoss: pluginCheckpointRetired && persistedWarmSession - ? providerSessionReplaceableAfterStateLoss(persistedWarmSession, input.execution) : false, + replaceAfterConfirmedProviderStateLoss: stateLossCheckpoint + ? providerSessionReplaceableAfterStateLoss(stateLossCheckpoint, input.execution) : false, keepSessionOpen: warmSessionId !== null, sessionGoalControl: input.sessionGoalControl, resumeSessionGoalHeartbeat: input.resumeSessionGoalHeartbeat, @@ -13265,6 +13276,7 @@ async function executePaperclipNativeSessionAttempt( } }, }); + }; let result: Awaited>; try { result = await trace.run(runnerSessionStartupScope, runExecution);