From 0134081be822b1764f154fa0b8d94bbcf3240bd3 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Thu, 3 Dec 2026 07:39:29 -0800 Subject: [PATCH] fix(native): resume a saved session whatever the task status (#23533) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A native agent keeps a warm session between the turns of a task > - After the warm session leaves memory, the server recovers it from saved state > - That recovery required the task status to be `in_progress` > - Some runs start on a task that is not `in_progress`, by design > - Those runs lost their session, although the saved session was intact > - Run dispatch already decides which tasks a run may start on > - This pull request removes the status check from recovery > - The benefit is that a comment on a task in review continues the same conversation ## Linked Issues or Issue Description Refs #16451 (added this recovery), #21001 (separated the two kinds of refusal). **What happened?** A task was in review. The warm session was no longer in memory. A comment started a run. The run failed with `native_session_interrupted` and `warm_recovery_refused=current_run_not_admitted`. The task then continued in a fresh session. A comment soon after the previous run did resume the session. That path uses the session in memory and does not read the task status. **Expected behavior** The run must resume the saved session. Automatic checkout leaves a task in review on purpose. The agent skill tells the agent to check out the task after it reads the comment. The agent cannot do that before its session resumes. **Steps to reproduce** 1. Run a task on a remote environment with a warm session. 2. Let the agent move the task to review. 3. Wait until the warm session leaves memory. 4. Add a comment to the task. I saw this failure once on a live task. An API call had set that task to review. The new test shows the cause. I did not repeat steps 1 to 4 on a task that an agent moved to review. **Paperclip version or commit** The check is on `master` at 4db307d53c. ## What Changed - Warm session recovery no longer checks the task status. - The status check did not stop the run. It only lost the saved session. On a closed task the automatic fresh continuation does not apply, so the run failed. - The ownership, cancellation, agent and lease checks do not change. - Automatic checkout does not change. ## Verification - `npx vitest run src/services/native-runtime/remote-warm-session-recovery.test.ts` in `server`: 11 tests pass on an embedded PostgreSQL database. - The file tests every task status, and each ownership and cancellation refusal. - The tests replace only the parser of the saved execution input and the saved checkpoint. The suite setup reads the same database settings as the suite gate. - I ran the same tests against the previous check. The cases for a status other than `in_progress` failed. The other cases passed. - `npx tsc --noEmit` in `server` has no errors. CI runs the other test suites. ## Risks - A run can now resume on a task whose status changed while the run started. The path that uses the session in memory already allows this. - A person who closes a task, and any actor who cancels one, also stops its run. The run checks then refuse recovery. If an agent marks the task done while the run starts, the run continues and keeps its session. - Saved state does not change. A session saved by the previous release resumes as before, or resumes where it was refused. - Other failures of the current run can still end in a fresh session. This pull request does not change that policy. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) by Anthropic, in Claude Code, with tool use (shell, file editing, code search) and extended thinking. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../remote-warm-session-recovery.test.ts | 83 +++++++++++++++++++ .../remote-warm-session-recovery.ts | 3 +- 2 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 server/src/services/native-runtime/remote-warm-session-recovery.test.ts diff --git a/server/src/services/native-runtime/remote-warm-session-recovery.test.ts b/server/src/services/native-runtime/remote-warm-session-recovery.test.ts new file mode 100644 index 00000000000..cf91464c87d --- /dev/null +++ b/server/src/services/native-runtime/remote-warm-session-recovery.test.ts @@ -0,0 +1,83 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, expect, it, vi } from "vitest"; +import { agents, companies, completionContracts, createDb, environmentLeases, environments, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db"; +import { ISSUE_STATUSES } from "@paperclipai/shared"; +import { startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js"; +import { describeEmbeddedPostgres } from "../../__tests__/helpers/native-restart.js"; +import { currentNativeControllerIdentity } from "./native-restart-recovery.js"; +import { inspectRemoteWarmSessionRecovery } from "./remote-warm-session-recovery.js"; + +const saved = vi.hoisted(() => ({ runId: "" })); +vi.mock("../../vendor/paperclip-runner/index.js", async original => ({ ...(await original()), + parseNativeExecutionInput: () => ({ binding: { runId: saved.runId }, + session: { driverKind: "acpx_runtime", lifecyclePolicy: { mode: "warm", idleTimeoutMs: 1 } } }) })); + +describeEmbeddedPostgres("warm session recovery revalidation", () => { + let temporary: Awaited>; + let db: ReturnType; + const companyId = randomUUID(), agentId = randomUUID(), otherAgentId = randomUUID(), environmentId = randomUUID(); + + beforeAll(async () => { + temporary = await startRecoveryPostgres("remote-warm-session-recovery-"); + db = createDb(temporary.connectionString); + await db.insert(companies).values({ id: companyId, name: "Warm recovery", issuePrefix: "WSR" }); + await db.insert(agents).values([agentId, otherAgentId].map(id => ({ id, companyId, name: id, adapterType: "paperclip_runner" }))); + await db.insert(environments).values({ id: environmentId, name: "Remote", driver: "sandbox" }); + }, 60_000); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + + async function fixture() { + const issueId = randomUUID(), priorRunId = randomUUID(), runId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID(); + const identity = { runId: priorRunId, normalizedSessionId: randomUUID(), runnerInstanceId: randomUUID(), environmentLeaseId: randomUUID(), + turnId: "turn", itemId: "item" }; + const controller = await currentNativeControllerIdentity(); + await db.insert(issues).values({ id: issueId, companyId, title: "Follow up", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(heartbeatRuns).values([ + { id: priorRunId, companyId, agentId, status: "succeeded", runtimeMode: "native", nativeIssueId: issueId, finishedAt: new Date(0) }, + { id: runId, companyId, agentId, status: "running", runtimeMode: "native", nativeIssueId: issueId }]); + const [contract] = await db.insert(completionContracts).values({ companyId, issueId, revision: 1, schemaVersion: "paperclip.completion-contract/v1", + policyVersion: "v1", risk: "low", completionAuthority: "agent", incompleteCriteriaPolicy: "block", contractJson: {}, + canonicalSha256: "a".repeat(64), createdByActorType: "system", createdByActorId: "test" }).returning(); + await db.update(heartbeatRuns).set({ completionContractId: contract!.id }).where(eq(heartbeatRuns.id, priorRunId)); + const [result] = await db.insert(nativeRunResults).values({ companyId, issueId, runId: priorRunId, completionContractId: contract!.id, + serverFingerprint: priorRunId, schemaStatus: "accepted", resultJson: { terminalState: "succeeded" }, canonicalSha256: "b".repeat(64) }).returning(); + await db.insert(nativeRunFinalizations).values([ + { runId: priorRunId, companyId, issueId, phase: "committed", resultId: result!.id, controllerBootId: randomUUID(), controllerPid: 2 ** 22 + 1, + controllerHostHash: controller.hostHash, controllerProcessStartedAt: new Date(0) }, + { runId, companyId, issueId, phase: "observed", leaseOwner: "owner", leaseExpiresAt: new Date(Date.now() + 60_000), + controllerBootId: controller.bootId, controllerPid: controller.pid }]); + await db.insert(environmentLeases).values([ + { id: identity.environmentLeaseId, heartbeatRunId: priorRunId, status: "expired" }, + { id: leaseId, heartbeatRunId: runId, status: "active" }].map(lease => ({ ...lease, companyId, environmentId, issueId, provider: "remote", + providerLeaseId, leasePolicy: "reuse_by_environment", metadata: { remoteCwd: "." } }))); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + saved.runId = priorRunId; + const recovery = await inspectRemoteWarmSessionRecovery({ db, identity, matchesExecution: () => true, canReuseProcess: () => true, + execution: { binding: { runId, companyId, agentId, issueId } } as never, + target: { kind: "remote", transport: "sandbox", leaseId, environmentId, providerKey: "remote", remoteCwd: ".", + sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId } } as never, + readControlState: () => ({ identity, commands: [], committedEvents: [{ eventType: "run.terminal", envelope: identity }] }), + loadCheckpoint: () => ({ identity: { runId: priorRunId, companyId, issueId, agentId, sessionId: identity.normalizedSessionId }, + driverKind: "acpx_runtime", providerSessionId: "provider", activeTurnId: null, pendingRuntimeRequests: [] }) as never }); + return { issueId, runId, revalidate: () => recovery!.revalidate("owner") }; + } + + it.each(ISSUE_STATUSES)("resumes the saved session of a task that is %s", async status => { + const f = await fixture(); + await db.update(issues).set({ status }).where(eq(issues.id, f.issueId)); + await expect(f.revalidate()).resolves.toBeUndefined(); + }); + + it.each([ + ["the task is reassigned", (f: { issueId: string }) => db.update(issues).set({ assigneeAgentId: otherAgentId }).where(eq(issues.id, f.issueId))], + ["the run no longer owns the task", (f: { issueId: string }) => db.update(issues).set({ executionRunId: null }).where(eq(issues.id, f.issueId))], + ["the run ended", (f: { runId: string }) => db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, f.runId))], + ["the run is being cancelled", (f: { runId: string }) => db.update(heartbeatRuns).set({ resultJson: { nativeCancellation: { requested: true } } }) + .where(eq(heartbeatRuns.id, f.runId))], + ] as const)("refuses when %s", async (_label, change) => { + const f = await fixture(); + await change(f); + await expect(f.revalidate()).rejects.toThrow("warm_recovery_refused=current_run_not_admitted"); + }); +}); diff --git a/server/src/services/native-runtime/remote-warm-session-recovery.ts b/server/src/services/native-runtime/remote-warm-session-recovery.ts index 07c50a0441c..1167f6f5eb6 100644 --- a/server/src/services/native-runtime/remote-warm-session-recovery.ts +++ b/server/src/services/native-runtime/remote-warm-session-recovery.ts @@ -290,8 +290,7 @@ export async function inspectRemoteWarmSessionRecovery(input: { if (!current || current.run.status !== "running" || current.run.resultJson?.nativeCancellation || current.company.status !== "active" || current.agent.lifecycleState !== "ready" || ["paused", "terminated", "pending_approval"].includes(current.agent.status) || - current.issue.executionRunId !== binding.runId || current.issue.assigneeAgentId !== binding.agentId || - current.issue.status !== "in_progress") return refuseCurrentRun("current_run_not_admitted"); + current.issue.executionRunId !== binding.runId || current.issue.assigneeAgentId !== binding.agentId) return refuseCurrentRun("current_run_not_admitted"); if (current.owner.leaseOwner !== leaseOwner || !current.owner.leaseExpiresAt || current.owner.leaseExpiresAt <= new Date() || current.owner.resultId || current.owner.controllerBootId !== controller.bootId || current.owner.controllerPid !== controller.pid) {