Files
PaperClipAI/server
DottaandPaperclip 3621d7204d 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>
2026-11-30 13:45:49 -06:00
..