fix(recovery): stop retrying a setup failure behind a refused workspace writer hold (#23446)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A run can fail setup with "The workspace still has an unfinished
writer or save operation." when the task's own remote workspace is still
held by an earlier writer run that never finished saving.
> - #22103 stopped the assigned-work sweep from looping a board
escalation behind such a hold. Staging still showed these failures in
pairs.
> - Each pair is one continuation (a sweep continuation, a delivered
fresh continuation, or a comment that reopened the task) whose run fails
on the hold, followed by an immediate bounded `transient_failure` retry
from the failure path, which fails the same way.
> - `scheduleBoundedRetryForRun` never reads the workspace hold before
it schedules that retry.
> - This pull request makes the retry scheduler, the assigned-work sweep
and stranded recovery agree: while the hold refuses a start, nobody
starts another run; the task goes to the board-owned stranded hold,
which the sweep (#22103) and the released-writer pass (#21221) continue
once the writer releases.
> - The benefit is one failed run per held workspace instead of repeated
pairs, and no task left in progress with nothing moving it.

## Linked Issues or Issue Description

Refs #22103
Refs #21221
Refs #21394
Refs #23051

**What happened?**
On staging, tasks whose workspace writer hold stayed refused produced
failed runs in pairs, seconds apart:
- A continuation run failed setup with the writer-pending message
(`setup_failed`, `executionRecovery: { kind: "bootstrap",
providerWorkStarted: false }`).
- The failure path then scheduled a bounded `transient_failure` retry of
that run (`scheduledRetryAttempt: 1`), which failed setup on the same
hold.
One pair started from a delivered fresh continuation (`source:
execution.reconciled`), another from an assigned-work sweep continuation
of a task a comment had reopened (`source:
issue.assigned_work_invariant`, `assignedWorkViolation: retry_offered`).

**Expected behavior**
While the task's workspace writer hold refuses a start, no retry or
continuation is started. The task is escalated once to the board-owned
stranded hold and continued once after the hold releases.

**Steps to reproduce**
1. Bind an in-progress task to an execution workspace whose remote
workspace writer is an ended run with dirty, unsaved state (the hold
refuses a start).
2. Fail the task's latest run with `setup_failed` and the writer-pending
message, before provider work, as an assigned-work continuation.
3. Call `scheduleBoundedRetryForRun` for that run: before this change it
schedules a retry.
4. Run the assigned-work check: before this change it continues the task
(`retry_offered`).
5. Run stranded recovery: before this change it skips the task because
the sweep owns the failed continuation, so with the sweep held back the
task would have no path.

**Paperclip version or commit**
`master` at ab2183aae.

**Deployment mode**
Hosted (cloud sandbox workspaces).

## What Changed

- `server/src/services/remote-workspace-writer-hold.ts`: add
`failedRunWorkspaceHoldRefusesStart(db, run)`: true when the run failed
setup with the writer-pending message and its task's workspace hold
still refuses a start (`remoteWorkspaceHoldRefusesStart`). Export
`REMOTE_WORKSPACE_WRITER_PENDING_CODE`, the code reservation already
uses.
- `server/src/services/heartbeat/retries.ts`:
`scheduleBoundedRetryForRun` returns `not_scheduled` with `errorCode:
remote_workspace_writer_pending` for such a run. Other runs do not read
the database for this check.
- `server/src/services/recovery/assigned-work-sweep.ts` (+
`assigned-work-invariant.ts` fact): the hold read from #22103 now also
covers a task whose latest run failed on the hold. For an open task with
a `retry_offered` or `no_pending_path` violation behind a refused hold,
the sweep reports `left_to_hold_owner` instead of continuing it,
including in the locked re-check.
- `server/src/services/recovery/service.ts`: stranded continuation
recovery does not count such a failed run as owned by the sweep, so it
escalates the task to the board hold instead of skipping it.
- Tests: `retries.test.ts` (refused hold: no retry and no successor;
released hold: retry scheduled) and `released-writer-escalation.test.ts`
(reopened task behind the refused hold: sweep leaves it, stranded
recovery escalates with no successor run, and the released-writer pass
continues it once after release).

## Verification

- `cd server && npx vitest run src/services/heartbeat/retries.test.ts
src/__tests__/released-writer-escalation.test.ts
src/__tests__/assigned-work-invariant.test.ts
src/services/heartbeat/recovery.test.ts`: 210/210 pass.
- The 19 other server test files that call
`reconcileStrandedAssignedIssues` pass on this head (18 files: 1,350
passed, 19 skipped; `workspace-recovery-admission.test.ts`: 149/149).
- Each part is needed. With the scheduler check removed, the retries
test schedules a retry (`scheduled`, expected `not_scheduled`). With the
stranded ownership change removed, the escalation test leaves the task
in progress (expected `blocked`). With the sweep change removed, the
sweep continues the task (expected `left_to_hold_owner`).
- I could not run the full server `tsc` locally (the sandbox's memory
limit stops it). CI must confirm typecheck, build and the full suite.

## Risks

- Low to medium. The new reads happen only for runs that failed setup
with the writer-pending message: one join from the task to its execution
workspace and one hold read.
- A task behind a long refused hold now waits on the board-owned
stranded hold instead of failing repeatedly. The sweep and the
released-writer pass already continue that hold when the writer
releases.
- If the hold is already free when these paths look, behavior is
unchanged: the retry is scheduled and the sweep continues the task.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, git, GitHub CLI) and code execution.

## 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
- [ ] I have updated relevant documentation to reflect my changes (not
needed: no command or documented behavior 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 20:41:33 -08:00
1 parent ab2183aaed
commit 29a45b42db
7 files changed
+107 -12

No files matched your search

@@ -201,6 +201,35 @@ describePostgres("a task stranded behind its own workspace's ended writer", () =
expect(wakesFor(f.task.id)).toHaveLength(1);
}, 60_000);
it("a task reopened behind the refused hold gets no retry or sweep continuation and returns to this pass", async () => {
const f = await seedStrandedTask({ laterDecision: null });
await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));
const [latest] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.issueId, f.task.id),
eq(heartbeatRuns.errorCode, "setup_failed"))).orderBy(sql`${heartbeatRuns.finishedAt} desc`).limit(1);
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.task.id, source: "issue.assigned_work_invariant",
wakeReason: "issue_continuation_needed", previousRunId: randomUUID() } }).where(eq(heartbeatRuns.id, latest!.id));
await db.update(issues).set({ status: "in_progress", blockedTransitionAt: null, updatedAt: new Date(Date.now() - 3_600_000) })
.where(eq(issues.id, f.task.id));
const successors = async () => (await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.issueId, f.task.id), sql`${heartbeatRuns.status} in ('queued', 'scheduled_retry', 'running')`))).length;
expect(await recoveryService(db, { enqueueWakeup: enqueueWakeup as never }).assignedWork
.checkIssue({ companyId: f.companyId, issueId: f.task.id })).toMatchObject({ outcome: "left_to_hold_owner" });
expect(wakesFor(f.task.id)).toEqual([]);
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.task.id, skipRelatedRecovery: true });
expect(await successors()).toBe(0);
expect(await issue(f.task.id)).toMatchObject({ status: "blocked" });
const [escalation] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, f.task.id),
eq(issueRecoveryActions.status, "active")));
expect(escalation).toMatchObject({ kind: "stranded_assigned_issue", ownerType: "board" });
await f.releaseWriter();
expect(await scheduledRecoveryPass(f.companyId)).toBe(true);
expect(await issue(f.task.id)).toMatchObject({ status: "todo" });
expect(wakesFor(f.task.id)).toHaveLength(1);
}, 60_000);
it("delivers a wake that a crash left pending, and keeps backing off a refused one", async () => {
const f = await seedStrandedTask({ laterDecision: null });
await f.releaseWriter();
+30 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import type { Db } from "@paperclipai/db";
import { activityLog, agents, agentWakeupRequests, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRunEvents, heartbeatRuns, issues, projects, projectWorkspaces } from "@paperclipai/db";
import { activityLog, agents, agentWakeupRequests, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, issues, projects, projectWorkspaces } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
@@ -12,6 +12,7 @@ import * as legacy from "../heartbeat.js";
import { createHeartbeatRunState } from "./run-state.js";
import { pendingCaseHandoffForRun } from "./case-handoff-lifecycle.js";
import * as extracted from "./retries.js";
import { REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE } from "../remote-workspace-writer-hold.js";
import type { HeartbeatRetryDependencies } from "./retries.js";
type Run = typeof heartbeatRuns.$inferSelect;
@@ -343,6 +344,34 @@ describePostgres("heartbeat retry module database wiring", () => {
}
});
it("does not retry a setup failure while its workspace's writer hold refuses a start, and retries once it is free", async () => {
const { run, agent, issue, companyId } = await fixture();
const [writer] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "issue", issueId: issue.id,
status: "failed", errorCode: "native_finalization_superseded", finishedAt: new Date(now.getTime() - 9 * 3_600_000),
contextSnapshot: { issueId: issue.id } }).returning();
const remoteWorkspace = { schema: "paperclip.remote-workspace.v1", epoch: 3, snapshotId: randomUUID(), source: { kind: "empty" },
writerRunId: writer!.id, dirty: true, location: null };
const [workspace] = await db.insert(executionWorkspaces).values({ companyId, sourceIssueId: issue.id, name: "Task workspace",
mode: "isolated_workspace", strategyType: "project_primary", status: "active", providerType: "cloud_sandbox",
metadata: { remoteWorkspace } }).returning();
try {
await db.update(issues).set({ executionWorkspaceId: workspace!.id }).where(eq(issues.id, issue.id));
const [failed] = await db.update(heartbeatRuns).set({ errorCode: "setup_failed", error: REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE })
.where(eq(heartbeatRuns.id, run.id)).returning();
const { retries } = boundRetries();
expect(await retries.scheduleBoundedRetryForRun(failed!, agent, { now }))
.toMatchObject({ outcome: "not_scheduled", errorCode: "remote_workspace_writer_pending", issueId: issue.id });
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, run.id))).toEqual([]);
await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { ...remoteWorkspace, epoch: 4, writerRunId: null, dirty: false } } })
.where(eq(executionWorkspaces.id, workspace!.id));
expect(await retries.scheduleBoundedRetryForRun(failed!, agent, { now })).toMatchObject({ outcome: "scheduled" });
} finally {
await db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, issue.id));
await db.delete(executionWorkspaces).where(eq(executionWorkspaces.companyId, companyId));
}
});
// A run that could not retire its predecessor re-queues in the uncharged lane
// with the answered interaction's own wake, so the retry still carries it.
it("keeps an answered interaction in an uncharged interrupted-preparation retry that keeps its wake", async () => {
+6 -1
View File
@@ -1,5 +1,6 @@
import { hasPendingRunCleanup } from "../execution-blocker.js";
import { runOwnerFenceHeldSql } from "../remote-workspace-writer-hold.js";
import { failedRunWorkspaceHoldRefusesStart, REMOTE_WORKSPACE_WRITER_PENDING_CODE, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE,
runOwnerFenceHeldSql } from "../remote-workspace-writer-hold.js";
import { AGENT_DIRECTORY_BUSY_ERROR_CODE, AGENT_DIRECTORY_BUSY_MAX_DEFERRALS, AGENT_DIRECTORY_BUSY_RETRY_REASON, AGENT_DIRECTORY_BUSY_RETRY_WAKE_REASON, agentDirectoryBusyRetryDelayMs, type AgentDirectoryPreparationDeferral } from "./agent-directory-busy.js";
import { isInterruptedNativePreparation } from "../cancelled-native-startup.js";
import { isPreDispatchExecutionWaitVerified } from "../pre-dispatch-execution-wait.js";
@@ -541,6 +542,10 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen
}
if (await hasCaseHandoffForRun(run)) return { outcome: "not_scheduled" as const,
reason: "The durable case handoff owns successor work.", issueId: readNonEmptyString(run.contextSnapshot?.issueId) };
if (await failedRunWorkspaceHoldRefusesStart(db, run, (opts?.now ?? new Date()).getTime())) {
return { outcome: "not_scheduled" as const, reason: REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE,
errorCode: REMOTE_WORKSPACE_WRITER_PENDING_CODE, issueId: readNonEmptyString(run.contextSnapshot?.issueId) };
}
if (["openai_dot", "muse"].includes(String(parseObject(agent.adapterConfig).provider))
|| ["openai_dot", "muse"].includes(String(parseObject(parseObject(parseObject(run.runnerProfileJson).nativeExecutionInput).provider).kind))) {
return { outcome: "not_scheduled" as const, reason: "Dot external execution must be reconciled before a new assignment; Paperclip cannot confirm its external stop.", issueId: readNonEmptyString(run.contextSnapshot?.issueId) };
@@ -179,6 +179,7 @@ export type AssignedWorkFacts = {
/** A saved-work recovery the recovery queue still owes this task: the
* task's saved files must be recovered before any run can start. */
savedWorkRecovery?: SavedWorkRecoveryFact | null;
workspaceWriterRefused?: boolean;
agent: { status: string; invokable: boolean; updatedAt?: Date } | null;
companyPaused: boolean;
pauseHold: boolean;
@@ -102,7 +102,7 @@ function chatFailedBeforeProviderWork(latest: RunRow | null, issue: Pick<IssueRo
return isSetupFailureBeforeProviderWork({ errorCode: latest.errorCode, resultJson: latest.resultJson });
}
type RunRow = Pick<typeof heartbeatRuns.$inferSelect, "id" | "status" | "agentId" | "runtimeMode" | "errorCode" | "finishedAt"
type RunRow = Pick<typeof heartbeatRuns.$inferSelect, "id" | "status" | "agentId" | "runtimeMode" | "errorCode" | "error" | "finishedAt"
| "scheduledRetryAt" | "controllerBootId" | "controllerLeaseExpiresAt" | "controllerProcess" | "resultJson"> & { issueId: string };
export type AssignedWorkDeps = {
@@ -171,6 +171,11 @@ function createPassLog() {
};
}
function leftToWorkspaceWriterHold(status: string, facts: AssignedWorkFacts, verdict: AssignedWorkVerdict): boolean {
return status !== "blocked" && facts.workspaceWriterRefused === true && verdict.kind === "violation"
&& (verdict.reason === "retry_offered" || verdict.reason === "no_pending_path");
}
export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
const now = () => deps.now?.() ?? new Date();
const proveOwner = deps.proveOwner ?? ((stamp: LocalOwnerStamp) => proveOwnerGone(stamp, { ...currentProcessProbe(), readOnly: true }));
@@ -211,7 +216,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
const runIssue = sql<string>`${heartbeatRuns.contextSnapshot}->>'issueId'`;
const runColumns = {
issueId: runIssue, id: heartbeatRuns.id, status: heartbeatRuns.status, agentId: heartbeatRuns.agentId,
runtimeMode: heartbeatRuns.runtimeMode, errorCode: heartbeatRuns.errorCode, finishedAt: heartbeatRuns.finishedAt,
runtimeMode: heartbeatRuns.runtimeMode, errorCode: heartbeatRuns.errorCode, error: heartbeatRuns.error, finishedAt: heartbeatRuns.finishedAt,
scheduledRetryAt: heartbeatRuns.scheduledRetryAt, controllerBootId: heartbeatRuns.controllerBootId,
controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt, controllerProcess: heartbeatRuns.controllerProcess,
resultJson: sql<Record<string, unknown> | null>`jsonb_build_object('cancelledByActorType', ${heartbeatRuns.resultJson}->'cancelledByActorType')`,
@@ -231,7 +236,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
from unnest(${idParam}) as requested(id)
cross join lateral (
select r.id, r.status, r.agent_id as "agentId", r.runtime_mode as "runtimeMode", r.error_code as "errorCode",
r.finished_at as "finishedAt", r.scheduled_retry_at as "scheduledRetryAt",
r.error, r.finished_at as "finishedAt", r.scheduled_retry_at as "scheduledRetryAt",
r.controller_boot_id as "controllerBootId", r.controller_lease_expires_at as "controllerLeaseExpiresAt",
r.controller_process as "controllerProcess",
jsonb_build_object('cancelledByActorType', r.result_json->'cancelledByActorType',
@@ -341,10 +346,13 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
executionRecovery: sql<StrandedHoldRun["executionRecovery"]>`${heartbeatRuns.resultJson}->'executionRecovery'` })
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, strandedRunIds))) : [])
.map(({ id, ...run }) => [id, run]));
const writerHeldIssueIds = [...actionMap.entries()].filter(([, action]) => {
const run = strandedRuns.get(String(action.evidence?.latestRunId ?? ""));
return run?.errorCode === "setup_failed" && run.error === REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE;
}).map(([issueId]) => issueId);
const writerPending = (run: { errorCode: string | null; error: string | null } | null | undefined) =>
run?.errorCode === "setup_failed" && run.error === REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE;
const writerHeldIssueIds = [...new Set([
...[...actionMap.entries()].filter(([, action]) => writerPending(strandedRuns.get(String(action.evidence?.latestRunId ?? ""))))
.map(([issueId]) => issueId),
...rowsOf<RunRow>(latestRuns).filter(run => writerPending(run)).map(run => run.issueId),
])];
const writerRefusedIssueIds = new Set<string>();
if (writerHeldIssueIds.length) {
const bound = await database.select({ issueId: issues.id, metadata: executionWorkspaces.metadata }).from(issues)
@@ -496,6 +504,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
budgetStop: companyBudget || agent?.pauseReason === "budget" || agent?.pauseReason === "budget_exceeded",
blockedBy: issue.status !== "blocked" ? null : attributeBlock(blockedEntry, issue.assigneeAgentId),
savedWorkRecovery: savedWorkByIssue.get(issue.id) ?? null,
workspaceWriterRefused: writerRefusedIssueIds.has(issue.id),
});
}
return result;
@@ -675,6 +684,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
}
// A stalled native run is ended by native recovery, not here: the sweep
// builds no second ender. It stays a counted violation in the report.
if (leftToWorkspaceWriterHold(issue.status, facts, verdict)) return { verdict, outcome: "left_to_hold_owner", retryAt: null };
if (verdict.reason === "native_run_stalled") return { verdict, outcome: "left_to_native_recovery", retryAt: null };
if (verdict.reason === "run_owner_gone") {
// Hand the run to heartbeat's lost-process settle path; its own failure
@@ -885,7 +895,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
const verdict = evaluateAssignedWork(fresh, at);
let stalledFence: Claimed["stalledFence"] = null;
if (verdict.kind !== "violation" || verdict.stale || verdict.reason === "run_owner_gone" || verdict.reason === "native_run_stalled"
|| (current.status === "blocked" && fresh.activeRecoveryAction && !fresh.activeRecoveryAction.continuedBySweep)) return { kind: "changed" as const };
|| (current.status === "blocked" && fresh.activeRecoveryAction && !fresh.activeRecoveryAction.continuedBySweep)
|| leftToWorkspaceWriterHold(current.status, fresh, verdict)) return { kind: "changed" as const };
if (verdict.reason === "queued_run_stalled") {
const stall = fresh.activeRuns.find(run => run.id === verdict.runId)?.queuedStall;
const fence = fences.find(row => row.id === verdict.runId);
+3 -1
View File
@@ -1,5 +1,6 @@
import { wakeWaitersOfStalledIssues, type BlockerStallWakeup } from "./blocker-stall-wakeups.js";
import { wakeReadyPoolDependentsForBlocker } from "../headless-task-queue.js";
import { failedRunWorkspaceHoldRefusesStart } from "../remote-workspace-writer-hold.js";
import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "../antigravity-swarm-refusal.js";
import { DEPENDENCY_WAKE_REPEATED_FAILURE_STREAK, readDependencyWakeCircuit } from "./dependency-wake-circuit-breaker.js";
import { INTERACTION_DELIVERY_DENIED, isInteractionDeliveryDeniedRun } from "../agent-interaction-delivery.js";
@@ -6116,7 +6117,8 @@ export function recoveryService(
// escalates it as before.
preparationRetry = latestRun!.agentId === agentId
&& await failedRunOwnsPreparationRetry(issue.companyId, latestRun!.id);
const sweepOwnsFailure = !preparationRetry && assignedWorkSweepOwnsFailedRun(issue, latestRun, agentId);
const sweepOwnsFailure = !preparationRetry && assignedWorkSweepOwnsFailedRun(issue, latestRun, agentId)
&& !(await failedRunWorkspaceHoldRefusesStart(db, { ...latestRun!, companyId: issue.companyId }));
if (classification.kind === "non_retryable" && sweepOwnsFailure) {
result.skipped += 1;
continue;
@@ -1,7 +1,7 @@
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 { readRemoteWorkspaceAuthority, 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";
@@ -86,6 +86,7 @@ export function runOwnerFenceHeldSql() {
/** The setup error a run gets when reservation refuses a remote workspace hold. */
export const REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE = "The workspace still has an unfinished writer or save operation.";
export const REMOTE_WORKSPACE_WRITER_PENDING_CODE = "remote_workspace_writer_pending";
type RemoteWorkspaceWriterHold = Awaited<ReturnType<typeof readRemoteWorkspaceWriterHold>>;
@@ -167,6 +168,23 @@ export async function readRemoteWorkspaceWriterHold(tx: Db, input: {
return { kind: "unattributed" };
}
export async function failedRunWorkspaceHoldRefusesStart(tx: Db, run: {
id: string; companyId: string; errorCode: string | null; error: string | null;
issueId?: string | null; contextSnapshot?: unknown;
}, now = Date.now()): Promise<boolean> {
if (run.errorCode !== "setup_failed" || run.error !== REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE) return false;
const snapshot = object(run.contextSnapshot);
const issueId = uuid(run.issueId) ?? uuid(snapshot.issueId) ?? uuid(snapshot.taskId);
if (!issueId) return false;
const [row] = await tx.select({ metadata: executionWorkspaces.metadata }).from(issues)
.innerJoin(executionWorkspaces, and(eq(executionWorkspaces.companyId, issues.companyId),
eq(executionWorkspaces.id, issues.executionWorkspaceId)))
.where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId)));
const authority = row ? readRemoteWorkspaceAuthority(row.metadata as Record<string, unknown> | null) : null;
if (!authority) return false;
return remoteWorkspaceHoldRefusesStart(await readRemoteWorkspaceWriterHold(tx, { companyId: run.companyId, authority, runId: run.id }), now);
}
/**
* Abandons a dirty remote workspace epoch whose ended writer was already
* superseded by a recorded successor run, once that successor has also ended