diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 65457294a6e..c6e3c9c9b38 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1153,6 +1153,8 @@ workspace repair gate. Native runner ownership keeps its existing restart path. Real gates still apply: company and task ownership, active provider ownership, budget limits, agent availability, dependencies, pending approval/review paths, and explicit pause holds. Native runner reattachment and finalization retain their existing ownership protocol. Process, HTTP, and gateway adapters retain their recovery rules because invoking those adapters can itself repeat an external action rather than start a conversation turn. +A source that already stopped and was released remains fenced until its export settles; restart reconciliation scans these released sources too. Both provider reuse and destruction check the physical allocation for a shutdown fence or file-repair pin, including historical lease rows. + An operator Stop waits for provider termination. Remote sandbox providers may return a stopped/deleted receipt after their control-plane operation completes. Paperclip binds that receipt to the company, run, and exact lease; successful file cleanup, a terminal run row, or an in-sandbox shutdown event is not sufficient. Legacy conversational runs receive their cancellation acknowledgement after all remote leases have confirmed termination. Stop alone never creates a continuation. A user message queued during remote cleanup is reconsidered when the provider confirms termination; it still passes normal admission and adopts pending comment IDs in order. Once stopped, the next explicit wake uses the same queue. A compatible saved ACP session can resume, and an unavailable or incompatible session can start fresh with the full task context. Run credentials and scratch paths remain scoped to the new run. A subtree pause requires Resume; a message does not bypass it. Cancelled runs and runs with a recorded pending stop lose run-scoped API write authority, while reads remain available for diagnostics. This applies to ordinary tasks as well as conversations. Task and interaction mutations recheck that authority in the write transaction, so a cancelled run cannot overwrite a recovery disposition with a late Done or resolve an interaction after revocation. A task handoff that intentionally stops its own run can commit only with a server receipt tied to that exact request. Direct sandbox CLI adapters such as Grok register cancellation before preparation and keep ownership until host-owned termination is verified, including a sandbox acquired before adapter registration. A failed stop does not acknowledge cancellation or abandon an outstanding remote command. Interrupted workspace restore failures remain recorded for recovery; a stop receipt proves termination, not successful file restoration. diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts index a781e8c408a..68f41a81e88 100644 --- a/server/src/services/environment-runtime.ts +++ b/server/src/services/environment-runtime.ts @@ -1,4 +1,4 @@ -import { allowLegacyShutdownWorkspaceCleanup } from "./legacy-shutdown-workspace-settlement.js"; +import { allowLegacyShutdownWorkspaceCleanup, legacyShutdownWorkspaceResourceProtected } from "./legacy-shutdown-workspace-settlement.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"; @@ -1944,6 +1944,9 @@ function createSandboxEnvironmentDriver( lease.metadata?.agentId === input.agentId, ) : []; + for (let index = reusableCandidateLeases.length - 1; index >= 0; index--) { + if (await legacyShutdownWorkspaceResourceProtected(db, reusableCandidateLeases[index]!)) reusableCandidateLeases.splice(index, 1); + } const reusableExistingLeases = reusableCandidateLeases.filter((lease) => reusableSandboxLeaseScopeMatches({ lease, @@ -2359,6 +2362,9 @@ function createSandboxEnvironmentDriver( lease.metadata?.agentId === input.agentId, ) : []; + for (let index = reusableCandidateLeases.length - 1; index >= 0; index--) { + if (await legacyShutdownWorkspaceResourceProtected(db, reusableCandidateLeases[index]!)) reusableCandidateLeases.splice(index, 1); + } const reusableExistingLeases = reusableCandidateLeases.filter((lease) => reusableSandboxLeaseScopeMatches({ lease, @@ -3328,6 +3334,7 @@ function createSandboxEnvironmentDriver( lease: EnvironmentLease; failureReason: string; }): Promise { + if (await legacyShutdownWorkspaceResourceProtected(db, input.lease)) return null; let cleanupStatus: "success" | "failed" = "success"; let termination: ReturnType; const metadata = input.lease.metadata ?? {}; @@ -4069,7 +4076,9 @@ export function environmentRuntimeService( const released: EnvironmentRuntimeLeaseRecord[] = []; for (let leaseRow of leaseRows) { try { - if (!(await allowLegacyShutdownWorkspaceCleanup(db, leaseRow))) continue; + if (!(await allowLegacyShutdownWorkspaceCleanup(db, leaseRow, new Date(), { + ownerStopOnly: cancelActiveWork === true && providerResourceDisposition === "stop_and_retain", + }))) continue; if (leaseRow.metadata?.legacyShutdownWorkspaceSettlement) { leaseRow = (await db.select().from(environmentLeases).where(and( eq(environmentLeases.id, leaseRow.id), eq(environmentLeases.companyId, leaseRow.companyId), diff --git a/server/src/services/heartbeat/recovery.test.ts b/server/src/services/heartbeat/recovery.test.ts index fbf9d322f35..2850237f9f4 100644 --- a/server/src/services/heartbeat/recovery.test.ts +++ b/server/src/services/heartbeat/recovery.test.ts @@ -4,13 +4,13 @@ import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environ import { eq } from "drizzle-orm"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; -import { environmentRuntimeService } from "../environment-runtime.js"; +import { classifyEnvironmentCapabilities, environmentRuntimeService } from "../environment-runtime.js"; import { environmentService } from "../environments.js"; import { createHeartbeatRecovery, type HeartbeatRecoveryDependencies } from "./recovery.js"; import type { HotRestartIntent } from "../hot-restart.js"; import type { NativeRestartRecoveryClaim, NativeRestartRecoveryDisposition } from "../native-runtime/index.js"; import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "../native-runtime/native-runner-ownership.js"; -import { allowLegacyShutdownWorkspaceCleanup, beginLegacyShutdownWorkspaceSettlement } from "../legacy-shutdown-workspace-settlement.js"; +import { allowLegacyShutdownWorkspaceCleanup, beginLegacyShutdownWorkspaceSettlement, finishLegacyShutdownWorkspaceSettlement, legacyShutdownWorkspaceResourceProtected, sweepLegacyShutdownWorkspaceSettlements } from "../legacy-shutdown-workspace-settlement.js"; import { adapterExecutionControls, createAdapterExecutionControl } from "../adapter-execution-control.js"; type Run = typeof heartbeatRuns.$inferSelect; @@ -73,7 +73,7 @@ function callbacks(db: Db) { terminateHeartbeatRunProcess: vi.fn(async () => undefined), mergeRunStopMetadataForAgent: vi.fn((_agent, _outcome, options) => options?.resultJson ?? null), classifyAndPersistRunLiveness: vi.fn(async run => run), - releaseEnvironmentLeasesForRun: vi.fn(async () => undefined), + releaseEnvironmentLeasesForRun: vi.fn(async () => undefined), acknowledgeRemoteStop: vi.fn(async () => undefined), resumeRemoteStopComments: vi.fn(async () => undefined), dispatchPendingNativeStatusWakeups: vi.fn(async () => undefined), @@ -275,6 +275,106 @@ describePostgres("heartbeat recovery module ownership", () => { } }); + async function seedShutdownSource() { + const run = await seedRun(); + const [lease] = await db.insert(environmentLeases).values({ companyId: run.companyId, heartbeatRunId: run.id, + issueId: run.issueId, status: "active", provider: "daytona", providerLeaseId: randomUUID(), leasePolicy: "ephemeral", + metadata: { driver: "sandbox", sandboxProviderPlugin: true, pluginId: "fixture-plugin", remoteCwd: "/home/daytona/workspace" } }).returning(); + await beginLegacyShutdownWorkspaceSettlement(db, run, new Date(Date.now() + 30_000)); + return { run, lease }; + } + async function deleteShutdownSource(f: Awaited>) { + await db.delete(environmentLeases).where(eq(environmentLeases.id, f.lease.id)); + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.run.issueId!)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)); + adapterExecutionControls.delete(f.run.id); + } + + it("does not turn a stale pending snapshot into a repair hold after settlement", async () => { + const f = await seedShutdownSource(); + try { + const old = (await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]; + await db.update(heartbeatRuns).set({ status: "interrupted", contextSnapshot: { issueId: f.run.issueId }, resultJson: { workspaceRestored: true } }).where(eq(heartbeatRuns.id, f.run.id)); + await finishLegacyShutdownWorkspaceSettlement(db, f.run); + const single = createDb(database.connectionString, { maxConnections: 1 }); + try { expect(await allowLegacyShutdownWorkspaceCleanup(single, old, new Date(Date.now() + 60_000))).toBe(true); } + finally { await single.$client.end({ timeout: 1 }); } + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]) + .toMatchObject({ status: "active", leasePolicy: "ephemeral", metadata: { legacyShutdownWorkspaceSettlement: { state: "settled" } } }); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.run.issueId!))).toHaveLength(0); + } finally { await deleteShutdownSource(f); } + }); + + it("allows the aborted owner to stop and retain its command while excluding outside cleanup", async () => { + const f = await seedShutdownSource(); + const control = createAdapterExecutionControl(); control.controller.abort(); + adapterExecutionControls.set(f.run.id, control); + const stop = vi.fn(async () => ({ providerLeaseId: f.lease.providerLeaseId, state: "stopped" })); + const release = vi.fn(async () => null); + const runtime = environmentRuntimeService(db, { drivers: [{ driver: "sandbox", resolveCapabilities: async () => classifyEnvironmentCapabilities({}), + acquireRunLease: async () => { throw new Error("Unexpected acquire"); }, releaseRunLease: release, + retryPendingSandboxTeardown: stop }] }); + try { + await runtime.releaseRunLeases(f.run.id, "released", undefined, "stop_and_retain", false); + expect(stop).not.toHaveBeenCalled(); + await runtime.releaseRunLeases(f.run.id, "released", undefined, "stop_and_retain", true); + expect(stop).toHaveBeenCalledOnce(); expect(release).not.toHaveBeenCalled(); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]) + .toMatchObject({ status: "released", cleanupStatus: "success", metadata: { remoteExecutionTermination: { state: "stopped" }, + sandboxStopAndRetainReceipt: { leaseId: f.lease.id } } }); + } finally { control.finish(); await deleteShutdownSource(f); } + }); + + it.each(["ephemeral", "reuse_by_environment"] as const)("recovers a stopped %s source after its shutdown controller disappears", async leasePolicy => { + const f = await seedShutdownSource(); + await db.update(environmentLeases).set({ leasePolicy }).where(eq(environmentLeases.id, f.lease.id)); + const control = createAdapterExecutionControl(); control.controller.abort(); adapterExecutionControls.set(f.run.id, control); + const stop = vi.fn(async () => ({ providerLeaseId: f.lease.providerLeaseId, state: "stopped" })); + const runtime = environmentRuntimeService(db, { drivers: [{ driver: "sandbox", resolveCapabilities: async () => classifyEnvironmentCapabilities({}), + acquireRunLease: async () => { throw new Error("Unexpected acquire"); }, releaseRunLease: vi.fn(), retryPendingSandboxTeardown: stop }] }); + try { + await runtime.releaseRunLeases(f.run.id, "released", undefined, "stop_and_retain", true); + adapterExecutionControls.delete(f.run.id); // SIGKILL before export/finally settled. + await db.update(heartbeatRuns).set({ status: "interrupted", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.run.id)); + const [source] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)); + expect(source.status).toBe("released"); + // An old reuse receipt must not bypass the current allocation's fence. + expect(await legacyShutdownWorkspaceResourceProtected(db, { provider: source.provider, providerLeaseId: source.providerLeaseId })).toBe(true); + await sweepLegacyShutdownWorkspaceSettlements(db, new Date(Date.now() + 60_000)); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]) + .toMatchObject({ status: "released", leasePolicy: "retain_on_failure", metadata: { + legacyShutdownWorkspaceSettlement: { state: "expired" }, workspaceRestoreRecovery: { runId: f.run.id } } }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0].resultJson) + .toMatchObject({ workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: { leaseIds: [f.lease.id] } }); + expect(await legacyShutdownWorkspaceResourceProtected(db, source)).toBe(true); + expect(stop).toHaveBeenCalledOnce(); + } finally { control.finish(); await deleteShutdownSource(f); } + }); + + it("retries lease release when ordinary completion wins the shutdown status race", async () => { + const f = await seedShutdownSource(); const control = createAdapterExecutionControl(); + adapterExecutionControls.set(f.run.id, control); + const deps = callbacks(db); + deps.setRunStatusIfRunning.mockImplementation(async () => { + await db.update(heartbeatRuns).set({ status: "succeeded", resultJson: { workspaceRestored: true } }).where(eq(heartbeatRuns.id, f.run.id)); + // The adapter's first release was deferred by the fence; its finally ended. + control.finish(); return { updated: false, run: null }; + }); + deps.getRun.mockImplementation(async id => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0] ?? null); + deps.releaseEnvironmentLeasesForRun.mockImplementation(async input => { + expect(input.status).toBe("succeeded"); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0].metadata) + .toMatchObject({ legacyShutdownWorkspaceSettlement: { state: "settled" } }); + await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success", releasedAt: new Date() }).where(eq(environmentLeases.id, f.lease.id)); + }); + try { + await createHeartbeatRecovery(db, deps).drainRunningRunsForShutdown("SIGTERM", new Date(), [f.run.id]); + expect(deps.releaseEnvironmentLeasesForRun).toHaveBeenCalledOnce(); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0].status).toBe("released"); + expect(deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); + } finally { control.finish(); await deleteShutdownSource(f); } + }); + it("pins an unjoined sandbox restore for repair before bounded shutdown cleanup", async () => { const run = await seedRun(); await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: run.issueId } }).where(eq(heartbeatRuns.id, run.id)); diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index b0e1e9a0c12..47a043db81a 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -73,7 +73,7 @@ import { } from "../hot-restart.js"; import { serverVersion } from "../../version.js"; import { adapterExecutionControls, waitForAdapterStop } from "../adapter-execution-control.js"; -import { allowLegacyShutdownWorkspaceCleanup, beginLegacyShutdownWorkspaceSettlement, finishLegacyShutdownWorkspaceSettlement } from "../legacy-shutdown-workspace-settlement.js"; +import { allowLegacyShutdownWorkspaceCleanup, beginLegacyShutdownWorkspaceSettlement, finishLegacyShutdownWorkspaceSettlement, sweepLegacyShutdownWorkspaceSettlements } from "../legacy-shutdown-workspace-settlement.js"; import type { environmentService } from "../environments.js"; import type { environmentRuntimeService, ProviderResourceDisposition } from "../environment-runtime.js"; @@ -1211,6 +1211,11 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD try { await waitForAdapterStop(control.settled, Math.max(1, settlementDeadline.getTime() - Date.now())); await finishLegacyShutdownWorkspaceSettlement(db, run); + const current = await getRun(run.id, { includeExecutionEvidence: true }); + if (current && HEARTBEAT_RUN_TERMINAL_STATUSES.some(status => status === current.status)) { + await releaseEnvironmentLeasesForRun({ runId: current.id, companyId: current.companyId, + agentId: current.agentId, status: current.status, failureReason: current.error ?? undefined }); + } } catch { /* The durable fence retains this source after controller loss. */ } } return; @@ -2436,6 +2441,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD // pending_cleanup sweep, so this tick can stop the recovered sandbox. // Isolate the sweep so its failure never hides the reaper result. try { + await sweepLegacyShutdownWorkspaceSettlements(db); const orphanedActiveLeaseSweep = await sweepOrphanedActiveLeases({ backoffMs: staleThresholdMs, }); diff --git a/server/src/services/legacy-shutdown-workspace-settlement.ts b/server/src/services/legacy-shutdown-workspace-settlement.ts index 4e0507d2d28..76b33c12687 100644 --- a/server/src/services/legacy-shutdown-workspace-settlement.ts +++ b/server/src/services/legacy-shutdown-workspace-settlement.ts @@ -1,13 +1,14 @@ -import { and, eq, ne, or, sql } from "drizzle-orm"; -import { environmentLeases, heartbeatRuns, type Db } from "@paperclipai/db"; -import { terminalizeLegacyExecution } from "./legacy-execution-recovery.js"; +import { and, eq, gt, inArray, ne, or, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { adapterExecutionControls } from "./adapter-execution-control.js"; import { legacyControllerBootId } from "./legacy-controller-lease.js"; +import { LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "./workspace-restore-recovery-state.js"; const SCHEMA = "paperclip.legacy-shutdown-workspace-settlement.v1"; type Lease = Pick; type Run = Pick; -function pending(lease: Lease) { +export function pendingLegacyShutdownWorkspaceSettlement(lease: Lease) { const value = lease.metadata?.legacyShutdownWorkspaceSettlement; if (!value || typeof value !== "object" || Array.isArray(value)) return null; const marker = value as Record; @@ -15,6 +16,29 @@ function pending(lease: Lease) { && typeof marker.deadlineAt === "string" ? marker : null; } +/** Historical reuse rows may name the same allocation as the fenced source. */ +export async function legacyShutdownWorkspaceResourceProtected(db: Db, + lease: Pick) { + if (!lease.provider || !lease.providerLeaseId) return false; + const [protectedLease] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( + eq(environmentLeases.provider, lease.provider), eq(environmentLeases.providerLeaseId, lease.providerLeaseId), + or(sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'schema' = ${SCHEMA} + and ${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'state' = 'pending'`, + sql`${environmentLeases.metadata}->'workspaceRestoreRecovery'->>'schema' = ${LEGACY_WORKSPACE_RECOVERY_SCHEMA}`), + )).limit(1); + return !!protectedLease; +} + +/** Released stop receipts still need reconciliation if export never settled. */ +export async function sweepLegacyShutdownWorkspaceSettlements(db: Db, now = new Date()) { + const rows = await db.select().from(environmentLeases).where(and( + sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'schema' = ${SCHEMA}`, + sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'state' = 'pending'`, + sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'deadlineAt' <= ${now.toISOString()}`, + )).orderBy(sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'deadlineAt'`).limit(50); + for (const lease of rows) await allowLegacyShutdownWorkspaceCleanup(db, lease, now); +} + /** Commit the fence while the run is still live, before exposing interruption. */ export async function beginLegacyShutdownWorkspaceSettlement(db: Db, run: Run, deadlineAt: Date) { await db.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || @@ -37,26 +61,67 @@ export async function finishLegacyShutdownWorkspaceSettlement(db: Db, run: Run, } /** A restart or another cleanup worker must never infer saved files from timeout. */ -export async function allowLegacyShutdownWorkspaceCleanup(db: Db, lease: Lease, now = new Date()) { - const marker = pending(lease); - if (!marker) return true; - const deadline = Date.parse(marker.deadlineAt as string); - if (!Number.isFinite(deadline) || deadline > now.getTime()) return false; - const [run] = await db.select().from(heartbeatRuns).where(and( - eq(heartbeatRuns.companyId, lease.companyId), eq(heartbeatRuns.id, lease.heartbeatRunId!), - eq(heartbeatRuns.runtimeMode, "legacy"), - )); - if (!run) return false; - // The old container may have been killed before its timeout handler. Pin the - // exact source and repair hold before permitting any provider cleanup. - const preserved = await terminalizeLegacyExecution({ db, run, status: run.status, - recordRestoreFailureOnly: true, patch: { resultJson: { workspaceRestoreFailure: "restore_failed" } } }); - if (!preserved) return false; - await db.update(environmentLeases).set({ metadata: sql`jsonb_set(${environmentLeases.metadata}, - '{legacyShutdownWorkspaceSettlement,state}', '"expired"'::jsonb)` }).where(and( - eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, lease.companyId), - eq(environmentLeases.heartbeatRunId, run.id), - sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement' = ${JSON.stringify(marker)}::jsonb`, - )); - return true; +export async function allowLegacyShutdownWorkspaceCleanup(db: Db, lease: Lease, now = new Date(), + options: { ownerStopOnly?: boolean } = {}) { + if (!pendingLegacyShutdownWorkspaceSettlement(lease)) return true; + return db.transaction(async tx => { + const [hint] = await tx.select().from(environmentLeases).where(and( + eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, lease.companyId), + eq(environmentLeases.heartbeatRunId, lease.heartbeatRunId!), + )); + if (!hint) return false; + if (!pendingLegacyShutdownWorkspaceSettlement(hint)) return true; + // Match the terminal recorder's issue -> run -> lease lock order. Settlement + // and expiry compete on the current lease row, not the caller's old snapshot. + if (hint.issueId) await tx.select({ id: issues.id }).from(issues).where(and( + eq(issues.id, hint.issueId), eq(issues.companyId, lease.companyId))).for("update"); + const [run] = await tx.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, lease.companyId), eq(heartbeatRuns.id, lease.heartbeatRunId!), + eq(heartbeatRuns.runtimeMode, "legacy"), + )).for("update"); + const [current] = await tx.select().from(environmentLeases).where(and( + eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, lease.companyId), + eq(environmentLeases.heartbeatRunId, lease.heartbeatRunId!), + )).for("update"); + if (!run || !current) return false; + const marker = pendingLegacyShutdownWorkspaceSettlement(current); + if (!marker) return true; + // Stopping and retaining the exact owner's command is a prerequisite for + // some adapters to settle. This exception never permits provider destruction. + if (options.ownerStopOnly && marker.controllerBootId === legacyControllerBootId + && adapterExecutionControls.get(run.id)?.controller.signal.aborted) return true; + const deadline = Date.parse(marker.deadlineAt as string); + if (!Number.isFinite(deadline) || deadline > now.getTime()) return false; + // A killed container cannot certify export. Preserve source and hold in + // this same transaction before any worker may perform provider cleanup. + if (current.status !== "active") { + const { hasConfirmedSandboxStopAndRetain, readStopOnlyCleanup } = await import("./sandbox-stop-and-retain.js"); + if (!(current.status === "released" && hasConfirmedSandboxStopAndRetain(current)) + && !(current.status === "pending_cleanup" && readStopOnlyCleanup(current))) return false; + // The shutdown marker was committed on this exact active source before + // cancellation. A stop receipt does not certify the later file export. + const [competing] = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and( + ne(environmentLeases.id, current.id), eq(environmentLeases.provider, current.provider!), + eq(environmentLeases.providerLeaseId, current.providerLeaseId!), + or(inArray(environmentLeases.status, ["active", "pending_cleanup"]), + gt(environmentLeases.acquiredAt, current.acquiredAt)), + )).limit(1); + if (competing) return false; + await tx.update(environmentLeases).set({ leasePolicy: "retain_on_failure", + metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({ workspaceRestoreRecovery: { + schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, runId: run.id, + } })}::jsonb`, + }).where(eq(environmentLeases.id, current.id)); + } + const { terminalizeLegacyExecution } = await import("./legacy-execution-recovery.js"); + const preserved = await terminalizeLegacyExecution({ db: tx as unknown as Db, run, status: run.status, + recordRestoreFailureOnly: true, patch: { resultJson: { workspaceRestoreFailure: "restore_failed" } } }); + if (!preserved) return false; + await tx.update(environmentLeases).set({ metadata: sql`jsonb_set(${environmentLeases.metadata}, + '{legacyShutdownWorkspaceSettlement,state}', '"expired"'::jsonb)` }).where(and( + eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, lease.companyId), + eq(environmentLeases.heartbeatRunId, run.id), + )); + return true; + }); }