From e2908fff5c4ef62496009b791bb6dca1d1b1ea68 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 30 Sep 2026 17:20:25 -0500 Subject: [PATCH] fix: enforce terminal outcomes during recovered sandbox cleanup (#14767) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native runners can keep a reusable sandbox warm after successful turns. > - Failed turns must stop their sandbox before a later retry resumes it. > - Workspace recovery can release a lease outside the executor's normal teardown. > - Successful file copy-back can then retain a sandbox even when its run failed. > - This pull request checks the durable run outcome at the shared release boundary. > - Ordinary teardown and recovery now apply the same retention rule. ## Linked Issues or Issue Description **What happened?** A real Daytona verification on `5edf55d73` produced a failed native turn. The runner process exited, but workspace recovery retained the sandbox without stopping it. The recovery callback used successful workspace copy-back to select warm retention. It bypassed the terminal-state check in normal heartbeat teardown. **Expected behavior** Keep a sandbox running only after a successful run. Failed, cancelled, timed-out, and interrupted runs must convert requested warm retention to stop-and-retain. Preserve the existing ownership hold before release. **Steps to reproduce** 1. Persist a terminal failed native run whose workspace copy-back succeeds. 2. Release its environment lease from the recovery path with a stored `keep_running` disposition. 3. Observe that the provider receives `keep_running` on the base commit. 4. With this fix, the provider receives `stop_and_retain` and the lease status follows the durable run outcome. **Paperclip version or commit** Base: `5edf55d7350c7f08c9dd132c7e0f1421fa0bf2fb`. **Deployment mode** Native runner with a reusable Daytona sandbox. Related: #14747 retires unsuccessful warm runner sessions. This change closes the separate recovery lease-release path. Related search found no duplicate fix. ## What Changed - Read the durable run status at the shared lease-release boundary. - Apply the existing terminal-outcome retention rule before calling the environment runtime. - Use that same durable status for the lease-state mapping. - Add five database-backed regressions for four unsuccessful outcomes and successful warm retention. - Document the recovery rule. ## Verification - Before the fix: the four unsuccessful-outcome regressions fail; the successful case passes. - After the fix: 163 tests pass across the lease-release, native lifecycle, and explicit continuation suites. - Repository typecheck and build pass. - `pnpm test:run` encountered the existing local `native-session-resume.test.ts:1125` assertion failure; a focused rerun reproduced the same failure. This was also recorded before this follow-up with the unmodified base executor. The full command was stopped after that confirmation, so later local groups were not completed. - All 56 latest-head checks are successful or intentionally skipped (54 passed, 2 skipped), including the complete CI test groups and browser E2E suite. Greptile is 5/5 on `e7da3b3ad`, with no unresolved review comments. - Deployed exact PR head `e7da3b3adbf7a13642c0e56f5b0f0c4666adf358` to the staging workspace and independently verified the serving commit. A real failed native turn persisted `keep_running` and completed workspace finalization, reproducing the recovery-path conditions; Paperclip automatically issued stop-and-retain, and an independent Daytona read confirmed `stopped`. No manual stop was used. - Retried that failed run through the public API after correcting its temporary API-key credential. The same stopped sandbox resumed successfully. Three successful turns retained one live runner PID/start time and the same native, runner, and provider sessions. - Verified exact canonical note contents, deletion persistence, and an unchanged 8 MiB binary after every turn. Subsequent checkpoints copied/hashed only 58 and 87 bytes. After sandbox deletion, canonical files still matched. Temporary secrets were removed and agent/configuration policy restored. - Live acceptance used temporary API-key authentication. The separate managed-subscription authentication issue and browser Retry control were not tested by this campaign. ## Risks - Recovery callers can no longer use stale success status to retain a failed run's sandbox. - The existing native ownership hold still blocks release while ownership is unresolved. - Successful warm turns and explicit destroy dispositions keep their existing behavior. - No database migration, API contract, dependency, or UI change is included. ## Model Used OpenAI Codex, GPT-6, with reasoning, tool use, code execution, and test analysis. The exact served model ID and context-window size are not exposed in this session. ## 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 Co-authored-by: Paperclip --- doc/DEVELOPING.md | 3 ++ ...eat-run-terminalize-before-release.test.ts | 37 +++++++++++++++++++ server/src/services/heartbeat.ts | 13 +++++-- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 40b568a6b64..7fdd364f4a5 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1246,6 +1246,9 @@ Only successful turns retain a live warm provider session. A structured failed or cancelled result must retire that session and collect its managed files before heartbeat stops the reusable sandbox. A later retry can resume the same sandbox without inheriting the stopped provider transport. +The shared lease-release boundary rechecks the durable run status for recovery +and ordinary teardown. Successful workspace copy-back alone must not keep a +failed turn's sandbox running. Run the credential-free real-process restart suite with: diff --git a/server/src/__tests__/heartbeat-run-terminalize-before-release.test.ts b/server/src/__tests__/heartbeat-run-terminalize-before-release.test.ts index 3d0ab72eec6..62555a27371 100644 --- a/server/src/__tests__/heartbeat-run-terminalize-before-release.test.ts +++ b/server/src/__tests__/heartbeat-run-terminalize-before-release.test.ts @@ -301,6 +301,43 @@ describeEmbeddedPostgres("heartbeat teardown terminalizes the run before releasi expect(releaseRunLeases).not.toHaveBeenCalled(); }); + it.each(["failed", "cancelled", "timed_out", "interrupted", "succeeded"])( + "uses the durable %s outcome when recovered workspace cleanup requests warm retention", + async (status) => { + const { companyId, agentId, issueId, runId } = await seed({ + issueStatus: status === "succeeded" ? "done" : "blocked", + runStatus: status, + }); + await db.update(heartbeatRuns).set({ + runtimeMode: "native", + nativeIssueId: issueId, + nativePhase: "committed", + finishedAt: new Date(), + }).where(eq(heartbeatRuns.id, runId)); + const releaseRunLeases = vi.fn(async () => []); + const heartbeat = heartbeatService(db, { + environmentRuntime: { releaseRunLeases } as unknown as HeartbeatEnvironmentRuntime, + }); + + // Successful workspace copy-back does not make a failed provider turn + // successful. Recovery can reach this boundary without the run's finally. + await heartbeat.releaseEnvironmentLeasesForRun({ + runId, + companyId, + agentId, + status: "succeeded", + providerResourceDisposition: "keep_running", + }); + + expect(releaseRunLeases).toHaveBeenCalledWith( + runId, + leaseReleaseStatusForRunStatus(status), + expect.any(Function), + status === "succeeded" ? "keep_running" : "stop_and_retain", + ); + }, + ); + it.each(["daytona", "local"])("destroy after failed checkpoint requires a terminal remote owner: %s", async provider => { const { companyId, agentId, runId } = await seed({ issueStatus: "blocked", runStatus: "running" }); await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId)); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 0b77ae299c8..388f1583fa8 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -10173,7 +10173,14 @@ export function heartbeatService( }) { const leaseOwnerRun = await getRun(input.runId); if (leaseOwnerRun && isNativeRunnerOwnershipHeld(leaseOwnerRun)) return; - if (input.providerResourceDisposition === "destroy") { + // Recovery can finish workspace copy-back outside the executor's finally. + // Successful copy-back does not earn warm retention for a failed turn. + const status = leaseOwnerRun?.status ?? input.status; + const providerResourceDisposition = providerResourceDispositionForTerminalRun( + input.providerResourceDisposition, + status, + ); + if (providerResourceDisposition === "destroy") { const closeResult = await ( options.closeWarmNativeSessionsForRun ?? (async ({ runId, reason }) => { @@ -10241,9 +10248,9 @@ export function heartbeatService( heartbeatRunId: input.runId, companyId: input.companyId, agentId: input.agentId, - status: leaseReleaseStatusForRunStatus(input.status), + status: leaseReleaseStatusForRunStatus(status), failureReason: input.failureReason ?? undefined, - providerResourceDisposition: input.providerResourceDisposition, + providerResourceDisposition, nativeLifecycleTelemetry: input.nativeLifecycleTelemetry, }) .catch((err) => {