diff --git a/packages/paperclip-runner/src/native-session-runtime.test.ts b/packages/paperclip-runner/src/native-session-runtime.test.ts index 770afe9ba6e..ce3bf57d645 100644 --- a/packages/paperclip-runner/src/native-session-runtime.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.test.ts @@ -7089,6 +7089,90 @@ describe("executeNativeSession recovery", () => { }); }); + describe("a follow-up whose previous Runner Core proved stopped without saved state", () => { + const sameSessionCheckpoint = (): PersistedNativeSession => ({ + backendKind: "mock", driverKind: "codex_app_server", sessionId: "driver-gone", identity, + providerSessionId: "provider-gone", providerRecoveryPolicy: "same_session_only", + cursor: "4", semanticResult: null, terminal: null, activeTurnId: null, terminalTurns: [], + pendingRuntimeRequests: [], dispositionOnlyRecoveryConsumed: false, dispositionOnlyRecoveryTurnId: null, + lineage: [], + }); + const stateUnavailable: NativeSessionRecoveryResult = { + recovered: false, failureClass: PROVIDER_STATE_INCOMPATIBLE, resumeStateUnavailable: true, + reason: "Error: NativeRunnerResumeStateUnavailableError: PRP provider resume state is unavailable", + }; + function harness(options: { + confirmed: boolean; + checkpoint?: PersistedNativeSession; + recovery?: NativeSessionRecoveryResult; + }) { + const startTurn = vi.fn(async () => ({ turnId: "turn-fresh" })); + const replacementSession: NativeSession = { + identity: () => identity, + capabilities: async () => ({ resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }), + async *events() { yield runnerEvent(1, "turn.completed"); }, + startTurn, + result: async () => ({ result, terminal, turnId: "turn-fresh" }), + snapshot: async () => ({ ...sameSessionCheckpoint(), sessionId: "driver-fresh", providerSessionId: "provider-fresh" }), + close: async () => {}, + }; + const openReplacementSession = vi.fn(async () => replacementSession); + const backend: NativeSessionBackend = { + descriptor: async () => ({ kind: "mock", name: "confirmed-state-loss", version: "1", + capabilities: { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true } }), + openSession: vi.fn(async () => { throw new Error("replacement seam must be used"); }), + openReplacementSession, + recoverSession: vi.fn(async () => options.recovery ?? stateUnavailable), + }; + const events: PrpEvent[] = []; + const controlPlane: ControlPlanePort = { + openRun: vi.fn(async () => undefined), + loadSessionCheckpoint: async () => structuredClone(options.checkpoint ?? sameSessionCheckpoint()), + checkpointSession: async () => {}, + async appendEvent(event) { + events.push(structuredClone(event as PrpEvent)); + return { cursor: events.length, highestContiguousSourceSeq: highestContiguous(events), disposition: "committed" }; + }, + replayEvents: async () => ({ events: [], highestContiguousSourceSeq: 0 }), + completeRun: async () => {}, + }; + const onContinuityBreak = vi.fn(async () => undefined); + const run = () => executeNativeSession({ + input, backend, controlPlane, onContinuityBreak, + replaceAfterConfirmedProviderStateLoss: options.confirmed, + runnerInstanceId: "runner-recovery", controlPlaneInstanceId: "control-recovery", + }); + return { run, startTurn, openReplacementSession, onContinuityBreak }; + } + + it("continues in a fresh provider session and records the continuity break", async () => { + const h = harness({ confirmed: true }); + await expect(h.run()).resolves.toMatchObject({ providerSessionId: "provider-fresh" }); + expect(h.openReplacementSession).toHaveBeenCalledOnce(); + expect(h.startTurn).toHaveBeenCalledOnce(); + expect(h.onContinuityBreak).toHaveBeenCalledWith(expect.objectContaining({ + reason: expect.stringContaining("saved provider state is unavailable"), + previousProviderSessionId: "provider-gone", replacementProviderSessionId: "provider-fresh", + })); + }); + + it.each([ + ["Core did not prove the previous Runner stopped without state", { confirmed: false }], + ["the Runner did not prove the saved state is gone", { confirmed: true, recovery: { + recovered: false as const, failureClass: PROVIDER_STATE_INCOMPATIBLE, reason: "saved launch profile changed" } }], + ["the recovery failure is unclassified", { confirmed: true, recovery: { + recovered: false as const, reason: "provider transport closed" } }], + ["a provider turn was in flight", { confirmed: true, checkpoint: { ...sameSessionCheckpoint(), activeTurnId: "turn-open" } }], + ["a runtime request was pending", { confirmed: true, checkpoint: { ...sameSessionCheckpoint(), + pendingRuntimeRequests: [{ requestId: "request-open" } as never] } }], + ] as const)("refuses to replace the provider session when %s", async (_label, options) => { + const h = harness(options as Parameters[0]); + await expect(h.run()).rejects.toThrow("native_session_recovery_failed"); + expect(h.openReplacementSession).not.toHaveBeenCalled(); + expect(h.startTurn).not.toHaveBeenCalled(); + }); + }); + // A remote workspace epoch was abandoned, so the run was assigned a new // sibling root while its checkpoint still names the old one. A checkpoint // that requires the same session (an unfinished goal) ends with the diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.ts index 7fed5d55bf4..9f13400684e 100644 --- a/packages/paperclip-runner/src/native-session-runtime.ts +++ b/packages/paperclip-runner/src/native-session-runtime.ts @@ -395,6 +395,7 @@ export interface ExecuteNativeSessionOptions { onSessionQuarantined?: (reason: string) => Promise | void; existingSession?: NativeSession; persistedSession?: PersistedNativeSession | null; + replaceAfterConfirmedProviderStateLoss?: boolean; keepSessionOpen?: boolean; /** Apply a structured session-goal control instead of starting an ordinary turn. */ sessionGoalControl?: NativeSessionGoalControl | null; @@ -2119,6 +2120,18 @@ function checkpointCursor(cursor: string | null | undefined): number { */ const GOVERNED_WAIT_PROVIDER_WORK_PROOF_TIMEOUT_MS = 30_000; +function runnerProvedSavedStateGone( + checkpoint: PersistedNativeSession, + recovery: NativeSessionRecoveryResult, + restartInterruption: boolean, +): boolean { + return recovery.failureClass === PROVIDER_STATE_INCOMPATIBLE && + recovery.resumeStateUnavailable === true && + !restartInterruption && + checkpoint.activeTurnId === null && + Array.isArray(checkpoint.pendingRuntimeRequests) && checkpoint.pendingRuntimeRequests.length === 0; +} + async function governedWaitFollowUpMayStartFresh(input: { input: NativeExecutionInput; checkpoint: PersistedNativeSession; @@ -2131,14 +2144,10 @@ async function governedWaitFollowUpMayStartFresh(input: { if ( checkpoint.providerRecoveryPolicy !== "allow_replacement_after_governed_wait" || ("homeMode" in input.input && input.input.homeMode === "preconfigured") || - recovery.failureClass !== PROVIDER_STATE_INCOMPATIBLE || - recovery.resumeStateUnavailable !== true || - input.restartInterruption || + !runnerProvedSavedStateGone(checkpoint, recovery, input.restartInterruption) || checkpoint.identity.runId !== input.input.binding.runId || !(checkpoint.cursor === null || checkpoint.cursor === "0") || - checkpoint.activeTurnId !== null || !Array.isArray(checkpoint.terminalTurns) || checkpoint.terminalTurns.length > 0 || - !Array.isArray(checkpoint.pendingRuntimeRequests) || checkpoint.pendingRuntimeRequests.length > 0 || checkpoint.semanticResult !== null || checkpoint.terminal !== null || checkpoint.governedWait !== undefined || @@ -2778,7 +2787,11 @@ export async function executeNativeSession( controlPlane: options.controlPlane, timeoutMs: recoveryTimeoutMs, }); - if (!replacementAllowed && !governedWaitFollowUpLostState) { + const confirmedStateLoss = !replacementAllowed && !governedWaitFollowUpLostState && + options.replaceAfterConfirmedProviderStateLoss === true && + !("homeMode" in input && input.homeMode === "preconfigured") && + runnerProvedSavedStateGone(providerRecoveryCheckpoint, recovery, Boolean(checkpointedInterruption)); + if (!replacementAllowed && !governedWaitFollowUpLostState && !confirmedStateLoss) { if (recovery.failureClass === PROVIDER_STATE_INCOMPATIBLE) { throw new NativeProviderStateIncompatibleError(recovery.reason ?? "unknown"); } @@ -2791,7 +2804,7 @@ export async function executeNativeSession( throw failure; } continuityBreak = { - reason: governedWaitFollowUpLostState + reason: governedWaitFollowUpLostState || confirmedStateLoss ? `saved provider state is unavailable, so the follow-up continues in a fresh provider session without the earlier conversation context (${recovery.reason ?? "unknown"})` : recovery.reason ?? "provider session is no longer recoverable", previousDriverSessionId: providerRecoveryCheckpoint.sessionId, diff --git a/server/src/__tests__/helpers/plugin-runner-eviction.ts b/server/src/__tests__/helpers/plugin-runner-eviction.ts index 6fc5f9bdcaa..557182be1e4 100644 --- a/server/src/__tests__/helpers/plugin-runner-eviction.ts +++ b/server/src/__tests__/helpers/plugin-runner-eviction.ts @@ -81,7 +81,8 @@ export function registerPluginRunnerEvictionSuite(harness: "codex" | "claude", e const thisCase: { teardown?: () => Promise } = {}; currentCase = thisCase; const detached = mode === "detached" || mode === "missing state" || mode === "foreign state"; - const denied = mode.startsWith("missing") || mode.endsWith("state"); + const freshSession = mode === "missing state"; + const denied = !freshSession && (mode.startsWith("missing") || mode.endsWith("state")); const relaunch = mode === "relaunch after inspection"; const unavailableResume = mode === "after inspection" || mode === "bare unavailable" || relaunch; const reusesLease = mode === "reused lease" || unavailableResume; @@ -166,6 +167,7 @@ export function registerPluginRunnerEvictionSuite(harness: "codex" | "claude", e const releases: DurableRecoveryIdentity[] = [], claims: DurableRecoveryIdentity[] = []; let handle: RunnerProcessHandle | undefined, submissions = 0, cleaning = false, sourceReadRequests = 0, sourceReadResponses = 0; let pendingFollowup: Promise | undefined; + const runLogs: string[] = []; thisCase.teardown = async () => { cleaning = true; const cleanup = await Promise.allSettled([closeIdleWarmNativeSessionsForRestart(), ...[...hosts.values()].map(host => host.close())]); @@ -313,7 +315,7 @@ export function registerPluginRunnerEvictionSuite(harness: "codex" | "claude", e runnerEnvironment: harness === "claude" ? { ANTHROPIC_API_KEY: "synthetic-fixture" } : {}, ...(mode === "prepared copy" ? { instructionWorkingCopy: instructionCopy(current.binding.runId) } : {}), managedAiCredentialHome: home, managedAiCredentialIdentity: "fixture-revision", managedAiAccountIdentity: "fixture-account", turnTimeoutMs: 15_000, - runnerExecutionTarget: target }); + onLog: async (_stream, chunk) => { runLogs.push(chunk); }, runnerExecutionTarget: target }); }; try { const a = await execute(execution, leaseA); expect(a).toMatchObject({ exitCode: 0, timedOut: false }); @@ -410,7 +412,11 @@ export function registerPluginRunnerEvictionSuite(harness: "codex" | "claude", e if (denied || mode === "bare unavailable") return; await waitForCondition("automatic release B", () => releases.length === 2); expect(await proof()).toBeUndefined(); - expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId); + if (freshSession) { + expect({ sourceReadRequests, sourceReadResponses }).toEqual({ sourceReadRequests: 1, sourceReadResponses: 0 }); + expect(runLogs.join("")).toContain("finished without a saved runner checkpoint"); + expect(runLogs.join("")).toContain("provider session continuity break"); + } else expect((await supervisor()).snapshot.providerSessionId).toBe(providerSessionId); const methods = (await readFile(calls, "utf8")).trim().split(/\r?\n/); expect(submissions).toBe(2); if (mode === "after inspection" || relaunch) expect({ resumeAttempts, acquisitions }).toEqual({ resumeAttempts: 1, acquisitions: 1 }); 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 abfb089f011..0c5a8d5864e 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -545,6 +545,7 @@ import { verifyNativeHarnessBackupStreamed, shouldRestoreNativeHarnessBackupIntoSandbox, remoteProviderStateNeverOpened, + providerSessionReplaceableAfterStateLoss, } from "./native-session-executor.js"; import { onNativeRunnerEvidence } from "./native-runner-evidence-signal.js"; @@ -19987,6 +19988,20 @@ describe("runnerd provider runtime wiring", () => { } finally { owner.mockRestore(); resume.mockRestore(); } }); + it("keeps same-session recovery for an unfinished goal or Antigravity after a confirmed lost plugin checkpoint", () => { + const codex = { provider: { kind: "codex", model: null, approvalPolicy: "never" } } as unknown as NativeExecutionInput; + const goal = (status: string) => ({ threadId: "thread", objective: "ship", status, tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0 }) as never; + expect(providerSessionReplaceableAfterStateLoss({}, codex)).toBe(true); + expect(providerSessionReplaceableAfterStateLoss({ goal: null }, codex)).toBe(true); + expect(providerSessionReplaceableAfterStateLoss({ goal: goal("complete") }, codex)).toBe(true); + for (const status of ["active", "paused", "blocked", "limited", "usageLimited", "budgetLimited"]) { + expect(providerSessionReplaceableAfterStateLoss({ goal: goal(status) }, codex), status).toBe(false); + } + const antigravity = { provider: { kind: "acpx", agent: "antigravity" } } as unknown as NativeExecutionInput; + expect(providerSessionReplaceableAfterStateLoss({}, antigravity)) + .toBe(!antigravityRelease.antigravityForcesSameSessionRecovery(antigravity.provider)); + }); + it.each([ "stopped-state-unavailable", "stopped-availability-omitted", diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index f780da12e73..910f5e9e09b 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -6544,7 +6544,15 @@ async function assertPluginTaskReattachmentBinding(input: { return taskId; } -async function migrateRunnerdStateRootForExecution(input: { +async function migrateRunnerdStateRootForExecution( + input: Omit[0], "onPluginCheckpointRetired">, +): Promise<{ binding?: VerifiedWarmTransitionBinding; pluginCheckpointRetired: boolean }> { + let pluginCheckpointRetired = false; + const binding = await migrateRunnerdStateRoot({ ...input, onPluginCheckpointRetired: () => { pluginCheckpointRetired = true; } }); + return { binding, pluginCheckpointRetired }; +} + +async function migrateRunnerdStateRoot(input: { db: Db; execution: NativeExecutionInput; preparedExecutionAdmission?: NativePreparedExecutionAdmission; @@ -6556,6 +6564,7 @@ async function migrateRunnerdStateRootForExecution(input: { runnerExecutionTarget?: AdapterExecutionTarget | null; bootstrapRetryLeaseOwner?: string; pluginCheckpointUnavailableConfirmed?: boolean; + onPluginCheckpointRetired?: () => void; }): Promise { const scoped = scopedRunnerdStateRoot(input.execution); await restoreWarmRunnerdController(input); @@ -6728,7 +6737,10 @@ async function migrateRunnerdStateRootForExecution(input: { if (verification === "terminal_state_indeterminate" && !input.retainedWarmOwnerRunId && (!input.restartRecovery || input.restartRecovery.kind === "bootstrap_incomplete")) { const retirement = await retireFinishedPerTurnRunnerdOwner({ ...input, root: scoped, identity, pluginCheckpointUnavailableConfirmed }); - if (retirement.retired) return; + if (retirement.retired) { + if (pluginCheckpointUnavailableConfirmed) input.onPluginCheckpointRetired?.(); + return; + } if (retirement.refused !== "lifecycle_not_per_turn") retirementRefusal = `; retirement_refused=${retirement.refused}`; } if ( @@ -8975,6 +8987,14 @@ function loadWarmNativeCheckpoint( return resumed; } +export function providerSessionReplaceableAfterStateLoss( + checkpoint: Pick, + execution: Pick, +): boolean { + if (antigravityForcesSameSessionRecovery(execution.provider)) return false; + return checkpoint.goal == null || checkpoint.goal.status === "complete"; +} + async function releaseWarmNativeSession( sessionId: string, ownerToken: symbol, @@ -11276,6 +11296,7 @@ async function executePaperclipNativeSessionAttempt( } else releasedWarmSource(input, cachedReleasedOwner.pluginTaskId ?? null); } let pluginCheckpointUnavailableConfirmed = false; + let pluginCheckpointRetired = false; if (input.useRunnerd && canRecoverWarmOwner && !input.backend && input.runnerExecutionTarget?.kind === "remote" && input.execution.session.lifecyclePolicy.mode === "warm" && @@ -11339,7 +11360,7 @@ async function executePaperclipNativeSessionAttempt( } } if (input.useRunnerd) { - retainedTransition = await timeController("state_migration", () => migrateRunnerdStateRootForExecution({ + const migration = await timeController("state_migration", () => migrateRunnerdStateRootForExecution({ db: input.db, execution: input.execution, preparedExecutionAdmission: input.preparedExecutionAdmission, @@ -11352,6 +11373,8 @@ async function executePaperclipNativeSessionAttempt( bootstrapRetryLeaseOwner: input.leaseOwner, pluginCheckpointUnavailableConfirmed, })); + retainedTransition = migration.binding; + pluginCheckpointRetired = migration.pluginCheckpointRetired; } const durableRunnerBinding = input.useRunnerd ? loadRunnerdDurableBinding(input.execution, retainedTransition) @@ -12911,6 +12934,8 @@ async function executePaperclipNativeSessionAttempt( }, existingSession: existingWarmSession, persistedSession: persistedWarmSession, + replaceAfterConfirmedProviderStateLoss: pluginCheckpointRetired && persistedWarmSession + ? providerSessionReplaceableAfterStateLoss(persistedWarmSession, input.execution) : false, keepSessionOpen: warmSessionId !== null, sessionGoalControl: input.sessionGoalControl, resumeSessionGoalHeartbeat: input.resumeSessionGoalHeartbeat, @@ -16624,7 +16649,7 @@ export async function createRunnerdBackend(input: { input.execution.binding.runId || hasRetainedWarmTransitionEvidence(scopedRunnerdStateRoot(input.execution)) ) { - retainedTransition = await migrateRunnerdStateRootForExecution({ + retainedTransition = (await migrateRunnerdStateRootForExecution({ db: input.db, execution: input.execution, preparedExecutionAdmission: input.preparedExecutionAdmission, @@ -16634,7 +16659,7 @@ export async function createRunnerdBackend(input: { onLog: input.onLog, restartRecovery: input.restartRecovery, runnerExecutionTarget: input.runnerExecutionTarget, - }); + })).binding; } input.executionContext?.signal.throwIfAborted(); const backend = await createRunnerdBackendWithinSessionClaim(