mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Remote task workspaces enforce a single writer run at a time (`writerRunId`) and intentionally keep a dirty ended writer held until its unsaved files are saved, proved unchanged, or explicitly abandoned > - Two edge cases left remote workspaces permanently stuck behind an ended writer with `"The workspace still has an unfinished writer or save operation."` (`setup_failed`, HTTP 409) > - First, `readRemoteWorkspaceWriterHold` checked `hasRemoteTerminationReceipt` directly on an unused reservation (`dirty: false`) without resolving an expired `reuse_by_environment` lease through `resolveRemoteTerminationLease` > - Second, when a dirty ended writer already had a recorded continuation or successor run and that successor also ended before taking over the workspace (for example `controller_lease_lost`), no recovery pass could revisit the already-superseded writer, leaving the task wedged forever > - This pull request resolves expired reusable leases in `readRemoteWorkspaceWriterHold` and adds `releaseSupersededRemoteWorkspaceWriter` to safely abandon a superseded ended writer's stale dirty epoch once its successor has ended, while keeping every unsaved-files and board-owned export hold fenced > - The benefit is that wedged tasks recover cleanly without losing unverified files or bypassing intentional board-owned save holds ## Linked Issues or Issue Description Refs #21221 Refs #22103 **What happened?** Remote task workspaces could remain permanently blocked behind an ended writer run, causing every subsequent run to fail setup with `409` / `setup_failed`: `"The workspace still has an unfinished writer or save operation."`: 1. On an unused reservation (`dirty: false`), if the ended writer ran on a `reuse_by_environment` lease that later expired via reusable-lease handoff and whose successor tip lease was destroyed, `readRemoteWorkspaceWriterHold` ignored `resolveRemoteTerminationLease` and treated the workspace as held forever. 2. When a dirty ended writer was already superseded by a recorded successor run (`nativeRunFinalizations.failureDetail.successorRunId`, resolved `explicitUserContinuation`, or resolved `executionReconciliation` with `continuationRunId`), and that successor ended (for example `controller_lease_lost`) before taking over or rebinding the workspace, neither `workspace-recovery-fallback`, `fresh-continuation-fallback`, `settlePreparationOnlyRemoteWorkspaceEpoch`, nor `released-writer-escalation` could ever release the old writer's epoch. Note: a dirty ended writer with an uncommitted accepted result and an open board-owned export recovery hold (for example `native_workspace_sync_out_retry_exhausted` on `sandbox_disk_full`) is intentionally kept fenced; that hold is preserved here. **Expected behavior** - An unused reservation (`dirty: false`) whose expired `reuse_by_environment` lease resolves to a destroyed tip via `resolveRemoteTerminationLease` is reported as `{ kind: "free" }`. - A dirty ended writer whose durable successor has already ended (with no uncommitted accepted result, open/active recovery hold, unsettled no-replay hold, running save, or live controller/finalizer lease) has its stale epoch safely abandoned via `abandonUnverifiedRemoteWorkspaceEpoch` during workspace reservation or stranded-writer escalation settlement, so the next run restores the last committed snapshot into a new directory without overwriting or applying unverified files. - Board-owned unsaved-files export holds and live successors/leases/saves remain strictly fenced. **Steps to reproduce** 1. Bind a task to a remote execution workspace whose ended writer run has `dirty: true` and a recorded `location`, plus a durable successor run recorded on `nativeRunFinalizations.failureDetail.successorRunId`, resolved `explicitUserContinuation`, or resolved `executionReconciliation.continuationRunId`. 2. End the successor run (for example `failed` with `controller_lease_lost`) before it reserves or rebinds a workspace. 3. Call `reserveRemoteWorkspace` for a new run on that workspace (or run `continueTasksAfterWorkspaceWriterReleased` when the task is stranded behind a `setup_failed` writer-pending escalation). Before this change, reservation throws `"The workspace still has an unfinished writer or save operation."` and the task stays blocked forever. 4. Separately, give a clean (`dirty: false`) ended writer an expired `reuse_by_environment` lease whose successor tip lease carries a `destroyed` termination receipt; before this change, `readRemoteWorkspaceWriterHold` returns `{ kind: "held" }` instead of `{ kind: "free" }`. **Paperclip version or commit** `master` at `fb900bf0fe`. **Deployment mode** Self-hosted server / cloud sandbox remote workspaces. ## What Changed - `server/src/services/remote-workspace-writer-hold.ts`: - Resolve `environmentLeases` rows through `resolveRemoteTerminationLease(tx, lease)` in `readRemoteWorkspaceWriterHold` before checking `hasRemoteTerminationReceipt` for `unusedReservation`, matching the repo's other remote termination checks. - Add `releaseSupersededRemoteWorkspaceWriter`, which checks fail-closed guards (terminal ended writer, `FOR UPDATE SKIP LOCKED`, no live controller/finalizer lease, no running snapshot operation on the epoch, no uncommitted accepted result, identifiable writer issue, no open/escalated recovery action, no active `systemRecovery`, no unsettled `automaticRecovery.replay === "blocked"` hold, no unsettled `restore_unsafe_archive` hold, durable `successorRunId` present, and every non-caller successor run is terminal and not live) and abandons the stale epoch via `abandonUnverifiedRemoteWorkspaceEpoch`. - `server/src/services/remote-workspaces.ts`: - In `reserveRemoteWorkspace`, attempt `releaseSupersededRemoteWorkspaceWriter` right after `releaseUnchangedRemoteWorkspaceWriter` when an ended dirty writer still holds the workspace. - `server/src/services/recovery/released-writer-escalation.ts`: - Lock the bound `executionWorkspaces` row in `continueOne` and attempt `releaseSupersededRemoteWorkspaceWriter` before `readRemoteWorkspaceWriterHold`, so tasks already stranded behind a superseded ended writer's hold unblock and continue once. - `server/src/__tests__/released-writer-escalation.test.ts`: - Add red-first behavioral regressions for expired reusable lease resolution (destroyed vs stopped vs active tip), superseded dirty writers across all three supersession paths (`coordinator`, `explicit_continuation`, `reconciliation`) and both `failed` and `succeeded` writers, stranded-task recovery, and 12 negative safety guards (including board-owned uncommitted accepted result export holds, live successors, open recovery actions, active system recovery, unsettled no-replay holds, unsafe archive holds, running snapshot saves, and live controller/finalizer leases). ## Verification - **Red (before production edits)**: - 5/5 targeted behavioral regressions failed (`destroyed-tip` returned `held` instead of `free`; `coordinator`, `explicit_continuation`, and `reconciliation` superseded dirty writers threw `"The workspace still has an unfinished writer or save operation."`; stranded task stayed `blocked`), while all safety negative tests passed. - **Green (at `8159b9a39c`, rebased on `master` after `#22831`)**: - `npx tsc --noEmit -p server/tsconfig.json`: passed. - `node scripts/check-test-budget.mjs --base origin/master`: passed (`105 nightly suites validated, 1 test file(s) checked`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/released-writer-escalation.test.ts`: **25/25 passed**. - Prior pre-rebase targeted matrix across sibling suites (`abandoned-workspace-files-hold`, `issue-blocker-stall-wakeups`, `native-cancelled-workspace-preservation`, `heartbeat-remote-workspace-busy`, `legacy-workspace-rehome`, `workspace-recovery-stop-proof`, `superseded-workspace-export-recovery`, `remote-workspace-save-concurrency`): **185/185 passed**; required CI covers the full suite, build, and E2E on `8159b9a39c`. ## Risks - **Low risk, fail-closed design**: `releaseSupersededRemoteWorkspaceWriter` never touches an unsuperseded writer, an uncommitted accepted result (board-owned save holds stay fenced), an open/active recovery hold, an unsettled no-replay hold, a running save, or a live successor/controller/finalizer lease. - When abandonment runs, it uses `abandonUnverifiedRemoteWorkspaceEpoch` to advance the epoch, retain the old root in `remoteWorkspaceAbandonedEpochs` (never overwritten or applied), and force the next run to restore the last committed snapshot into a new directory. - Row locking follows the existing lock order (`issues` -> `issueRecoveryActions` -> `executionWorkspaces` -> `heartbeatRuns FOR UPDATE SKIP LOCKED`), avoiding lock inversions and deadlocks. - No schema change, no migration, and no Runner protocol change. - Note on file length: `server/src/services/remote-workspaces.ts` was already over 1,000 lines; this PR adds only 6 lines there (import + fallback call) and keeps all new logic in `server/src/services/remote-workspace-writer-hold.ts` (242 lines). ## Model Used - Google Gemini (Antigravity agentic coding environment) with tool use (shell, file read/edit, code search, Vitest execution) and extended reasoning. ## 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
Server Tests
Server tests that need a real PostgreSQL process must use
./helpers/embedded-postgres.ts instead of constructing embedded-postgres
directly.
The shared helper creates a throwaway data directory and a reserved-safe loopback port for each test database. This protects the live Paperclip control-plane Postgres from server vitest runs; see PAP-2033 for the incident that introduced this guard.