From cd02a8e0e4299f0c6a6c8eb6bd08482887590563 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:34:15 -0600 Subject: [PATCH] fix(workspaces): release superseded ended writers and resolve expired reusable leases on writer holds (#22847) ## 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 --- .../released-writer-escalation.test.ts | 343 +++++++++++++++++- .../recovery/released-writer-escalation.ts | 24 +- .../services/remote-workspace-writer-hold.ts | 178 ++++++++- server/src/services/remote-workspaces.ts | 8 +- 4 files changed, 533 insertions(+), 20 deletions(-) diff --git a/server/src/__tests__/released-writer-escalation.test.ts b/server/src/__tests__/released-writer-escalation.test.ts index e81be6042a1..f70b474b8d2 100644 --- a/server/src/__tests__/released-writer-escalation.test.ts +++ b/server/src/__tests__/released-writer-escalation.test.ts @@ -3,11 +3,20 @@ import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { and, eq, sql } from "drizzle-orm"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { activityLog, agents, agentWakeupRequests, authUsers, companies, companyMemberships, createDb, executionWorkspaces, - heartbeatRuns, issueRecoveryActions, issueRelations, issues, statusDecisions } from "@paperclipai/db"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { activityLog, agents, agentWakeupRequests, authUsers, companies, companyMemberships, completionContracts, createDb, environments, + environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issueRelations, issues, nativeRunFinalizations, + nativeRunResults, projects, projectWorkspaces, statusDecisions, workspaceOperations } from "@paperclipai/db"; +import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; +import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; +import { createStorageService } from "../storage/service.js"; +import { createReusableLeaseHandoff } from "../services/environment-lease-handoff.js"; import { heartbeatService } from "../services/heartbeat.js"; -import { REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE } from "../services/remote-workspace-writer-hold.js"; +import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; +import { readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, remoteWorkspaceHoldRefusesStart } + from "../services/remote-workspace-writer-hold.js"; +import { REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA } from "../services/remote-workspace-epoch-abandonment.js"; +import { reserveRemoteWorkspace } from "../services/remote-workspaces.js"; import { continueTasksAfterWorkspaceWriterReleased, RELEASED_WORKSPACE_WRITER_OUTCOME } from "../services/recovery/released-writer-escalation.js"; import { recoveryActionSweepCondition } from "../services/recovery/blocker-stall-wakeups.js"; @@ -50,6 +59,10 @@ describePostgres("a task stranded behind its own workspace's ended writer", () = heartbeat = heartbeatService(db); }, 240_000); + afterEach(() => { + vi.unstubAllEnvs(); + }); + afterAll(async () => { await heartbeat?.drainActiveRunExecutions(); await db?.$client.end({ timeout: 0 }); @@ -238,4 +251,326 @@ describePostgres("a task stranded behind its own workspace's ended writer", () = expect(await action(f.actionId)).toMatchObject({ status: "active" }); expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]); }, 60_000); + + it("abandons a superseded ended writer's stale epoch and continues the stranded task", async () => { + const f = await seedStrandedTask(); + const leaseId = randomUUID(); + const location = { environmentId: randomUUID(), leaseId, providerLeaseId: randomUUID(), + remoteCwd: `/work/.paperclip-workspaces/${f.workspaceId}-3-${leaseId}` }; + const [wsBefore] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)); + const currentAuthority = readRemoteWorkspaceAuthority(wsBefore!.metadata)!; + await db.update(executionWorkspaces).set({ metadata: { ...wsBefore!.metadata, + remoteWorkspace: { ...currentAuthority, location } } }).where(eq(executionWorkspaces.id, f.workspaceId)); + const successorId = randomUUID(); + const [writerRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.writerRunId)); + await db.update(heartbeatRuns).set({ errorCode: "native_continuation_requires_reconciliation" }) + .where(eq(heartbeatRuns.id, f.writerRunId)); + await db.insert(heartbeatRuns).values({ id: successorId, companyId: f.companyId, agentId: f.agentId, + issueId: f.task.id, nativeIssueId: f.task.id, runtimeMode: "native", status: "failed", + errorCode: "controller_lease_lost", + createdAt: new Date(writerRun!.finishedAt!.getTime() + 60_000), + finishedAt: new Date(writerRun!.finishedAt!.getTime() + 5 * 60_000), + contextSnapshot: { issueId: f.task.id } }); + await db.insert(nativeRunFinalizations).values({ runId: f.writerRunId, companyId: f.companyId, + issueId: f.task.id, phase: "terminal_failure", attempt: 1, + failureCode: "native_continuation_requires_reconciliation", + failureDetail: { successorRunId: successorId } }); + + expect(await scheduledRecoveryPass(f.companyId)).toBe(true); + + expect(await issue(f.task.id)).toMatchObject({ status: "todo", blockedTransitionAt: null, executionWorkspaceId: f.workspaceId }); + expect(await action(f.actionId)).toMatchObject({ status: "resolved", outcome: "restored", + resolutionNote: RELEASED_WORKSPACE_WRITER_OUTCOME }); + const [wsAfter] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)); + expect(readRemoteWorkspaceAuthority(wsAfter!.metadata)).toMatchObject({ + epoch: 4, writerRunId: null, dirty: false, location: null, snapshotId: currentAuthority.snapshotId, + }); + expect(wsAfter!.metadata?.remoteWorkspaceAbandonedEpochs).toEqual([expect.objectContaining({ + schema: REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA, epoch: 3, runId: f.writerRunId, location, + })]); + expect(wakesFor(f.task.id)).toHaveLength(1); + }, 60_000); + + it("keeps a stranded task blocked when the writer holds unsaved files for a board-owned export recovery", async () => { + const f = await seedStrandedTask(); + const leaseId = randomUUID(); + const location = { environmentId: randomUUID(), leaseId, providerLeaseId: randomUUID(), + remoteCwd: `/work/.paperclip-workspaces/${f.workspaceId}-3-${leaseId}` }; + const [wsBefore] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)); + const currentAuthority = readRemoteWorkspaceAuthority(wsBefore!.metadata)!; + const heldMetadata = { ...wsBefore!.metadata, remoteWorkspace: { ...currentAuthority, location } }; + await db.update(executionWorkspaces).set({ metadata: heldMetadata }).where(eq(executionWorkspaces.id, f.workspaceId)); + const [contract] = await db.insert(completionContracts).values({ + companyId: f.companyId, issueId: f.task.id, 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({ errorCode: "native_workspace_sync_out_retry_exhausted", completionContractId: contract!.id }) + .where(eq(heartbeatRuns.id, f.writerRunId)); + const [res] = await db.insert(nativeRunResults).values({ companyId: f.companyId, issueId: f.task.id, + runId: f.writerRunId, completionContractId: contract!.id, serverFingerprint: `fp-${f.writerRunId}`, + schemaStatus: "accepted", resultJson: { terminalState: "succeeded" }, canonicalSha256: "b".repeat(64) }).returning(); + await db.insert(nativeRunFinalizations).values({ runId: f.writerRunId, companyId: f.companyId, + issueId: f.task.id, phase: "terminal_failure", attempt: 3, resultId: res!.id, + failureCode: "native_workspace_sync_out_retry_exhausted" }); + + expect(await scheduledRecoveryPass(f.companyId)).toBe(true); + + expect(await issue(f.task.id)).toMatchObject({ status: "blocked" }); + expect(await action(f.actionId)).toMatchObject({ status: "active", ownerType: "board" }); + const [wsAfter] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspaceId)); + expect(readRemoteWorkspaceAuthority(wsAfter!.metadata)).toEqual({ ...currentAuthority, location }); + expect(wakesFor(f.task.id)).toEqual([]); + }, 60_000); + + async function seedReservationWorkspace() { + vi.stubEnv("DATABASE_URL", temporary.connectionString); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "62".repeat(32)); + const [company] = await db.insert(companies).values({ name: "Writer hold reservation", issuePrefix: `R${randomUUID().slice(0, 6)}` }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Worker", adapterType: "paperclip_runner" }).returning(); + const [project] = await db.insert(projects).values({ companyId: company!.id, name: "Source project" }).returning(); + const [source] = await db.insert(projectWorkspaces).values({ companyId: company!.id, projectId: project!.id, + name: "Task files", sourceType: "empty" }).returning(); + const [environment] = await db.insert(environments).values({ name: `Reservation ${randomUUID()}`, driver: "sandbox", config: {} }).returning(); + const [task] = await db.insert(issues).values({ companyId: company!.id, projectId: project!.id, + projectWorkspaceId: source!.id, title: "Continue saved work", status: "todo", assigneeAgentId: agent!.id }).returning(); + const snapshotId = randomUUID(); + const authority = { schema: "paperclip.remote-workspace.v1" as const, epoch: 3, snapshotId, + source: { kind: "empty" as const }, location: null, writerRunId: null, dirty: false }; + const [workspace] = await db.insert(executionWorkspaces).values({ companyId: company!.id, sourceIssueId: task!.id, + projectId: project!.id, projectWorkspaceId: source!.id, name: "Task files", mode: "isolated_workspace", + strategyType: "project_primary", providerType: "cloud_sandbox", cwd: `/workspaces/${randomUUID()}`, + metadata: { remoteWorkspace: authority } }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace!.id, executionWorkspacePreference: "reuse_existing", + executionWorkspaceSettings: { mode: "isolated_workspace" } }).where(eq(issues.id, task!.id)); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent!.id, + issueId: task!.id, status: "running", runtimeMode: "legacy" }).returning(); + const storage = { ...createStorageService(createLocalDiskStorageProvider(path.join(home, company!.id))), provider: "s3" as const }; + const input = { db, storage, companyId: company!.id, issueId: task!.id, runId: run!.id, agentId: agent!.id, + environmentId: environment!.id, projectId: project!.id, projectWorkspaceId: source!.id, + existingWorkspaceId: workspace!.id, source: authority.source }; + const readWorkspace = async () => (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace!.id)))[0]!; + return { input, company: company!, agent: agent!, task: task!, workspace: workspace!, authority, run: run!, readWorkspace }; + } + + it.each(["destroyed-tip", "stopped-tip", "active-tip"] as const) + ("resolves an expired reusable lease through its destroyed tip before holding an unused reservation (%s)", async mode => { + const f = await seedReservationWorkspace(); + const endedAt = new Date(Date.now() - 2 * 60 * 60_000); + const handoffAt = new Date(endedAt.getTime() + 60_000); + const [writer] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, + issueId: f.task.id, status: "failed", finishedAt: endedAt }).returning(); + const [tipRun] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, + issueId: f.task.id, status: mode === "active-tip" ? "running" : "succeeded", + finishedAt: mode === "active-tip" ? null : new Date(handoffAt.getTime() + 60_000) }).returning(); + const providerLeaseId = randomUUID(); + const [expiredLease] = await db.insert(environmentLeases).values({ companyId: f.company.id, environmentId: f.input.environmentId, + executionWorkspaceId: f.workspace.id, heartbeatRunId: writer!.id, issueId: f.task.id, provider: "daytona", providerLeaseId, + status: "expired", cleanupStatus: "success", leasePolicy: "reuse_by_environment", + acquiredAt: new Date(endedAt.getTime() - 60_000), releasedAt: handoffAt, + metadata: { agentId: f.agent.id } }).returning(); + const [tipLease] = await db.insert(environmentLeases).values({ companyId: f.company.id, environmentId: f.input.environmentId, + executionWorkspaceId: f.workspace.id, heartbeatRunId: tipRun!.id, issueId: f.task.id, provider: "daytona", providerLeaseId, + status: mode === "active-tip" ? "active" : "released", + cleanupStatus: mode === "active-tip" ? null : "success", + leasePolicy: "reuse_by_environment", + acquiredAt: handoffAt, releasedAt: mode === "active-tip" ? null : new Date(handoffAt.getTime() + 60_000), + metadata: { agentId: f.agent.id } }).returning(); + const handoff = createReusableLeaseHandoff(expiredLease!, tipLease!); + await db.update(environmentLeases).set({ metadata: { agentId: f.agent.id, reusableLeaseSuccessor: handoff } }) + .where(eq(environmentLeases.id, expiredLease!.id)); + const tipTermination = mode === "destroyed-tip" + ? remoteTerminationReceipt(tipLease!, { providerLeaseId, state: "destroyed" }) + : mode === "stopped-tip" + ? remoteTerminationReceipt(tipLease!, { providerLeaseId, state: "stopped" }) + : undefined; + await db.update(environmentLeases).set({ metadata: { + agentId: f.agent.id, reusableLeasePredecessor: handoff, + ...(tipTermination ? { remoteExecutionTermination: tipTermination } : {}), + } }).where(eq(environmentLeases.id, tipLease!.id)); + const held = { ...f.authority, writerRunId: writer!.id, dirty: false }; + await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: held } }).where(eq(executionWorkspaces.id, f.workspace.id)); + + const hold = await readRemoteWorkspaceWriterHold(db, { companyId: f.company.id, authority: held, runId: f.run.id }); + if (mode === "destroyed-tip") { + expect(hold).toEqual({ kind: "free" }); + await expect(reserveRemoteWorkspace(f.input)).resolves.toMatchObject({ id: f.workspace.id }); + expect(readRemoteWorkspaceAuthority((await f.readWorkspace()).metadata)).toMatchObject({ writerRunId: f.run.id, epoch: 4 }); + } else { + expect(hold.kind).toBe("held"); + await expect(reserveRemoteWorkspace(f.input)).rejects.toThrow("unfinished writer"); + } + }); + + async function seedDirtyEndedWriter(options: { + supersession: "coordinator" | "explicit_continuation" | "reconciliation" | "none"; + writerStatus?: "failed" | "succeeded"; + successorStatus?: "failed" | "running" | "queued"; + uncommittedAcceptedResult?: boolean; + openRecoveryAction?: boolean; + pendingSystemRecovery?: boolean; + unsettledNoReplayHold?: boolean; + unsafeArchiveHold?: boolean; + runningSnapshotOp?: boolean; + liveControllerLease?: boolean; + liveFinalizerLease?: boolean; + }) { + const f = await seedReservationWorkspace(); + const endedAt = new Date(Date.now() - 2 * 60 * 60_000); + const leaseId = randomUUID(); + const location = { environmentId: f.input.environmentId, leaseId, providerLeaseId: randomUUID(), + remoteCwd: `/work/.paperclip-workspaces/${f.workspace.id}-3-${leaseId}` }; + let contractId: string | null = null; + if (options.uncommittedAcceptedResult) { + const [contract] = await db.insert(completionContracts).values({ + companyId: f.company.id, issueId: f.task.id, 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(); + contractId = contract!.id; + } + const [writer] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, + issueId: f.task.id, nativeIssueId: f.task.id, completionContractId: contractId, runtimeMode: "native", + status: options.writerStatus ?? "failed", + errorCode: options.uncommittedAcceptedResult ? "native_workspace_sync_out_retry_exhausted" : "native_continuation_requires_reconciliation", + createdAt: new Date(endedAt.getTime() - 10 * 60_000), startedAt: new Date(endedAt.getTime() - 9 * 60_000), + finishedAt: endedAt, + controllerLeaseExpiresAt: options.liveControllerLease ? new Date(Date.now() + 10 * 60_000) : null, + contextSnapshot: { issueId: f.task.id }, + runnerProfileJson: { remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", workspaceId: f.workspace.id, + leaseId, providerLeaseId: location.providerLeaseId, remoteCwd: location.remoteCwd, + epoch: f.authority.epoch, state: "prepared", snapshotId: f.authority.snapshotId } } }).returning(); + const [successor] = options.supersession !== "none" ? await db.insert(heartbeatRuns).values({ + companyId: f.company.id, agentId: f.agent.id, issueId: f.task.id, nativeIssueId: f.task.id, + runtimeMode: "native", status: options.successorStatus ?? "failed", errorCode: options.successorStatus ? null : "controller_lease_lost", + createdAt: new Date(endedAt.getTime() + 60_000), + finishedAt: (options.successorStatus ?? "failed") === "failed" ? new Date(endedAt.getTime() + 5 * 60_000) : null, + contextSnapshot: { issueId: f.task.id } }).returning() : []; + const held = { ...f.authority, writerRunId: writer!.id, dirty: true, location }; + await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: held } }).where(eq(executionWorkspaces.id, f.workspace.id)); + let resultId: string | null = null; + if (options.uncommittedAcceptedResult && contractId) { + const [res] = await db.insert(nativeRunResults).values({ companyId: f.company.id, issueId: f.task.id, + runId: writer!.id, completionContractId: contractId, serverFingerprint: `fp-${writer!.id}`, + schemaStatus: "accepted", resultJson: { terminalState: "succeeded" }, canonicalSha256: "b".repeat(64) }).returning(); + resultId = res!.id; + } + await db.insert(nativeRunFinalizations).values({ + runId: writer!.id, companyId: f.company.id, issueId: f.task.id, + phase: "terminal_failure", attempt: 1, resultId, + leaseOwner: options.liveFinalizerLease ? "native-finalizer:live" : null, + leaseExpiresAt: options.liveFinalizerLease ? new Date(Date.now() + 10 * 60_000) : null, + failureCode: options.uncommittedAcceptedResult ? "native_workspace_sync_out_retry_exhausted" : "native_continuation_requires_reconciliation", + failureDetail: options.supersession === "coordinator" && successor ? { successorRunId: successor.id } : {}, + }); + if (options.supersession === "explicit_continuation" && successor) { + await db.insert(issueRecoveryActions).values({ companyId: f.company.id, sourceIssueId: f.task.id, + kind: "active_run_watchdog", status: "resolved", outcome: "cancelled", ownerType: "system", + cause: "native_continuation_requires_reconciliation", fingerprint: `explicit:${writer!.id}`, + nextAction: "User started a fresh continuation.", + evidence: { runId: writer!.id, automaticRecovery: { policy: "preserve_without_replay_v1", replay: "explicit_user_continuation", runId: writer!.id }, + explicitUserContinuation: { previousRunId: writer!.id, runId: successor.id, + readiness: { mode: "fresh_isolated_workspace", retryIntentId: randomUUID(), sourceRunId: writer!.id, retainedSourceIds: [] } } } }); + } + if (options.supersession === "reconciliation" && successor) { + await db.insert(issueRecoveryActions).values({ companyId: f.company.id, sourceIssueId: f.task.id, + kind: "active_run_watchdog", status: "resolved", outcome: "restored", ownerType: "system", + cause: "native_continuation_requires_reconciliation", fingerprint: `reconciled:${writer!.id}`, + nextAction: "Continued in a fresh run.", + evidence: { runId: writer!.id, executionReconciliation: { runId: writer!.id, providerStopped: true, actionOutcome: "mixed", outcomeEvidence: "continued" }, + continuationDelivery: "delivered", continuationRunId: successor.id } }); + } + if (options.openRecoveryAction) { + await db.insert(issueRecoveryActions).values({ companyId: f.company.id, sourceIssueId: f.task.id, + kind: "active_run_watchdog", status: "active", ownerType: "board", + cause: options.uncommittedAcceptedResult ? "native_workspace_sync_out_retry_exhausted" : "native_continuation_requires_reconciliation", + fingerprint: `open:${writer!.id}`, nextAction: "Retry to save files.", evidence: { runId: writer!.id } }); + } + if (options.pendingSystemRecovery) { + await db.insert(issueRecoveryActions).values({ companyId: f.company.id, sourceIssueId: f.task.id, + kind: "active_run_watchdog", status: "resolved", outcome: "blocked", ownerType: "system", + cause: "native_continuation_requires_reconciliation", fingerprint: `sysrec:${writer!.id}`, + nextAction: "Saving files.", + evidence: { runId: writer!.id, systemRecovery: { schema: "paperclip.system-recovery.v1", policyVersion: 1, + sourceRunId: writer!.id, revision: 1, generationId: randomUUID(), intentId: null, phase: "preserve_files", + state: "running", attemptId: randomUUID(), attempts: 1, retriesUsed: 0, firstFailureAt: null, + nextAttemptAt: null, deadlineAt: null, providerCooldownAt: null, failure: null, + preservationOperationIds: [], freshAttemptRunId: null } } }); + } + if (options.unsettledNoReplayHold) { + await db.insert(issueRecoveryActions).values({ companyId: f.company.id, sourceIssueId: f.task.id, + kind: "active_run_watchdog", status: "resolved", outcome: "blocked", ownerType: "board", + cause: "native_continuation_requires_reconciliation", fingerprint: `noreplay:${writer!.id}`, + nextAction: "Stopped.", + evidence: { runId: writer!.id, automaticRecovery: { policy: "preserve_without_replay_v1", replay: "blocked", runId: writer!.id } } }); + } + if (options.unsafeArchiveHold) { + await db.insert(issueRecoveryActions).values({ companyId: f.company.id, sourceIssueId: f.task.id, + kind: "active_run_watchdog", status: "resolved", outcome: "blocked", ownerType: "board", + cause: "native_continuation_requires_reconciliation", fingerprint: `unsafe:${writer!.id}`, + nextAction: "Archive refused.", + evidence: { runId: writer!.id, workspaceRestoreFailure: "restore_unsafe_archive" } }); + } + if (options.runningSnapshotOp) { + await db.insert(workspaceOperations).values({ companyId: f.company.id, issueId: f.task.id, heartbeatRunId: writer!.id, + executionWorkspaceId: f.workspace.id, phase: "remote_workspace_snapshot", status: "running", + metadata: { epoch: String(f.authority.epoch), boundary: "final" } }); + } + return { ...f, writer: writer!, successor, held, location }; + } + + it.each(["coordinator", "explicit_continuation", "reconciliation"] as const) + ("abandons a superseded ended writer's dirty epoch on reservation once its successor has ended (%s)", async supersession => { + const f = await seedDirtyEndedWriter({ supersession }); + const reserved = await reserveRemoteWorkspace(f.input); + expect(reserved.id).toBe(f.workspace.id); + // Epoch advances once for abandonment (3 -> 4) and once for reservation (4 -> 5), + // clearing dirty and location so the next run restores the last committed snapshot into a new root. + expect(readRemoteWorkspaceAuthority(reserved.metadata)).toEqual({ + ...f.authority, epoch: 5, writerRunId: f.run.id, dirty: false, location: null, + }); + const abandoned = (reserved.metadata?.remoteWorkspaceAbandonedEpochs ?? []) as Array>; + expect(abandoned).toEqual([expect.objectContaining({ + schema: REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA, + epoch: 3, runId: f.writer.id, snapshotId: f.authority.snapshotId, location: f.location, + })]); + }); + + it("abandons a succeeded superseded dirty writer's epoch once its successor has ended", async () => { + const f = await seedDirtyEndedWriter({ supersession: "coordinator", writerStatus: "succeeded" }); + const reserved = await reserveRemoteWorkspace(f.input); + expect(readRemoteWorkspaceAuthority(reserved.metadata)).toEqual({ + ...f.authority, epoch: 5, writerRunId: f.run.id, dirty: false, location: null, + }); + }); + + it("keeps a board-owned unsaved-files export hold fenced during reservation", async () => { + const f = await seedDirtyEndedWriter({ supersession: "none", uncommittedAcceptedResult: true, openRecoveryAction: true }); + const hold = await readRemoteWorkspaceWriterHold(db, { companyId: f.company.id, authority: f.held, runId: f.run.id }); + expect(hold.kind).toBe("held"); + expect(remoteWorkspaceHoldRefusesStart(hold)).toBe(true); + await expect(reserveRemoteWorkspace(f.input)).rejects.toThrow("unfinished writer"); + expect(readRemoteWorkspaceAuthority((await f.readWorkspace()).metadata)).toEqual(f.held); + }); + + it.each([ + ["live successor running", { supersession: "explicit_continuation" as const, successorStatus: "running" as const }], + ["live successor queued", { supersession: "explicit_continuation" as const, successorStatus: "queued" as const }], + ["open recovery action", { supersession: "coordinator" as const, openRecoveryAction: true }], + ["pending system recovery", { supersession: "coordinator" as const, pendingSystemRecovery: true }], + ["unsettled no-replay hold", { supersession: "coordinator" as const, unsettledNoReplayHold: true }], + ["unsafe archive hold", { supersession: "coordinator" as const, unsafeArchiveHold: true }], + ["uncommitted accepted result", { supersession: "coordinator" as const, uncommittedAcceptedResult: true }], + ["running snapshot save", { supersession: "coordinator" as const, runningSnapshotOp: true }], + ["live controller lease", { supersession: "coordinator" as const, liveControllerLease: true }], + ["live finalizer lease", { supersession: "coordinator" as const, liveFinalizerLease: true }], + ])("refuses to abandon a superseded writer while safety guard holds (%s)", async (_label, opts) => { + const f = await seedDirtyEndedWriter(opts); + await expect(reserveRemoteWorkspace(f.input)).rejects.toThrow("unfinished writer"); + expect(readRemoteWorkspaceAuthority((await f.readWorkspace()).metadata)).toEqual(f.held); + }); }); diff --git a/server/src/services/recovery/released-writer-escalation.ts b/server/src/services/recovery/released-writer-escalation.ts index 2fe660eee9e..c2db29a2aaf 100644 --- a/server/src/services/recovery/released-writer-escalation.ts +++ b/server/src/services/recovery/released-writer-escalation.ts @@ -4,7 +4,7 @@ import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { logger } from "../../middleware/logger.js"; import { persistActivity, publishActivity } from "../activity-log.js"; import { issueService } from "../issues.js"; -import { readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE } from "../remote-workspace-writer-hold.js"; +import { readRemoteWorkspaceWriterHold, releaseSupersededRemoteWorkspaceWriter, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE } from "../remote-workspace-writer-hold.js"; import { notifyStatusCardIssueChange } from "../status-card-notifications.js"; import { deliverPendingRecoveryWakes, type PendingRecoveryWake, type RehomeWakeup } from "./legacy-workspace-rehome.js"; @@ -28,10 +28,14 @@ export const RELEASED_WORKSPACE_WRITER_NOTE = "This task could not start while a * continues from its last save), nothing a person could do remains. This pass * settles the escalation in one transaction: it resolves with a named outcome, * the task returns to `todo`, and a pending wake is recorded and delivered - * after commit (a wake lost to a crash stays pending for the next pass). The - * workspace itself is never changed here: the next run's admission takes it - * through the normal writer rule. Bounded and idempotent: a resolved - * escalation is never revisited, and a failed guard leaves the task as it is. + * after commit (a wake lost to a crash stays pending for the next pass). When + * the workspace is held only by a superseded ended writer whose successor has + * also ended (with no open recovery hold or uncommitted accepted result), that + * stale dirty epoch is abandoned first so the next run restores the last + * committed save into a new root; otherwise the workspace is never changed here + * and the next run's admission takes it through the normal writer rule. Bounded + * and idempotent: a resolved escalation is never revisited, and a failed guard + * leaves the task as it is. */ export async function continueTasksAfterWorkspaceWriterReleased(db: Db, wake: RehomeWakeup | null, scope: { companyId?: string; issueId?: string } = {}) { @@ -114,9 +118,13 @@ async function continueOne(tx: Db, input: { actionId: string; companyId: string; if (readiness.get(issue.id)?.isDependencyReady !== true) return null; // The hold that refused the run has settled: workspace reservation would now // admit a new writer. A writer still saving or running keeps the task as it is. - const [workspace] = await tx.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces) - .where(and(eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, issue.executionWorkspaceId))); - const authority = workspace ? readRemoteWorkspaceAuthority(workspace.metadata) : null; + const [workspace] = await tx.select().from(executionWorkspaces) + .where(and(eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, issue.executionWorkspaceId))).for("update"); + let authority = workspace ? readRemoteWorkspaceAuthority(workspace.metadata) : null; + if (workspace && authority?.dirty && authority.writerRunId) { + const released = await releaseSupersededRemoteWorkspaceWriter(tx, { workspace, authority }); + if (released) authority = released.authority; + } if (!authority || (await readRemoteWorkspaceWriterHold(tx, { companyId: input.companyId, authority })).kind !== "free") return null; const now = new Date(); await tx.update(issueRecoveryActions).set({ status: "resolved", outcome: "restored", resolvedAt: now, updatedAt: now, diff --git a/server/src/services/remote-workspace-writer-hold.ts b/server/src/services/remote-workspace-writer-hold.ts index cf9f9c946c9..66aeb0ff5dc 100644 --- a/server/src/services/remote-workspace-writer-hold.ts +++ b/server/src/services/remote-workspace-writer-hold.ts @@ -1,13 +1,75 @@ -import { and, eq, sql } from "drizzle-orm"; -import { environmentLeases, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, type Db } from "@paperclipai/db"; -import type { RemoteWorkspaceAuthority } from "@paperclipai/shared"; -import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, + workspaceOperations, type Db } from "@paperclipai/db"; +import { remoteWorkspaceRunReferenceSchema, type RemoteWorkspaceAuthority } from "@paperclipai/shared"; +import { adapterExecutionControls } from "./adapter-execution-control.js"; +import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt, resolveRemoteTerminationLease } from "./remote-execution-termination.js"; import { canonicalExecutionUuid } from "./execution-identity.js"; +import { abandonUnverifiedRemoteWorkspaceEpoch } from "./remote-workspace-epoch-abandonment.js"; import { REMOTE_WORKSPACE_PREPARATION_TIMEOUT_CODE } from "./remote-workspace-transport.js"; -import { WORKSPACE_BUSY_HOLDER_STALE_AFTER_MS } from "../modules/run-dispatch/index.js"; +import { readSystemRecovery } from "./system-recovery-state.js"; +import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js"; +import { wakeWorkspaceBusyWaitersInTx, WORKSPACE_BUSY_HOLDER_STALE_AFTER_MS } from "../modules/run-dispatch/index.js"; + +type Transaction = Parameters[0]>[0]; +type WriterHoldTx = Db | Transaction; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const TERMINAL_RUN_STATUSES = ["failed", "cancelled", "interrupted", "timed_out", "succeeded"]; +const ACTIVE_SYSTEM_RECOVERY_STATES = ["scheduled", "running", "awaiting_evidence"]; +const ACTIVE_CONTINUATION_DELIVERIES = ["pending", "delivered", "delegated"]; const object = (value: unknown): Record => typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : {}; +const uuid = (value: unknown): string | null => typeof value === "string" && UUID_RE.test(value) ? value : null; + +type RecoveryActionRow = { status: string; evidence: Record }; + +function hasBlockingUnsafeArchiveHold(action: RecoveryActionRow, writerId: string): boolean { + if (action.evidence.workspaceRestoreFailure !== "restore_unsafe_archive") return false; + return explicitContinuationSuccessorId(action, writerId) === null + && reconciliationSuccessorId(action, writerId) === null; +} + +function explicitContinuationSuccessorId(action: RecoveryActionRow, writerId: string): string | null { + const explicit = object(action.evidence.explicitUserContinuation); + const runId = uuid(explicit.runId); + return explicit.previousRunId === writerId && runId && runId !== writerId ? runId : null; +} + +function reconciliationSuccessorId(action: RecoveryActionRow, writerId: string): string | null { + if (!action.evidence.executionReconciliation) return null; + if (!ACTIVE_CONTINUATION_DELIVERIES.includes(String(action.evidence.continuationDelivery))) return null; + const runId = uuid(action.evidence.continuationRunId); + return runId && runId !== writerId ? runId : null; +} + +function writerHasBlockingHold(actions: RecoveryActionRow[], writerId: string): boolean { + return actions.some(action => { + if (["active", "escalated"].includes(action.status)) return true; + const systemRecovery = readSystemRecovery(action.evidence); + if (systemRecovery && ACTIVE_SYSTEM_RECOVERY_STATES.includes(systemRecovery.state)) return true; + if (object(action.evidence.automaticRecovery).replay === "blocked") return true; + return hasBlockingUnsafeArchiveHold(action, writerId); + }); +} + +function collectDurableSuccessorIds( + writerId: string, + coordinatorFailureDetail: Record | null | undefined, + actions: RecoveryActionRow[], +): string[] { + const ids = new Set(); + const coordinatorSuccessor = uuid(object(coordinatorFailureDetail).successorRunId); + if (coordinatorSuccessor && coordinatorSuccessor !== writerId) ids.add(coordinatorSuccessor); + for (const action of actions) { + if (action.status !== "resolved") continue; + const explicit = explicitContinuationSuccessorId(action, writerId); + if (explicit) ids.add(explicit); + const reconciled = reconciliationSuccessorId(action, writerId); + if (reconciled) ids.add(reconciled); + } + return [...ids]; +} export type RemoteWorkspaceWriter = { runId: string; agentId: string; issueId: string; issueIdentifier: string | null; lastActivityAt: Date; @@ -69,8 +131,9 @@ export async function readRemoteWorkspaceWriterHold(tx: Db, input: { runId: authority.writerRunId, agentId: prior.agentId, issueId: writerIssue.id, issueIdentifier: writerIssue.identifier, lastActivityAt: prior.lastOutputAt ?? prior.startedAt ?? prior.createdAt, ownerFenceHeld: prior.ownerFenceHeld === true, } }; - const leases = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, companyId), + const rawLeases = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, authority.writerRunId))); + const leases = await Promise.all(rawLeases.map(lease => resolveRemoteTerminationLease(tx, lease))); const bootstrap = object(prior?.executionRecovery); const pristinePreparation = !authority.location && !authority.snapshotId && prior?.status === "failed" && prior.runtimeMode === "legacy" && prior.nativeSessionId === null && prior.runnerInstanceId === null @@ -103,3 +166,106 @@ export async function readRemoteWorkspaceWriterHold(tx: Db, input: { } return { kind: "unattributed" }; } + +/** + * Abandons a dirty remote workspace epoch whose ended writer was already + * superseded by a recorded successor run, once that successor has also ended + * (or is itself reserving the workspace). Preserves every unsaved-files + * invariant: never touches a writer with an uncommitted accepted result, an + * open or active recovery hold, an unsettled no-replay hold, a running save, + * or a live controller/finalizer fence. Uses `abandonUnverifiedRemoteWorkspaceEpoch` + * so the old writer is fenced, its unverified root is retained unapplied, and + * the next writer restores the last committed snapshot into a new directory. + * The caller holds the workspace row lock. + */ +export async function releaseSupersededRemoteWorkspaceWriter(tx: WriterHoldTx, input: { + workspace: typeof executionWorkspaces.$inferSelect; + authority: RemoteWorkspaceAuthority; + callerRunId?: string | null; + wakeWaiters?: boolean; +}): Promise<{ workspace: typeof executionWorkspaces.$inferSelect; authority: RemoteWorkspaceAuthority } | null> { + const { workspace, authority } = input; + const runId = authority.writerRunId; + if (!runId || !authority.dirty || !authority.location || runId === input.callerRunId) return null; + const db = tx as Db; + const now = new Date(); + // Never wait on a writer run another transaction holds; that owner settles it. + const [writer] = await db.select({ + id: heartbeatRuns.id, status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt, + issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, + controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt, + runnerProfileJson: heartbeatRuns.runnerProfileJson, + contextIssueId: sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId')`, + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, workspace.companyId), eq(heartbeatRuns.id, runId))) + .for("update", { skipLocked: true }); + if (!writer || !TERMINAL_RUN_STATUSES.includes(writer.status) || !writer.finishedAt + || adapterExecutionControls.has(writer.id) + || (writer.controllerLeaseExpiresAt && writer.controllerLeaseExpiresAt > now)) return null; + const remoteProfile = writer.runnerProfileJson?.remoteWorkspace; + if (remoteProfile !== undefined && remoteProfile !== null) { + const parsed = remoteWorkspaceRunReferenceSchema.safeParse(remoteProfile); + if (!parsed.success || parsed.data.state !== "prepared" + || parsed.data.workspaceId !== workspace.id || parsed.data.epoch !== authority.epoch) return null; + } + const [saving] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and( + eq(workspaceOperations.companyId, workspace.companyId), eq(workspaceOperations.executionWorkspaceId, workspace.id), + eq(workspaceOperations.phase, "remote_workspace_snapshot"), inArray(workspaceOperations.status, ["running", "pending"]), + sql`${workspaceOperations.metadata}->>'epoch' = ${String(authority.epoch)}`)).limit(1); + if (saving) return null; + const [coordinator] = await db.select({ + phase: nativeRunFinalizations.phase, resultId: nativeRunFinalizations.resultId, + leaseOwner: nativeRunFinalizations.leaseOwner, leaseExpiresAt: nativeRunFinalizations.leaseExpiresAt, + failureDetail: nativeRunFinalizations.failureDetail, + }).from(nativeRunFinalizations).where(and( + eq(nativeRunFinalizations.companyId, workspace.companyId), eq(nativeRunFinalizations.runId, writer.id))); + if (coordinator?.leaseOwner && (!coordinator.leaseExpiresAt || coordinator.leaseExpiresAt > now)) return null; + // An uncommitted accepted result still owes its unsaved files to export recovery. + if (coordinator?.resultId && coordinator.phase !== "committed") return null; + + const writerIssueId = uuid(writer.nativeIssueId ?? writer.issueId ?? writer.contextIssueId); + if (!writerIssueId) return null; + const actions = await db.select({ + status: issueRecoveryActions.status, evidence: issueRecoveryActions.evidence, + }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, workspace.companyId), eq(issueRecoveryActions.sourceIssueId, writerIssueId), + or(sql`${issueRecoveryActions.evidence}->>'runId' = ${writer.id}`, + sql`${issueRecoveryActions.evidence}->>'sourceRunId' = ${writer.id}`))); + if (writerHasBlockingHold(actions, writer.id)) return null; + + const successorIds = collectDurableSuccessorIds(writer.id, coordinator?.failureDetail, actions); + if (successorIds.length === 0) return null; + + const successorRows = await db.select({ + id: heartbeatRuns.id, status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt, + controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt, + }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, workspace.companyId), inArray(heartbeatRuns.id, successorIds))); + const successorsById = new Map(successorRows.map(row => [row.id, row])); + for (const successorId of successorIds) { + if (successorId === input.callerRunId) continue; + const successor = successorsById.get(successorId); + if (!successor || !TERMINAL_RUN_STATUSES.includes(successor.status) || !successor.finishedAt + || adapterExecutionControls.has(successor.id) + || (successor.controllerLeaseExpiresAt && successor.controllerLeaseExpiresAt > now)) return null; + } + + // Register terminal-workspace work intent BEFORE modifying the workspace row + // (rules/sleep-aware-background-work.mdc). + await notifyTerminalWorkspaceWork(db, `workspace:${workspace.id}`); + let abandoned: Awaited>; + try { + abandoned = await abandonUnverifiedRemoteWorkspaceEpoch(tx as Transaction, { + companyId: workspace.companyId, workspaceId: workspace.id, runId: writer.id, + epoch: authority.epoch, snapshotId: authority.snapshotId, location: authority.location, + }); + } catch (error) { + if (error instanceof Error && error.message === "remote_workspace_authority_changed") return null; + throw error; + } + if (input.wakeWaiters !== false) { + await wakeWorkspaceBusyWaitersInTx(db, { + companyId: workspace.companyId, runId: writer.id, contextSnapshot: null, scheduledRetryReason: null, now, + }); + } + return abandoned; +} diff --git a/server/src/services/remote-workspaces.ts b/server/src/services/remote-workspaces.ts index a0477054e61..17a1b411cab 100644 --- a/server/src/services/remote-workspaces.ts +++ b/server/src/services/remote-workspaces.ts @@ -27,7 +27,7 @@ import { logger } from "../middleware/logger.js"; import { createGitRemoteAuthProvider } from "./git-credentials.js"; import { notifyCancelledWorkspacePreservation } from "./cancelled-workspace-preservation-notifications.js"; import { assertExecutionWorkspaceRecordAccess, assertTaskWorkspaceExecutionAccess } from "./task-workspace-access.js"; -import { readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, type RemoteWorkspaceWriter } from "./remote-workspace-writer-hold.js"; +import { readRemoteWorkspaceWriterHold, releaseSupersededRemoteWorkspaceWriter, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, type RemoteWorkspaceWriter } from "./remote-workspace-writer-hold.js"; import { persistActivity } from "./activity-log.js"; import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { @@ -270,8 +270,12 @@ export async function reserveRemoteWorkspace(input: { } // An ended writer that provably changed nothing hands the workspace on // at its saved version, so this run is admitted instead of waiting. + // Likewise, a dirty epoch whose ended writer was already superseded by a + // finished successor is abandoned cleanly so the next run restores the + // last committed snapshot into a new root. if (authority.dirty && authority.writerRunId && authority.writerRunId !== input.runId) { - const released = await releaseUnchangedRemoteWorkspaceWriter(tx, { workspace: existing, authority, wakeWaiters: false }); + const released = await releaseUnchangedRemoteWorkspaceWriter(tx, { workspace: existing, authority, wakeWaiters: false }) + ?? await releaseSupersededRemoteWorkspaceWriter(tx, { workspace: existing, authority, callerRunId: input.runId, wakeWaiters: false }); if (released) ({ workspace: existing, authority } = released); } const hold = await readRemoteWorkspaceWriterHold(tx as unknown as Db, { companyId: input.companyId, authority, runId: input.runId });