mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 15:52:45 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents in a `sandbox` environment run each task in a paid remote
sandbox that an environment lease tracks
> - When a run stops, the control plane must release that lease, and
terminating an agent waits until every lease of the agent is released
> - In a load test, a run stopped after its sandbox was ready but before
its runner started never released its lease, so the sandbox kept running
and the agent stayed in "terminating" forever
> - In the same test, terminating an agent whose failed run had a
scheduled same-run retry waited about 18 minutes, until the stale retry
time
> - This pull request makes lease release finish for every stop window,
records any release that must wait with a retry time, adds a hint-driven
safety net, and makes termination cancel a pending native retry at once
> - The benefit is that a stopped run never leaves a paid sandbox
running, and agent termination finishes in seconds without manual repair
## Linked Issues or Issue Description
**What happened?**
A load test with ten OpenCode agents in a `sandbox` environment stopped
its agents mid-run (pause, then terminate). Two defects appeared.
1. A run cancelled while it selected its provider pack (after the
sandbox was acquired and the workspace was prepared, before the runner
started) kept its environment lease `active` for more than 40 minutes.
The agent stayed in lifecycle `terminating`. The lifecycle worker
retried every pass and wrote `updatedAt` each time with no recorded
reason. Delete returned 409 "Complete termination before deleting the
agent".
2. A failed native run with a scheduled bootstrap retry kept its lease
until the stale retry time. Agent termination took about 18 minutes. The
run still showed "retry_scheduled" after the agent was terminated.
**Expected behavior**
A stopped run releases its sandbox lease within seconds. If release must
wait, the wait has a recorded reason and retry time, and a background
pass finishes it. Terminating an agent cancels a pending retry, releases
its lease, and reaches `terminated` promptly.
**Steps to reproduce**
1. Start a native run in a `sandbox` environment.
2. Stop it after the sandbox is acquired and the workspace is prepared,
before the runner starts.
3. Pause and then terminate the agent.
4. See that the lease stays `active` and the agent stays `terminating`.
**Paperclip version or commit**
Reproduced on `master` at 62033b9994 (load test build 2026.1106.0+2564).
**Relevant logs or output**
Root causes found in the code:
- `releaseEnvironmentLeasesForRun` returned with no record when
workspace retention refused a cancelled run. The refusal was permanent
when the run's native finalization owner had expired but was not
cleared. The owner is cleared only after `agentExecutionsHaveStopped`
sees every lease released, so the two waited on each other.
- `releaseRunLeases` silently skipped a lease whose prepared native
workspace was still "pending export", even for a run that never started
a runner and so never changed those files.
- The destroy path deferred on any busy warm session in the same
environment, also with no record.
- `stopInvocationsForAgents` returned on the first run that was still
live, so it did not release the leases of the other runs of the agent.
- The agent stop cancelled only `queued`, `running` and
`scheduled_retry` runs. A failed native run with a pending same-run
retry kept its lease until that retry fired.
- The lifecycle worker deferred a pending host step by 2 seconds every
pass, with no reason and no backoff.
## What Changed
- `releaseEnvironmentLeasesForRun` (`run-control.ts`):
- A native run with no runner launch evidence (no
`native.process_start_requested`, no runner event, no process id) skips
workspace retention and warm-session closing. No runner process exists
to fence, and no work ran against the prepared files.
- When retention is refused only because the run's native finalization
owner lease has expired, the release clears that expired owner
(compare-and-set on the exact expired owner of a cancelled run with no
result) and retries retention once. A recorded recovery then stops and
retains the sandbox, so the files stay recoverable.
- Every release that cannot finish now records
`metadata.releaseDeferral` (`reason`, `attempts`, `retryAt`,
disposition) on the active lease and publishes an `orphan-active-leases`
hint. The retry time backs off from 30 seconds to 15 minutes, then
retries hourly without end. The record keeps `failingSince` and the last
reason. A new Stop or terminate operation, or a server restart, triggers
an immediate attempt.
- `nativeWorkspaceExportPendingForLease` treats a cancelled run with no
runner launch evidence as owing no export.
- Safety net: `sweepOrphanedActiveLeases` (the existing hint- and
deadline-driven orphan-lease work) now retries the run's own release for
a due deferral or for a cancelled native run, after the native owner
lease has expired. The orphan-lease loader uses the stored `retryAt` as
the due time. No new timer or poller.
- Agent stop:
- It cancels a failed native run that has a pending same-run retry (or
an interrupted cancellation of one), through the existing
retry-cancellation path. A pause stamps `pauseStop` on those runs too,
so a budget resume can continue them.
- It releases the leases of every terminal run, and it skips a lease
whose deferral is not yet due.
- `agentInvocationStopBlocker` and `agentExecutionStopBlocker` return
why the stop must still wait.
- Lifecycle worker: a pending host or plugin step records
`pendingReason` and `pendingPasses` on the operation, and its retry
backs off from 2 seconds to a 60 second cap. When a release leaves a run
with no unsettled lease, the stopping agent's saved retry time is
cleared and the lifecycle queue is notified, so Pause or Terminate
finishes on the next pass.
- Cancelled-workspace preservation: a stopped run that never started a
runner has its prepared reference moved to
`nativeWorkspaceSyncReleasedUnchanged` when its lease is released, so
the preservation worker no longer selects it. The worker records the
same settlement itself for older runs, and waits on a live owner's exact
lease expiry.
## Verification
- Red on `master`, green on this branch (embedded PostgreSQL, fake
plugin sandbox provider):
-
`server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts`:
agent pause then terminate, and board Stop, for each window between
sandbox acquire and runner attach (artifact discovery, pack select, pack
upload, runner launch, transport connect, session open). Each test
checks that the provider gets a stop or destroy call, the lease is
released, the run is cancelled, and the agent reaches `terminated`
within one extra worker pass. It also checks the orphan-lease safety net
for a leaked lease and a recorded deferral that the background pass
finishes when due.
-
`server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts`:
terminating an agent whose failed run has a bootstrap retry 17 minutes
away cancels the retry, releases the lease and reaches `terminated` at
once. The test covers an open task and a cancelled task.
-
`server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts`:
a host step that stays pending records its reason, and its retry delay
grows to a 60 second cap.
- Related suites pass: run-control, recovery, orphaned active lease
sweep, environment runtime, agent lifecycle, native workspace
preservation and recovery, held comment wake.
- `server` typecheck passes.
## Risks
- A cancelled native run with no launch evidence now gets its prepared
sandbox destroyed instead of kept. The proof is the same launch evidence
that restart recovery uses.
- A launched cancelled run whose retention owes nothing is stopped and
retained, as before. A retention that throws (lock or write error, or a
live owner) now keeps the lease active with a recorded reason and retry
time, instead of a silent skip.
- Release now clears an expired native finalization owner of a cancelled
run. An old controller whose lease already expired then fails its next
owner check and stops, which is the normal lease rule.
- On the first start after deploy, the orphan-lease work releases leases
already leaked by cancelled native runs.
- Task state after pause then terminate: the run-scoped stop keeps the
task status (an open task stays open, a cancelled task stays cancelled),
and a run that held prepared files gets the existing workspace recovery
record on its stopped sandbox. No new state is added.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (code search, shell, test runs).
## 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
- [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: Claude Opus 5.5 <noreply@anthropic.com>
357 lines
26 KiB
TypeScript
357 lines
26 KiB
TypeScript
import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema } from "@paperclipai/shared";
|
|
import type { CancelledWorkspacePreservationScope } from "../cancelled-workspace-preservation-notifications.js";
|
|
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
|
|
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
|
|
import { notifyExecutionRunWork } from "../execution-control-notifications.js";
|
|
import { and, asc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm";
|
|
import { environmentLeases, executionWorkspaces, heartbeatRuns, workspaceRestoreFailureCodesSql, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
|
|
import { recordRequiredWorkspaceRestoreFailure } from "../legacy-execution-recovery.js";
|
|
import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";
|
|
import { logActivity } from "../activity-log.js";
|
|
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
|
|
import { nativeRunNeverLaunchedRunner, settleUnchangedNativeWorkspace } from "../environment-lease-release-deferral.js";
|
|
import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js";
|
|
import { NativeWorkspaceFinalizationBusyError } from "./native-workspace-finalization-ownership.js";
|
|
import { hasAcknowledgedNativeRunStopRequest } from "../acknowledged-native-stop.js";
|
|
import { logger } from "../../middleware/logger.js";
|
|
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js";
|
|
import { preserveRemoteWorkspacePreparationFailure } from "./native-workspace-finalization-state.js";
|
|
import { pinFailedObservedWorkspace } from "./native-observed-workspace-preservation.js";
|
|
import { hasConfirmedSandboxStopAndRetain } from "../sandbox-stop-and-retain.js";
|
|
import { preparedRemoteWorkspaceSource } from "../remote-workspace-lifecycle.js";
|
|
import { releaseUnchangedRemoteWorkspaceWriterById } from "../remote-workspaces.js";
|
|
import { isSupersededWorkspaceExport, markSupersededWorkspaceExportHold } from "./native-superseded-workspace-export.js";
|
|
|
|
const reusableLeasePolicies = ["reuse_by_environment", "reuse_by_execution_workspace"];
|
|
|
|
/** The exact source the restore recorder can retain. A released reusable lease
|
|
* qualifies only with a confirmed stop-and-retain receipt and the remote
|
|
* workspace binding proof. Native-sync descriptors have no such proof here. */
|
|
async function cancelledWorkspaceSource(db: Db, run: Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "runnerProfileJson">) {
|
|
const leases = await db.select().from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
|
|
cancelledWorkspaceSourceLease(),
|
|
));
|
|
for (const lease of leases) {
|
|
if (lease.status !== "released" || lease.leasePolicy === "ephemeral") return lease;
|
|
if (run.runnerProfileJson?.nativeWorkspaceSync == null && hasConfirmedSandboxStopAndRetain(lease)
|
|
&& await preparedRemoteWorkspaceSource(db, lease)) return lease;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function workspaceRecoveryReference(profile: Record<string, unknown> | null | undefined) {
|
|
const remote = remoteWorkspaceRunReferenceSchema.safeParse(profile?.remoteWorkspace);
|
|
return readNativeWorkspaceSyncReference(profile?.nativeWorkspaceSync) ?? (remote.success ? remote.data : null);
|
|
}
|
|
|
|
export async function preserveTaskRemoteWorkspaceWriter(db: Db, companyId: string, issueId: string) {
|
|
const [bound] = await db.select({ id: executionWorkspaces.id, metadata: executionWorkspaces.metadata }).from(issues)
|
|
.innerJoin(executionWorkspaces, and(eq(executionWorkspaces.id, issues.executionWorkspaceId),
|
|
eq(executionWorkspaces.companyId, issues.companyId)))
|
|
.where(and(eq(issues.companyId, companyId), eq(issues.id, issueId)));
|
|
if (!bound) return;
|
|
const authority = readRemoteWorkspaceAuthority(bound.metadata);
|
|
if (!authority?.dirty || !authority.writerRunId) return;
|
|
const [run] = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId,
|
|
nativeIssueId: heartbeatRuns.nativeIssueId, issueId: heartbeatRuns.issueId,
|
|
contextSnapshot: sql<Record<string, unknown>>`jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId')`,
|
|
runnerProfileJson: sql<Record<string, unknown>>`jsonb_build_object('remoteWorkspace', ${heartbeatRuns.runnerProfileJson}->'remoteWorkspace',
|
|
'nativeWorkspaceSync', ${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync')`,
|
|
}).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, authority.writerRunId),
|
|
eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "failed"),
|
|
sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text,
|
|
${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`,
|
|
));
|
|
const reference = remoteWorkspaceRunReferenceSchema.safeParse(run?.runnerProfileJson.remoteWorkspace);
|
|
if (!run || run.runnerProfileJson.nativeWorkspaceSync != null || !reference.success || reference.data.state !== "prepared"
|
|
|| reference.data.workspaceId !== bound.id || reference.data.epoch !== authority.epoch) return;
|
|
try { return await preserveNativeFailedWorkspace(db, run); }
|
|
catch (error) { if (!(error instanceof NativeWorkspaceFinalizationBusyError)) throw error; }
|
|
}
|
|
|
|
/** A Stop during an accepted result's copy-back retries ends that copy-back.
|
|
* No finalization exports those files afterwards, so they are kept like the
|
|
* files of any other stopped run. Other accepted results keep their own export
|
|
* repair path. */
|
|
function stoppedAcceptedCopyback(coordinator: Pick<typeof nativeRunFinalizations.$inferSelect, "phase" | "failureCode">) {
|
|
return coordinator.phase === "terminal_failure" && coordinator.failureCode === "native_retry_cancelled";
|
|
}
|
|
|
|
export async function preserveNativeFailedWorkspace(db: Db, selected: Pick<typeof heartbeatRuns.$inferSelect,
|
|
"id" | "companyId" | "nativeIssueId" | "issueId" | "contextSnapshot" | "runnerProfileJson">,
|
|
options: { allowPreterminal?: boolean; requireCancelledStop?: boolean; restartRecovery?: NativeRestartRecoveryClaim } = {}) {
|
|
if (workspaceRecoveryReference(selected.runnerProfileJson)?.state !== "prepared") return;
|
|
const issueId = selected.nativeIssueId ?? selected.issueId ?? selected.contextSnapshot?.issueId;
|
|
if (typeof issueId !== "string") return;
|
|
return db.transaction(async tx => {
|
|
await tx.execute(sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`);
|
|
const [task] = await tx.select({ id: issues.id }).from(issues).where(and(
|
|
eq(issues.id, issueId), eq(issues.companyId, selected.companyId),
|
|
)).for("update");
|
|
if (!task) return;
|
|
const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and(
|
|
eq(nativeRunFinalizations.runId, selected.id), eq(nativeRunFinalizations.companyId, selected.companyId),
|
|
eq(nativeRunFinalizations.issueId, issueId),
|
|
)).for("update");
|
|
if (options.requireCancelledStop && coordinator?.phase !== "terminal_failure") return;
|
|
const claim = options.restartRecovery;
|
|
const reference = workspaceRecoveryReference(selected.runnerProfileJson)!;
|
|
const ownsClaim = Boolean(options.allowPreterminal && coordinator?.phase === "observed" && claim
|
|
&& claim.runId === selected.id && claim.leaseOwner === coordinator.leaseOwner
|
|
&& claim.controllerGeneration === coordinator.controllerGeneration && claim.providerAttempt === coordinator.attempt
|
|
&& coordinator.leaseExpiresAt && coordinator.leaseExpiresAt.getTime() > Date.now()
|
|
&& (claim.kind !== "reattach_remote_runner" || (claim.remote.kind !== "plugin_task" && claim.remote.providerLeaseId === reference.providerLeaseId
|
|
&& claim.remote.remoteCwd === reference.remoteCwd)));
|
|
if ((coordinator?.leaseOwner || (claim && coordinator?.phase === "observed")) && !ownsClaim) throw new NativeWorkspaceFinalizationBusyError();
|
|
// A result retired as superseded after its workspace export failed owes
|
|
// the same files as an exhausted copy-back: nothing else exports them, and
|
|
// its writer keeps the workspace until they are saved or set aside.
|
|
const supersededExport = Boolean(coordinator && isSupersededWorkspaceExport(coordinator));
|
|
const exhaustedAcceptedCopyback = Boolean(coordinator?.resultId && coordinator.phase === "terminal_failure"
|
|
&& coordinator.failureCode === "native_workspace_sync_out_retry_exhausted") || supersededExport;
|
|
if (!coordinator || (coordinator.resultId && !exhaustedAcceptedCopyback
|
|
&& !(options.requireCancelledStop && stoppedAcceptedCopyback(coordinator)))
|
|
|| !(options.allowPreterminal ? ["observed", "terminal_failure"] : ["terminal_failure"]).includes(coordinator.phase)) return;
|
|
const [run] = await tx.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, selected.id), eq(heartbeatRuns.companyId, selected.companyId),
|
|
)).for("update");
|
|
if (!run || run.runtimeMode !== "native" || (!options.allowPreterminal && run.status !== "failed")) return;
|
|
if (options.requireCancelledStop && (run.status !== "cancelled" || !hasAcknowledgedNativeRunStopRequest(run)
|
|
|| run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt.getTime() > Date.now())) return;
|
|
const currentReference = workspaceRecoveryReference(run.runnerProfileJson);
|
|
if (!currentReference || currentReference.state !== "prepared"
|
|
|| (claim?.kind === "reattach_remote_runner" && (claim.remote.kind === "plugin_task" || claim.remote.providerLeaseId !== currentReference.providerLeaseId
|
|
|| claim.remote.remoteCwd !== currentReference.remoteCwd))) return;
|
|
const [source] = await tx.select().from(environmentLeases).where(and(
|
|
eq(environmentLeases.id, currentReference.leaseId), eq(environmentLeases.companyId, run.companyId),
|
|
eq(environmentLeases.heartbeatRunId, run.id), eq(environmentLeases.providerLeaseId, currentReference.providerLeaseId),
|
|
)).limit(1);
|
|
if (!source || source.issueId !== issueId || source.metadata?.remoteCwd !== currentReference.remoteCwd
|
|
|| (source.executionWorkspaceId && source.executionWorkspaceId !== currentReference.workspaceId)) return;
|
|
if (exhaustedAcceptedCopyback) {
|
|
const remote = remoteWorkspaceRunReferenceSchema.safeParse(run.runnerProfileJson?.remoteWorkspace);
|
|
if (run.status !== "failed" || !run.finishedAt || !run.completionContractId
|
|
|| run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt.getTime() > Date.now()
|
|
|| run.runnerProfileJson?.nativeWorkspaceSync != null || !remote.success || remote.data.state !== "prepared"
|
|
|| !hasConfirmedSandboxStopAndRetain(source)
|
|
|| !await preparedRemoteWorkspaceSource(tx as unknown as Db, source)) return;
|
|
const [accepted] = await tx.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
|
|
eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.issueId, issueId),
|
|
eq(nativeRunResults.runId, run.id), eq(nativeRunResults.id, coordinator.resultId!),
|
|
eq(nativeRunResults.completionContractId, run.completionContractId), eq(nativeRunResults.schemaStatus, "accepted"),
|
|
)).limit(1);
|
|
if (!accepted) return;
|
|
}
|
|
// A run that ended without changing its files has nothing to keep: its
|
|
// workspace is handed on at the saved version it started from.
|
|
if (!exhaustedAcceptedCopyback && !coordinator.resultId && coordinator.phase === "terminal_failure"
|
|
&& run.runnerProfileJson?.nativeWorkspaceSync == null
|
|
&& await releaseUnchangedRemoteWorkspaceWriterById(tx, { companyId: run.companyId,
|
|
workspaceId: currentReference.workspaceId, runId: run.id })) return;
|
|
// A stopped reusable sandbox is retained only with its exact stop receipt
|
|
// while the workspace is still bound to this writer. Otherwise record nothing.
|
|
if (!exhaustedAcceptedCopyback && source.status !== "active" && reusableLeasePolicies.includes(source.leasePolicy) && (!hasConfirmedSandboxStopAndRetain(source)
|
|
|| !await preparedRemoteWorkspaceSource(tx as unknown as Db, source))) return;
|
|
// Ownership settlement still applies to workspace-less external sessions.
|
|
// Their Runner descriptor is not evidence that user files need exporting.
|
|
const retainFiles = !nativeRunHasNoWorkspaceAccess(run);
|
|
const alreadyRetained = hasRequiredWorkspaceRecovery(run.resultJson);
|
|
if (retainFiles && !alreadyRetained) await notifyDeliveryWork(tx, DELIVERY_QUEUES.workspaceRecovery);
|
|
let retained = !retainFiles || alreadyRetained ? run : await recordRequiredWorkspaceRestoreFailure(tx as unknown as Db, run, { workspaceRestoreFailure: "restore_failed" }, source);
|
|
if (!retained || retainFiles && !hasRequiredWorkspaceRecovery(retained.resultJson)) return;
|
|
if (options.allowPreterminal && coordinator.phase === "observed") {
|
|
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
|
const [settled] = await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure",
|
|
leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null, nextAttemptAt: null,
|
|
recoveryState: "blocked", failureCode: coordinator.failureCode ?? "native_continuation_requires_reconciliation", updatedAt: new Date(),
|
|
}).where(and(eq(nativeRunFinalizations.runId, run.id), eq(nativeRunFinalizations.companyId, run.companyId),
|
|
eq(nativeRunFinalizations.issueId, issueId), eq(nativeRunFinalizations.phase, "observed"), isNull(nativeRunFinalizations.resultId),
|
|
ownsClaim && claim ? and(eq(nativeRunFinalizations.leaseOwner, claim.leaseOwner),
|
|
eq(nativeRunFinalizations.controllerGeneration, claim.controllerGeneration), eq(nativeRunFinalizations.attempt, claim.providerAttempt),
|
|
gt(nativeRunFinalizations.leaseExpiresAt, sql`now()`)) : isNull(nativeRunFinalizations.leaseOwner),
|
|
)).returning({ id: nativeRunFinalizations.runId });
|
|
if (!settled) throw new NativeWorkspaceFinalizationBusyError();
|
|
[retained] = await tx.update(heartbeatRuns).set({ nativePhase: "terminal_failure", nativePhaseUpdatedAt: new Date() })
|
|
.where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId))).returning();
|
|
}
|
|
if (supersededExport && retainFiles) await markSupersededWorkspaceExportHold(tx as unknown as Db, retained);
|
|
if (retainFiles && !alreadyRetained) await logActivity(tx as unknown as Db, {
|
|
companyId: run.companyId, actorType: "system", actorId: "native-workspace-recovery",
|
|
action: "issue.workspace_recovery_required", entityType: "issue",
|
|
entityId: issueId,
|
|
agentId: run.agentId, runId: run.id,
|
|
details: { runId: run.id, leaseId: source.id, reason: "native_execution_failed_before_workspace_export" },
|
|
});
|
|
return retained;
|
|
});
|
|
}
|
|
|
|
export async function preserveOrphanedNativeWorkspace(db: Db, lease: Pick<typeof environmentLeases.$inferSelect,
|
|
"companyId" | "heartbeatRunId">, options: { onDeferredDeadline?: (at: number) => void } = {}): Promise<boolean> {
|
|
if (!lease.heartbeatRunId) return false;
|
|
const [run] = await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, lease.companyId), eq(heartbeatRuns.id, lease.heartbeatRunId),
|
|
inArray(heartbeatRuns.status, ["failed", "cancelled", "timed_out", "interrupted"]),
|
|
)).limit(1);
|
|
if (!run || hasRequiredWorkspaceRecovery(run.resultJson)) return false;
|
|
try {
|
|
if (run.runtimeMode === "legacy") {
|
|
const parsed = remoteWorkspaceRunReferenceSchema.safeParse(run.runnerProfileJson?.remoteWorkspace);
|
|
if (!parsed.success) return false;
|
|
const [source] = await db.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, run.companyId),
|
|
eq(environmentLeases.id, parsed.data.leaseId), eq(environmentLeases.heartbeatRunId, run.id))).limit(1);
|
|
const retained = source && await preserveRemoteWorkspacePreparationFailure(db, source);
|
|
return Boolean(retained && hasRequiredWorkspaceRecovery(retained.resultJson));
|
|
}
|
|
if (run.status !== "failed") return false;
|
|
if (await pinFailedObservedWorkspace(db, run.companyId, run.id)) return true;
|
|
const retained = await preserveNativeFailedWorkspace(db, run);
|
|
return Boolean(retained && hasRequiredWorkspaceRecovery(retained.resultJson));
|
|
} catch (error) {
|
|
if (error instanceof NativeWorkspaceFinalizationBusyError) return false;
|
|
const code = retentionContentionCode(error);
|
|
if (!code) throw error;
|
|
options.onDeferredDeadline?.(Date.now() + 30_000);
|
|
logger.warn({ runId: run.id, code }, "Native workspace retention is waiting for its current owner");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function retentionContentionCode(error: unknown): string | null {
|
|
let current = error;
|
|
for (let depth = 0; depth < 4 && current && typeof current === "object"; depth++) {
|
|
const value = current as { code?: unknown; cause?: unknown };
|
|
if (value.code === "55P03" || value.code === "57014") return value.code;
|
|
current = value.cause;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const cancelledWorkspaceCursors = new WeakMap<Db, string>();
|
|
|
|
/** Leases that may still hold a cancelled writer's prepared files. A reusable
|
|
* (warm) lease that ends without success is stopped and kept `released` under
|
|
* its reusable policy; a reassignment Stop leaves the writer's unsaved files
|
|
* there. Admission only finds candidates: retention still requires the exact
|
|
* stop-and-retain receipt and the workspace still bound to this writer. */
|
|
function cancelledWorkspaceSourceLease() {
|
|
return or(eq(environmentLeases.status, "active"),
|
|
and(inArray(environmentLeases.status, ["pending_cleanup", "released"]), eq(environmentLeases.leasePolicy, "ephemeral")),
|
|
and(eq(environmentLeases.status, "released"), eq(environmentLeases.cleanupStatus, "success"),
|
|
inArray(environmentLeases.leasePolicy, reusableLeasePolicies),
|
|
sql`${environmentLeases.metadata}->'remoteExecutionTermination'->>'state' = 'stopped'`,
|
|
sql`${environmentLeases.metadata} ? 'sandboxStopAndRetainReceipt'`));
|
|
}
|
|
|
|
/** Older controllers could acknowledge Stop without pinning prepared files.
|
|
* Record only the file obligation; the existing stop-only cleanup worker owns
|
|
* provider teardown. This never resumes a turn or changes the task's status. */
|
|
export async function preserveCancelledNativeWorkspaces(db: Db) {
|
|
const select = (cursor?: string) => db.selectDistinct({ runId: heartbeatRuns.id })
|
|
.from(environmentLeases).innerJoin(heartbeatRuns, and(
|
|
eq(heartbeatRuns.id, environmentLeases.heartbeatRunId), eq(heartbeatRuns.companyId, environmentLeases.companyId),
|
|
)).innerJoin(nativeRunFinalizations, and(eq(nativeRunFinalizations.runId, heartbeatRuns.id),
|
|
eq(nativeRunFinalizations.companyId, heartbeatRuns.companyId), eq(nativeRunFinalizations.issueId, heartbeatRuns.nativeIssueId)))
|
|
.where(and(cancelledWorkspaceSourceLease(), eq(heartbeatRuns.runtimeMode, "native"),
|
|
eq(heartbeatRuns.status, "cancelled"), eq(nativeRunFinalizations.phase, "terminal_failure"),
|
|
or(isNull(nativeRunFinalizations.resultId), eq(nativeRunFinalizations.failureCode, "native_retry_cancelled")),
|
|
isNull(nativeRunFinalizations.leaseOwner),
|
|
sql`(${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' = 'prepared' OR ${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'->>'state' = 'prepared')`,
|
|
sql`${heartbeatRuns.resultJson}->'nativeCancellation'->>'dispatchState' = 'acknowledged'`,
|
|
cursor ? gt(heartbeatRuns.id, cursor) : undefined,
|
|
)).orderBy(asc(heartbeatRuns.id)).limit(5);
|
|
let candidates = await select(cancelledWorkspaceCursors.get(db));
|
|
if (!candidates.length) {
|
|
cancelledWorkspaceCursors.delete(db);
|
|
candidates = await select();
|
|
}
|
|
for (const candidate of candidates) {
|
|
cancelledWorkspaceCursors.set(db, candidate.runId);
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, candidate.runId));
|
|
if (run && hasAcknowledgedNativeRunStopRequest(run) && await cancelledWorkspaceSource(db, run)) {
|
|
try { await preserveNativeFailedWorkspace(db, run, { allowPreterminal: true, requireCancelledStop: true }); }
|
|
catch (error) {
|
|
if (error instanceof NativeWorkspaceFinalizationBusyError) continue;
|
|
const code = retentionContentionCode(error);
|
|
if (!code) throw error;
|
|
logger.warn({ runId: run.id, code }, "Cancelled native workspace retention is waiting for its current owner");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function pendingCancelledWorkspace() {
|
|
return sql`${heartbeatRuns.runtimeMode} = 'native' AND ${heartbeatRuns.status} = 'cancelled'
|
|
AND (${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' = 'prepared' OR ${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'->>'state' = 'prepared')
|
|
AND ${heartbeatRuns.resultJson}->'nativeCancellation'->>'dispatchState' = 'acknowledged'
|
|
AND (${heartbeatRuns.resultJson}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'
|
|
AND ${heartbeatRuns.resultJson}->>'workspaceRestoreFailure' IN (${workspaceRestoreFailureCodesSql})) IS NOT TRUE`;
|
|
}
|
|
|
|
export function registerCancelledWorkspacePreservationWork(db: Db,
|
|
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>, canRun: () => boolean,
|
|
canRecover: () => Promise<boolean>) {
|
|
type Entry = { id: string; companyId: string; dueAt: number };
|
|
type Candidate = Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "agentId" | "issueId" | "nativeIssueId"
|
|
| "runtimeMode" | "driverKind" | "status" | "resultJson" | "runnerProfileJson">;
|
|
const eligible = (run: Candidate) => run.nativeIssueId !== null && hasAcknowledgedNativeRunStopRequest(run)
|
|
&& workspaceRecoveryReference(run.runnerProfileJson)?.state === "prepared"
|
|
&& !hasRequiredWorkspaceRecovery(run.resultJson) && !nativeRunHasNoWorkspaceAccess(run);
|
|
const scopeCondition = (scope?: CancelledWorkspacePreservationScope) => scope ? and(
|
|
eq(heartbeatRuns.companyId, scope.companyId), scope.runId ? eq(heartbeatRuns.id, scope.runId) : undefined) : undefined;
|
|
async function load(scope: CancelledWorkspacePreservationScope | undefined, signal?: AbortSignal) {
|
|
if (!await canRecover()) return [];
|
|
const entries: Entry[] = [];
|
|
let cursor: string | undefined;
|
|
while (canRun() && !signal?.aborted) {
|
|
const rows = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
|
issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, runtimeMode: heartbeatRuns.runtimeMode,
|
|
driverKind: heartbeatRuns.driverKind, status: heartbeatRuns.status, resultJson: heartbeatRuns.resultJson,
|
|
runnerProfileJson: heartbeatRuns.runnerProfileJson }).from(heartbeatRuns).where(and(pendingCancelledWorkspace(), scopeCondition(scope),
|
|
cursor ? gt(heartbeatRuns.id, cursor) : undefined)).orderBy(asc(heartbeatRuns.id)).limit(100);
|
|
for (const row of rows) if (eligible(row)) entries.push({ id: row.id, companyId: row.companyId, dueAt: 0 });
|
|
if (rows.length < 100) return entries;
|
|
cursor = rows[rows.length - 1].id;
|
|
}
|
|
throw new Error("Cancelled workspace preservation reconstruction stopped");
|
|
}
|
|
async function check(entry: Entry, signal?: AbortSignal): Promise<Entry | null> {
|
|
if (!await canRecover()) return null;
|
|
const [run] = await db.select().from(heartbeatRuns)
|
|
.where(and(pendingCancelledWorkspace(), scopeCondition({ companyId: entry.companyId, runId: entry.id })));
|
|
if (!run || !eligible(run)) return null;
|
|
if (!canRun() || signal?.aborted) throw new Error("Cancelled workspace preservation stopped");
|
|
const controllerDeadline = run.controllerLeaseExpiresAt?.getTime();
|
|
if (controllerDeadline && controllerDeadline > Date.now()) return { ...entry, dueAt: controllerDeadline };
|
|
const [finalization] = await db.select().from(nativeRunFinalizations).where(and(
|
|
eq(nativeRunFinalizations.runId, run.id), eq(nativeRunFinalizations.companyId, run.companyId),
|
|
eq(nativeRunFinalizations.issueId, run.nativeIssueId!),
|
|
));
|
|
if (finalization?.resultId && !stoppedAcceptedCopyback(finalization)) return null;
|
|
if (finalization?.phase !== "terminal_failure" || finalization.leaseOwner) {
|
|
const ownerDeadline = finalization?.leaseOwner ? finalization.leaseExpiresAt?.getTime() ?? null : null;
|
|
if (ownerDeadline && ownerDeadline > Date.now()) return { ...entry, dueAt: ownerDeadline };
|
|
if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId)
|
|
&& await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null;
|
|
return { ...entry, dueAt: Date.now() + 30_000 };
|
|
}
|
|
if (await cancelledWorkspaceSource(db, run)) await preserveNativeFailedWorkspace(db, run, { allowPreterminal: true, requireCancelledStop: true });
|
|
else if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId)
|
|
&& await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null;
|
|
const [current] = await db.select().from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId)));
|
|
const currentControllerDeadline = current?.controllerLeaseExpiresAt?.getTime();
|
|
return current && current.status === "cancelled" && eligible(current) ? { ...entry,
|
|
dueAt: currentControllerDeadline && currentControllerDeadline > Date.now() ? currentControllerDeadline : Date.now() + 30_000 } : null;
|
|
}
|
|
return registerScopedDeadlineWork(coordinator, {
|
|
queue: DELIVERY_QUEUES.cancelledWorkspacePreservation, batchSize: 5,
|
|
decodeScope: (hint: string): CancelledWorkspacePreservationScope | undefined => hint === "*" ? undefined : JSON.parse(hint),
|
|
matches: (entry: Entry, scope?: CancelledWorkspacePreservationScope) => !scope ||
|
|
entry.companyId === scope.companyId && (!scope.runId || entry.id === scope.runId),
|
|
load, check,
|
|
}, canRun);
|
|
}
|