The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(runtime): preserve unexported native work during lease cleanup (#16583)
Dottaf5534717b020
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.mdindex 019d752eb2..bcd8156666 100644--- a/doc/DEVELOPING.md+++ b/doc/DEVELOPING.md@@ -2006,6 +2006,15 @@ The shared lease-release boundary rechecks the durable run status for recoveryand ordinary teardown. Successful workspace copy-back alone must not keep afailed turn's sandbox running.+Native workspace export also fences destructive lease cleanup. A failed heartbeat+can still own unexported files, including when checkpoint copyback failed before+its semantic result was accepted. The orphan and pending-cleanup sweeps preserve+the exact lease bound by a prepared workspace-sync reference until export records+it finalized. Direct release and destruction apply the same check. Explicit+stop-only cleanup remains available; neither a retry deadline nor an exhausted+retry budget authorizes deletion of the only workspace copy. This does not change+successful warm-session retention or admit another provider turn.+Run the credential-free real-process restart suite with:```shdiff --git a/server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.ts b/server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.tsindex 6ff69f16f0..016dfb87c1 100644--- a/server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.ts+++ b/server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.ts@@ -1,4 +1,7 @@import { randomUUID } from "node:crypto";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";import { eq } from "drizzle-orm";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import {@@ -35,6 +38,8 @@ vi.mock("../middleware/logger.js", () => ({import { logger } from "../middleware/logger.ts";import { heartbeatService, type HeartbeatEnvironmentRuntime } from "../services/heartbeat.ts";+import { environmentRuntimeService } from "../services/environment-runtime.js";+import { nativeWorkspaceExportPendingForLease } from "../services/native-runtime/native-workspace-finalization-state.js";const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;@@ -160,6 +165,89 @@ describeEmbeddedPostgres("heartbeat sweepOrphanedActiveLeases", () => {const oldEnough = () => new Date(Date.now() - 60 * 60 * 1000);+ async function seedUnexportedWorkspace(status = "active") {+ const { companyId, agentId, environmentId } = await seedCompanyAgentAndEnvironment();+ const runId = await insertHeartbeatRun({ companyId, agentId, status: "failed" });+ const leaseId = await insertActiveLease({ companyId, environmentId, heartbeatRunId: runId, status, updatedAt: oldEnough() });+ const lease = (await leaseRow(leaseId))!;+ const reference = {+ schema: "paperclip.native-workspace-sync/v3", state: "prepared",+ descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null,+ workspaceId: randomUUID(), leaseId, providerLeaseId: lease.providerLeaseId,+ remoteCwd: "/workspace", resourceDisposition: "destroy",+ };+ await db.update(heartbeatRuns).set({ runtimeMode: "native", runnerProfileJson: { nativeWorkspaceSync: reference } })+ .where(eq(heartbeatRuns.id, runId));+ return { companyId, agentId, environmentId, runId, leaseId, lease, reference };+ }++ it.each(["active", "pending_cleanup"])("preserves an unexported native workspace in %s across cleanup restart", async status => {+ const { runId, leaseId, reference } = await seedUnexportedWorkspace(status);+ const sandbox = await mkdtemp(join(tmpdir(), "native-export-cleanup-"));+ const output = join(sandbox, "unexported.txt");+ const nonce = randomUUID();+ await writeFile(output, nonce);+ const destroyRunLease = vi.fn(async () => {+ await rm(sandbox, { recursive: true, force: true });+ return (await db.update(environmentLeases).set({ status: "expired", cleanupStatus: "success" })+ .where(eq(environmentLeases.id, leaseId)).returning())[0];+ });+ const runtime = { destroyRunLease } as unknown as HeartbeatEnvironmentRuntime;+ try {+ const restarted = heartbeatService(db, { environmentRuntime: runtime });+ await restarted.sweepOrphanedActiveLeases({ backoffMs: 0 });+ await restarted.sweepPendingCleanupLeases({ backoffMs: 0 });+ expect(destroyRunLease).not.toHaveBeenCalled();+ expect(await readFile(output, "utf8")).toBe(nonce);+ expect((await leaseRow(leaseId))?.status).toBe(status);++ await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceSync: {+ ...reference, state: "finalized", finalHostSha256: "c".repeat(64),+ } } }).where(eq(heartbeatRuns.id, runId));+ const afterExport = heartbeatService(db, { environmentRuntime: runtime });+ await afterExport.sweepOrphanedActiveLeases({ backoffMs: 0 });+ await afterExport.sweepPendingCleanupLeases({ backoffMs: 0 });+ expect(destroyRunLease).toHaveBeenCalledOnce();+ await expect(readFile(output)).rejects.toMatchObject({ code: "ENOENT" });+ } finally {+ await rm(sandbox, { recursive: true, force: true });+ }+ });++ it("guards direct destructive release and teardown before provider dispatch", async () => {+ const { environmentId, runId, lease } = await seedUnexportedWorkspace();+ const runtime = environmentRuntimeService(db);+ const environment = (await db.select().from(environments).where(eq(environments.id, environmentId)))[0];+ const input = { environment, lease } as Parameters<typeof runtime.destroyRunLease>[0];+ expect(await runtime.releaseRunLeases(runId, "failed")).toEqual([]);+ expect(await runtime.releaseRunLeases(runId, "failed", undefined, "destroy")).toEqual([]);+ expect(await runtime.destroyRunLease(input)).toBeNull();+ await expect(runtime.retryPendingSandboxTeardown(input)).rejects.toThrow("Native workspace export is pending");+ expect(await leaseRow(lease.id)).toMatchObject({ status: "active", releasedAt: null });+ });++ it.each(["company", "run", "lease", "provider", "finalized", "no_workspace"])("does not pin an unrelated or exported source: %s", async mode => {+ const { companyId, agentId, runId, lease, reference } = await seedUnexportedWorkspace();+ const source = { ...lease };+ if (mode === "company") source.companyId = randomUUID();+ if (mode === "run") source.heartbeatRunId = randomUUID();+ if (mode === "lease") source.id = randomUUID();+ if (mode === "provider") source.providerLeaseId = randomUUID();+ if (mode === "finalized" || mode === "no_workspace") {+ await db.update(heartbeatRuns).set({+ ...(mode === "no_workspace" ? { driverKind: "openai_dot_mcp" } : {}),+ runnerProfileJson: {+ nativeWorkspaceSync: mode === "finalized" ? { ...reference, state: "finalized", finalHostSha256: "c".repeat(64) } : reference,+ ...(mode === "no_workspace" ? { nativeExecutionInput: {+ schema: "paperclip.native-execution-input.v6", binding: { runId, companyId, agentId, issueId: null },+ provider: { kind: "openai_dot" }, workspace: { access: "none", cwd: null },+ } } : {}),+ },+ }).where(eq(heartbeatRuns.id, runId));+ }+ expect(await nativeWorkspaceExportPendingForLease(db, source)).toBe(false);+ });+it.each([false, true])("releases an interrupted local run's bookkeeping lease (deleted environment: %s)", async (deletedEnvironment) => {const { companyId, agentId, environmentId } = await seedCompanyAgentAndEnvironment();await db.delete(environments).where(eq(environments.driver, "local"));diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.tsindex 07bad8dea9..c488b4c591 100644--- a/server/src/services/environment-runtime.ts+++ b/server/src/services/environment-runtime.ts@@ -1,4 +1,5 @@import { allowLegacyShutdownWorkspaceCleanup, legacyShutdownWorkspaceResourceProtected } from "./legacy-shutdown-workspace-settlement.js";+import { nativeWorkspaceExportPendingForLease } from "./native-runtime/native-workspace-finalization-state.js";import { beginIdleTrackedWork } from "./task-admission.js";import { hasStopOnlyCleanup, prepareSandboxStopAndRetain, readStopOnlyCleanup, settleStopOnlyCleanup, stopOnlyCleanupKey } from "./sandbox-stop-and-retain.js";import { JsonRpcCallError, readEnvironmentAcquisitionDiagnostic, readEnvironmentCreationCleanupError } from "@paperclipai/plugin-sdk";@@ -2611,6 +2612,9 @@ function createSandboxEnvironmentDriver(async retryPendingSandboxTeardown(input) {const exportResume = hasStopOnlyCleanup(input.lease);+ if (!exportResume && await nativeWorkspaceExportPendingForLease(db, input.lease)) {+ throw new Error("Native workspace export is pending; destructive cleanup is forbidden.");+ }const resumeIntent = readStopOnlyCleanup(input.lease);const assertExportResumeOwnership = async () => {if (!resumeIntent) throw new Error("Workspace export resume ownership is invalid.");@@ -3900,6 +3904,7 @@ export function environmentRuntimeService(scopeCondition?: ReturnType<typeof and>;failureReason: string;}): Promise<EnvironmentLease | null> {+ if (await nativeWorkspaceExportPendingForLease(db, input.leaseRow)) return null;if (!(await allowLegacyShutdownWorkspaceCleanup(db, input.leaseRow))) return null;const now = new Date();const attemptId = randomUUID();@@ -4080,6 +4085,8 @@ export function environmentRuntimeService(const released: EnvironmentRuntimeLeaseRecord[] = [];for (let leaseRow of leaseRows) {try {+ if (providerResourceDisposition !== "stop_and_retain" && providerResourceDisposition !== "keep_running"+ && !hasStopOnlyCleanup(leaseRow) && await nativeWorkspaceExportPendingForLease(db, leaseRow)) continue;if (!(await allowLegacyShutdownWorkspaceCleanup(db, leaseRow, new Date(), {ownerStopOnly: cancelActiveWork === true && providerResourceDisposition === "stop_and_retain",}))) continue;@@ -4445,6 +4452,7 @@ export function environmentRuntimeService(},async destroyRunLease(input: EnvironmentDriverLeaseInput): Promise<EnvironmentLease | null> {+ if (await nativeWorkspaceExportPendingForLease(db, input.lease)) return null;if (await legacyShutdownWorkspaceResourceProtected(db, input.lease)) return null;if (input.lease.metadata?.legacyShutdownWorkspaceSettlement) {if (!(await allowLegacyShutdownWorkspaceCleanup(db, input.lease))) return null;diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.tsindex 27ac5659e8..80384df1c8 100644--- a/server/src/services/heartbeat/recovery.ts+++ b/server/src/services/heartbeat/recovery.ts@@ -1,5 +1,5 @@import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js";-import { pendingNativeWorkspaceFinalizationCondition } from "../native-runtime/native-workspace-finalization-state.js";+import { nativeWorkspaceExportPendingForLease, pendingNativeWorkspaceFinalizationCondition } from "../native-runtime/native-workspace-finalization-state.js";import { CHAT_COMPLETION_WAKE_REASON } from "../chat-completion-delivery.js";import {hasStopOnlyCleanup,@@ -1491,6 +1491,10 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryDlet recovered = 0;for (const { lease } of rows) {+ if (await nativeWorkspaceExportPendingForLease(db, lease)) {+ await deferOrphanedActiveLease(lease.id);+ continue;+ }if (!(await allowLegacyShutdownWorkspaceCleanup(db, lease))) {await deferOrphanedActiveLease(lease.id);continue;@@ -1613,6 +1617,10 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryDlet capped = 0;for (const row of rows) {if (pendingCleanupAttemptsInFlight.has(row.id)) continue;+ if (!hasStopOnlyCleanup(row) && await nativeWorkspaceExportPendingForLease(db, row)) {+ await deferPendingCleanupLease(row.id);+ continue;+ }if (!(await allowLegacyShutdownWorkspaceCleanup(db, row))) {await deferPendingCleanupLease(row.id);continue;diff --git a/server/src/services/native-runtime/native-workspace-finalization-state.ts b/server/src/services/native-runtime/native-workspace-finalization-state.tsindex df83b63305..3317d8dc83 100644--- a/server/src/services/native-runtime/native-workspace-finalization-state.ts+++ b/server/src/services/native-runtime/native-workspace-finalization-state.ts@@ -1,5 +1,31 @@-import { heartbeatRuns, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";-import { and, eq, exists } from "drizzle-orm";+import { environmentLeases, heartbeatRuns, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";+import { and, eq, exists, sql } from "drizzle-orm";+import { nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";+import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";++type WorkspaceSourceLease = Pick<typeof environmentLeases.$inferSelect,+ "id" | "companyId" | "heartbeatRunId" | "provider" | "providerLeaseId">;++export async function nativeWorkspaceExportPendingForLease(db: Db, lease: WorkspaceSourceLease): Promise<boolean> {+ if (!lease.heartbeatRunId || !lease.provider || lease.provider === "local" || !lease.providerLeaseId) return false;+ const input = sql`${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput'`;+ const [run] = await db.select({+ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,+ issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId,+ runtimeMode: heartbeatRuns.runtimeMode, driverKind: heartbeatRuns.driverKind,+ reference: sql<unknown>`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'`,+ executionScope: sql<Record<string, unknown>>`jsonb_build_object(+ 'schema', ${input}->'schema', 'binding', ${input}->'binding', 'workspace', ${input}->'workspace',+ 'provider', jsonb_build_object('kind', ${input}#>'{provider,kind}'))`,+ }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.id, lease.heartbeatRunId), eq(heartbeatRuns.companyId, lease.companyId),+ eq(heartbeatRuns.runtimeMode, "native"),+ )).limit(1);+ if (!run || nativeRunHasNoWorkspaceAccess({ ...run, runnerProfileJson: { nativeExecutionInput: run.executionScope } })) return false;+ const reference = readNativeWorkspaceSyncReference(run.reference);+ return reference?.state === "prepared" && reference.leaseId === lease.id+ && reference.providerLeaseId === lease.providerLeaseId;+}/*** An accepted result transfers recovery to the workspace finalizer. A dead