mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-14 00:26:28 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs on remote sandboxes keep a warm sandbox and a verified harness backup so the next run continues the same provider session > - A run that starts while the previous run's workspace export is still saving gets a new (created) sandbox lease, because reuse skips an exporting sandbox > - When that run prepares the harness, it finds a backup but no recorded reusable lease, and it fails closed with `runner_harness_state_mismatch: backup_without_reusable_lease` > - #20278 accepted a destroyed source and a settled restore hold as retired backup sources, but not an idle warm source that is still `retained` for reuse > - This pull request accepts an idle warm source under the same proofs, claims it so it is never resumed again, and covers the resumed lease that the failed run leaves behind > - The benefit is that these recoveries continue the same session automatically instead of blocking the task ## Linked Issues or Issue Description Refs #20278 **What happened?** A monitor wake started about 90 seconds after the previous run on the same task finished. The previous run's warm sandbox lease was `retained` with policy `reuse_by_environment`, but its workspace export was still saving. Reuse skipped it and created a new sandbox. Workspace realization waited for the export (about 136 s) and restored the saved files. Then harness preparation found the previous run's backup (its lease stamp names this exact manifest, and no provider work followed it). The source lease was not destroyed and was not a restore hold, so the run failed with `native_session_recovery_failed: Error: runner_harness_state_mismatch: backup_without_reusable_lease` and the task was blocked. **What did you expect?** The run continues the same provider session. The idle source sandbox holds exactly the backed-up state, so restoring the backup into the new sandbox is safe. **Steps to reproduce** 1. Finish a warm native run on a remote sandbox. Its workspace export is still saving. 2. Start the next run on the same task before the export settles. 3. Reuse skips the exporting sandbox and creates a new lease. Harness preparation fails with `backup_without_reusable_lease`. 4. A retry resumes that new lease, which has no harness state, and fails with `resumed_unavailable`. ## What Changed - `native-retired-backup-source.ts`: an idle warm source is a third retired backup source. It must be `released` or `retained` with policy `reuse_by_environment`, its own run must be terminal and not the current run, and it must have no cleanup in flight, no restore hold or pending shutdown settlement, and no pending native workspace export. The backup stamp, single-owner chain, and later-provider-work checks still apply. - Before the restore, the idle source is claimed with a compare-and-swap on the checked row. The claim moves its `reusableSandboxLease` scope into a `reusableSandboxLeaseSuperseded` receipt. Reuse never resumes that older state again, and the next acquisition treats it as obsolete and destroys it. If a run resumed or changed the source first, the claim matches no row and the backup is not restored. - `environments.ts`: a cross-run reuse handoff now requires that the source row has no superseded receipt. The supersede claim and the handoff compete on the same row, so an acquisition that selected the source before the claim cannot resume it afterward. - The proof now rejects a backup whose source is the target allocation itself (`targetProviderLeaseId`). - `native-session-executor.ts`: a resumed lease whose sandbox has no harness state at all (`unavailable`) restores the backup under the same proof. This recovers the lease that the failed run left behind, so rows saved by older releases recover after deploy without a migration. - `doc/execution-semantics.md`: documents the idle-source rule, the supersede claim, and the resumed stateless lease. ## Verification - Red before the fix, green after: - `native-session-executor.test.ts` "restores a warm backup into a created lease only when an idle warm source finished its run and its export" failed with `backup_without_reusable_lease`. - "... a resumed lease never held the session and the warm source is idle" failed with `resumed_unavailable`. - `native-retired-backup-source.integration.test.ts` (real Postgres) "authorizes an idle retained/released warm source and claims it as superseded" failed (returned false). - Integration test "refuses a reuse handoff of a source superseded while its provider resume was pending" fails without the handoff guard and passes with it. - Safety rows stay refused: source run still running, workspace export pending, cleanup in flight, restore into its own allocation, stamp names another checkpoint, provider work after the backup, two host leases for one allocation, claim lost to another run, and a resumed lease that lost its own state. Existing destroyed-source and restore-hold rows are unchanged. - `cd server && npx vitest run src/services/native-runtime/native-session-executor.test.ts src/services/native-runtime/native-retired-backup-source.integration.test.ts src/services/native-runtime/remote-warm-session-recovery.test.ts` passes (1408 tests). - `npx tsc --noEmit -p server/tsconfig.json` passes. - `pnpm verify` exits 2 because a global CI input (`doc/execution-semantics.md`) changed. Required CI supplies the broad coverage. ## Risks - Previous-release story: no persisted shape changes. Lease rows saved by earlier releases carry forward. The new `reusableSandboxLeaseSuperseded` metadata key is additive. - The idle source is destroyed at the next acquisition for its workspace. Its state is the verified backup, which the restored lease now holds, so no work is lost. - Not covered: when the source cannot be proven retired or idle (for example a live owner or later provider work), the run still fails closed with the same named code. An automatic fresh-session fallback for that case is not in this PR. - The root trigger (reuse skips a sandbox while its export saves, then waits for that export) is unchanged. This PR does not change the reuse lookup. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, with tool use and code execution in Claude Code. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
166 lines
10 KiB
TypeScript
166 lines
10 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { and, eq, gt, inArray, ne, sql } from "drizzle-orm";
|
|
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db";
|
|
import { retiredReusableLeasePredecessors } from "../environment-lease-handoff.js";
|
|
import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js";
|
|
import { hasConfirmedSandboxStopAndRetain } from "../sandbox-stop-and-retain.js";
|
|
import { LEGACY_WORKSPACE_RECOVERY_KEY, LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "../workspace-restore-recovery-state.js";
|
|
import { readNativeHarnessBackupStamp } from "./native-harness-backup-stamp.js";
|
|
import { nativeWorkspaceExportPendingForLease, nativeWorkspaceExportPendingForResource } from "./native-workspace-finalization-state.js";
|
|
|
|
/** Durable run events that prove a provider session did work in a run. */
|
|
export const NATIVE_PROVIDER_DURABLE_EVENT_TYPES = new Set([
|
|
"harness.ready",
|
|
"session.started",
|
|
"session.resumed",
|
|
"session.updated",
|
|
"turn.started",
|
|
"provider.event",
|
|
"provider.rpc_result",
|
|
]);
|
|
|
|
export function nativeHarnessBackupManifestSha256(manifestBytes: Buffer | string): string {
|
|
return `sha256:${createHash("sha256").update(manifestBytes).digest("hex")}`;
|
|
}
|
|
|
|
/**
|
|
* A created sandbox normally refuses a per-turn backup that has no recorded
|
|
* reusable lease, because the backup's source sandbox may still hold newer
|
|
* provider state. That ambiguity is absent when Paperclip itself destroyed the
|
|
* source sandbox: the provider confirmed the termination, the source lease's
|
|
* stamp names exactly this backup, and no provider work for the session was
|
|
* recorded after the backup completed. This is the same proof a confirmed
|
|
* replacement relies on, reached through a lease that was retired first.
|
|
*
|
|
* A settled workspace-restore hold is the other retired source. The hold
|
|
* changed the lease to `retain_on_failure`, which reuse never selects, and
|
|
* stopped the sandbox under a stop-only receipt that permits no provider work.
|
|
* Releases before the hold settlement restored warm reuse left such rows
|
|
* stranded, so this also unsticks state saved by those releases.
|
|
*
|
|
* An idle warm source is the third. Its own run is terminal, no run holds the
|
|
* lease, and no workspace export is pending on the sandbox, so nothing can do
|
|
* provider work there. Reuse skips such a lease while the previous run's
|
|
* workspace export is still in flight, and the next run then gets a new lease.
|
|
* With no provider work after the backup, the idle sandbox holds exactly the
|
|
* checkpointed state, so restoring the backup continues the same session. The
|
|
* source is claimed as superseded first, so it is never resumed with that
|
|
* older state after the restored lease moves on.
|
|
*/
|
|
export async function retiredSourceAuthorizesNativeBackupRestore(db: Db, input: {
|
|
companyId: string;
|
|
currentRunId: string;
|
|
normalizedSessionId: string;
|
|
manifest: { sourceProviderLeaseId: string; runnerInstanceId: string; normalizedSessionId: string };
|
|
manifestSha256: string;
|
|
/** The allocation the backup restores into. Its own missing state never proves a retired source. */
|
|
targetProviderLeaseId?: string | null;
|
|
}): Promise<boolean> {
|
|
if (!input.manifest.sourceProviderLeaseId || input.manifest.normalizedSessionId !== input.normalizedSessionId
|
|
|| input.manifest.sourceProviderLeaseId === input.targetProviderLeaseId) return false;
|
|
const leases = await db.select().from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, input.companyId),
|
|
eq(environmentLeases.providerLeaseId, input.manifest.sourceProviderLeaseId),
|
|
));
|
|
const source = leases.filter(lease => lease.companyId === input.companyId
|
|
&& lease.providerLeaseId === input.manifest.sourceProviderLeaseId);
|
|
const tips = source.filter(lease => !Object.hasOwn(lease.metadata ?? {}, "reusableLeaseSuccessor"));
|
|
if (tips.length !== 1) return false;
|
|
const lease = tips[0]!;
|
|
if (!retiredReusableLeasePredecessors(lease, source.filter(row => row.id !== lease.id))) return false;
|
|
const termination = lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined;
|
|
const destroyed = ["expired", "failed"].includes(lease.status) && hasRemoteTerminationReceipt(lease)
|
|
&& termination?.state === "destroyed";
|
|
const stamp = readNativeHarnessBackupStamp(lease.metadata?.nativeHarnessBackup, lease.providerLeaseId!);
|
|
if (!stamp || stamp.manifestSha256 !== input.manifestSha256
|
|
|| stamp.normalizedSessionId !== input.normalizedSessionId
|
|
|| stamp.runnerInstanceId !== input.manifest.runnerInstanceId) return false;
|
|
// A released lease can still be selected for resume; only a retired one is final.
|
|
const idleSource = !destroyed && !await settledRestoreHoldRetiresSource(db, lease);
|
|
if (idleSource && !await idleWarmSourceRetiresBackup(db, lease, input.currentRunId)) return false;
|
|
// Provider work recorded after the checkpoint means the destroyed sandbox
|
|
// held newer state than this backup. Restoring would silently rewind it.
|
|
const later = await db.select({ runId: heartbeatRunEvents.runId }).from(heartbeatRunEvents)
|
|
.innerJoin(heartbeatRuns, eq(heartbeatRuns.id, heartbeatRunEvents.runId))
|
|
.where(and(
|
|
eq(heartbeatRunEvents.companyId, input.companyId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
eq(heartbeatRuns.nativeSessionId, input.normalizedSessionId),
|
|
ne(heartbeatRuns.id, input.currentRunId),
|
|
inArray(heartbeatRunEvents.eventType, [...NATIVE_PROVIDER_DURABLE_EVENT_TYPES]),
|
|
gt(heartbeatRunEvents.createdAt, new Date(stamp.completedAt)),
|
|
)).limit(1);
|
|
if (later.length) return false;
|
|
return !idleSource || await supersedeIdleWarmSource(db, lease, input);
|
|
}
|
|
|
|
export const SUPERSEDED_REUSABLE_SANDBOX_KEY = "reusableSandboxLeaseSuperseded";
|
|
|
|
/**
|
|
* Claims an idle warm source before its backup is restored elsewhere. The
|
|
* source still holds the checkpointed session, and the restored lease will
|
|
* move past it, so the source must never be resumed again. Removing its reuse
|
|
* scope makes the next acquisition for this workspace treat it as obsolete and
|
|
* clean it up through the existing obsolete-lease path. The write is a
|
|
* compare-and-swap on the checked row: a run that resumed or changed the lease
|
|
* in the meantime wins, and the restore does not happen.
|
|
*/
|
|
async function supersedeIdleWarmSource(db: Db, lease: typeof environmentLeases.$inferSelect, input: {
|
|
companyId: string; currentRunId: string; manifestSha256: string; targetProviderLeaseId?: string | null;
|
|
}) {
|
|
const { reusableSandboxLease: scope, ...metadata } = lease.metadata ?? {};
|
|
const [claimed] = await db.update(environmentLeases).set({
|
|
metadata: { ...metadata, [SUPERSEDED_REUSABLE_SANDBOX_KEY]: {
|
|
schema: "paperclip.reusable-sandbox-lease-superseded.v1", reason: "harness_backup_restored_elsewhere",
|
|
supersededByRunId: input.currentRunId, supersededByProviderLeaseId: input.targetProviderLeaseId ?? null,
|
|
manifestSha256: input.manifestSha256, reusableSandboxLease: scope ?? null, supersededAt: new Date().toISOString(),
|
|
} },
|
|
updatedAt: new Date(),
|
|
}).where(and(
|
|
eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.id, lease.id),
|
|
eq(environmentLeases.status, lease.status), eq(environmentLeases.leasePolicy, "reuse_by_environment"),
|
|
eq(environmentLeases.heartbeatRunId, lease.heartbeatRunId!),
|
|
sql`${environmentLeases.metadata} = ${JSON.stringify(lease.metadata)}::jsonb`,
|
|
)).returning({ id: environmentLeases.id });
|
|
return Boolean(claimed);
|
|
}
|
|
|
|
const TERMINAL_SOURCE_RUN_STATUSES = new Set(["succeeded", "failed", "cancelled", "timed_out", "interrupted"]);
|
|
|
|
/**
|
|
* A warm reusable lease whose run has ended and that no run holds. Its sandbox
|
|
* may still be running, but only a run does provider work there, and the
|
|
* caller's later-work check proves none did after the backup. A pending
|
|
* workspace export or cleanup on the allocation keeps it ambiguous.
|
|
*/
|
|
async function idleWarmSourceRetiresBackup(db: Db, lease: typeof environmentLeases.$inferSelect, currentRunId: string) {
|
|
if (lease.leasePolicy !== "reuse_by_environment" || !["released", "retained"].includes(lease.status)
|
|
|| !lease.heartbeatRunId || lease.heartbeatRunId === currentRunId
|
|
|| lease.metadata?.pendingCleanupInFlight === true
|
|
// A restore hold or a pending shutdown settlement still protects the files; reuse skips these too.
|
|
|| Object.hasOwn(lease.metadata ?? {}, LEGACY_WORKSPACE_RECOVERY_KEY)
|
|
|| (lease.metadata?.legacyShutdownWorkspaceSettlement as { state?: unknown } | undefined)?.state === "pending") return false;
|
|
const [run] = await db.select({ sourceRunStatus: heartbeatRuns.status }).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, lease.companyId), eq(heartbeatRuns.id, lease.heartbeatRunId))).limit(1);
|
|
if (!run || !TERMINAL_SOURCE_RUN_STATUSES.has(run.sourceRunStatus)) return false;
|
|
return !await nativeWorkspaceExportPendingForResource(db, lease, currentRunId);
|
|
}
|
|
|
|
/**
|
|
* A stopped, released lease is retired only when it is a workspace-restore hold
|
|
* that nothing can select for resume: `retain_on_failure` with the hold's own
|
|
* marker, a confirmed stop-and-retain receipt whose state is `stopped`, and no
|
|
* unsaved writer or pending native workspace export bound to the allocation.
|
|
* A stopped `reuse_by_environment` lease stays ambiguous and fails closed.
|
|
*/
|
|
async function settledRestoreHoldRetiresSource(db: Db, lease: typeof environmentLeases.$inferSelect): Promise<boolean> {
|
|
const marker = lease.metadata?.workspaceRestoreRecovery as { schema?: unknown; runId?: unknown } | undefined;
|
|
if (lease.leasePolicy !== "retain_on_failure" || lease.status !== "released" || !lease.heartbeatRunId
|
|
|| marker?.schema !== LEGACY_WORKSPACE_RECOVERY_SCHEMA || marker.runId !== lease.heartbeatRunId) return false;
|
|
// Provider expiry cannot revive the allocation; it only makes the source
|
|
// more final. Every other stop-and-retain receipt check stays strict.
|
|
if (!hasConfirmedSandboxStopAndRetain({ ...lease, expiresAt: null })) return false;
|
|
// Includes the dirty remote writer source (`preparedRemoteWorkspaceSource`).
|
|
return !await nativeWorkspaceExportPendingForLease(db, lease);
|
|
}
|