mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 01:24:30 +01:00
fix(native-runtime): retire finished plugin owners after destroyed leases (#23292)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner agents can run per-turn tasks on plugin environments that destroy each ephemeral lease after a turn completes. > - When a plugin environment destroys a finished per-turn lease, `createPluginEnvironmentDriver().destroyRunLease` releases the lease row with `status: "failed"`, `cleanupStatus: "success"`, a non-null `releasedAt`, and a bound `remoteExecutionTermination` stop receipt. > - On the next turn, `remoteExecutionHasStopped` accepts that lease as stopped, but `priorRemoteSandboxLeasesEnded` only accepts `released` or `expired`, so every follow-up fails with `runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=prior_lease_active` until automatic recovery retries with `forceFreshSession`. > - Even after retirement succeeds on a `per_turn` run, `replaceAfterConfirmedProviderStateLoss` only inspected `persistedWarmSession` (undefined for `per_turn` runs) instead of checking the control-plane session checkpoint. > - This pull request accepts cleanly destroyed `failed` leases (`cleanupStatus === "success"`, `releasedAt !== null`, different `providerLeaseId`) in `priorRemoteSandboxLeasesEnded` and falls back to `controlPlane.loadSessionCheckpoint()` when computing `replaceAfterConfirmedProviderStateLoss` after `pluginCheckpointRetired`. > - The benefit is that per-turn plugin Runner follow-ups retire settled destroyed leases and continue on the first attempt instead of failing once and forcing a fresh-session retry on every turn. ## Linked Issues or Issue Description Refs #22973, #23007. **What happened?** On a plugin environment running `per_turn` Paperclip Runner tasks (`leasePolicy: "ephemeral"`), every completed turn tears down its lease through `createPluginEnvironmentDriver().destroyRunLease`, which stores `status: "failed"`, `cleanupStatus: "success"`, `failureReason: "paperclip_runner_destroy_after_turn"`, a non-null `releasedAt`, and a bound `remoteExecutionTermination` stop receipt. When the next follow-up turn ran for the same task session, `recoverPluginRunnerCheckpoint` confirmed that the prior task stopped with no retained checkpoint, `remoteExecutionHasStopped` returned `true` (because `hasRemoteTerminationReceipt` accepts `["released", "expired", "failed"]` with `cleanupStatus === "success"`), and `inspectFinishedPerTurnRunnerdOwner` then called `priorRemoteSandboxLeasesEnded`. Because `priorRemoteSandboxLeasesEnded` only accepted `status === "released" || status === "expired"`, every follow-up failed immediately with: `runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=prior_lease_active` Recovery then retried ~20-30s later with `forceFreshSession`, which succeeded on a new session ID and repeated the same failure on the next turn. In addition, once a `per_turn` run retires a confirmed-unavailable plugin checkpoint (`pluginCheckpointRetired = true`), `replaceAfterConfirmedProviderStateLoss` only checked `persistedWarmSession`, which is `undefined` for `per_turn` runs (whose persisted checkpoint lives in `controlPlane.loadSessionCheckpoint()`). **Expected behavior** A finished prior run whose remote lease was destroyed with `status: "failed"`, `cleanupStatus: "success"`, `releasedAt !== null`, and a different `providerLeaseId` retires cleanly into `continuity-breaks` on the first follow-up attempt, and `per_turn` runs compute `replaceAfterConfirmedProviderStateLoss` from the control-plane session checkpoint when `persistedWarmSession` is absent (while still preserving same-session recovery for unfinished goals and pending-release Antigravity gates). **Steps to reproduce** Run `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "retires a finished per-turn plugin owner after a destroyed lease"` against `2d764bebc6`. **Paperclip version or commit** Reproduced on `origin/master` at `2d764bebc6` (and observed on deployed `bc98abda0c`). **Deployment mode** Self-hosted / Cloud server with plugin Runner task environment. ## What Changed - `server/src/services/native-runtime/native-session-executor.ts`: - Updated `priorRemoteSandboxLeasesEnded` to select `cleanupStatus` and treat a prior lease as ended when `(status === "released" || status === "expired" || (status === "failed" && cleanupStatus === "success")) && cleanupStatus !== "failed" && releasedAt !== null && providerLeaseId !== currentProviderLeaseId`. - Updated `executePaperclipNativeSessionAttempt` to fall back to `await controlPlane.loadSessionCheckpoint()` when `pluginCheckpointRetired && !existingWarmSession` and `persistedWarmSession` is absent, passing the resulting checkpoint to `providerSessionReplaceableAfterStateLoss`. - File-length note: `native-session-executor.ts` is an existing >1,000-line module; this PR makes a surgical +12 net-line fix inside the two existing functions rather than introducing a new file. - `server/src/services/native-runtime/native-session-executor.test.ts`: - Added 5 parameterized red/green regressions (`retires a finished per-turn plugin owner after a destroyed lease only when cleanup succeeded`) covering destroyed per-turn plugin leases, active-goal preservation (`replaceAfterConfirmedProviderStateLoss: false`), failed cleanup refusal, unverified (`null`) cleanup refusal, and same-provider-task refusal (`retirement_refused=prior_lease_active`). ## Verification - **Red (before production fix)**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "retires a finished per-turn plugin owner after a destroyed lease"` - Result: `2 failed | 3 passed` — both `destroyed-after-turn` and `destroyed-after-turn-active-goal` failed with `Error: runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=prior_lease_active`. - **Red for second-order fix (after Part 1 only)**: - Same command failed `1 failed | 4 passed` — `destroyed-after-turn` retired cleanly into `continuity-breaks` and then failed expecting `replaceAfterConfirmedProviderStateLoss: true` (received `false`). - **Green (after both fixes)**: - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "retires a finished per-turn plugin owner after a destroyed lease|handles unconfirmed plugin checkpoint status on replacement lease"` → `9 passed`. - `pnpm --filter @paperclipai/server typecheck` → passed (`below`, `cycle`, `above`, `tests`, `test-tree-0..2`). - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts` → `1565 passed | 7 skipped (1572)`. ## Risks - Low risk. No database schema or migration changes. - Fail-closed guarantees are preserved: a `failed` lease with `cleanupStatus: "failed"` or `cleanupStatus: null`, an unreleased lease (`releasedAt === null`), a `released`/`expired` lease with `cleanupStatus === "failed"`, or a lease matching `currentProviderLeaseId` all still return `false` from `priorRemoteSandboxLeasesEnded` and refuse retirement. - Existing already-persisted `status: "failed", cleanupStatus: "success"` lease rows from previous releases retire cleanly immediately upon deploy (upgrade-safe). - Unfinished goals still keep `replaceAfterConfirmedProviderStateLoss: false`. ## Model Used - Google Gemini (Antigravity agentic assistant) with tool use (file read/edit, shell execution, browser inspection). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
cf0ba4d9ee
commit
3621d7204d
2 files changed
+207
-8
No files matched your search
@@ -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<string, unknown>) => {
|
||||
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!,
|
||||
|
||||
@@ -6414,11 +6414,19 @@ async function priorRemoteSandboxLeasesEnded(db: Db, input: {
|
||||
companyId: string; runId: string; currentProviderLeaseId?: string;
|
||||
}): Promise<boolean> {
|
||||
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<ReturnType<typeof runExecution>>;
|
||||
try {
|
||||
result = await trace.run(runnerSessionStartupScope, runExecution);
|
||||
|
||||
Reference in new issue
Block a user