mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
fix: fence workspace settlement across controller shutdown
Protect unfinished exports with a durable lease marker, retain exact sources if the controller dies, settle runs in one shared window, and give Compose enough shutdown grace. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
1624f715bd
commit
3b919b0bd8
7 files changed
+192
-10
No files matched your search
@@ -1137,7 +1137,13 @@ An interrupted conversation does not permanently block its task. For local conve
|
||||
Shutdown, process loss, and provider failure use the existing durable failure retry counter and delay. Ordinary failure recovery permits at most two automatic retries in a failure chain. Accepted-interaction infrastructure recovery retains its existing bounded policy. Repeated scheduler visits reuse the same successor; restarting the server does not reset the counter. After exhaustion, automatic attempts stop. A new explicit user message can start a fresh run and failure budget. Productive max-turn continuation and confirmed workspace waits keep their separate existing semantics.
|
||||
|
||||
Graceful shutdown interrupts an owned legacy adapter through its cancellation
|
||||
control, then waits up to 30 seconds for provider stop and adapter settlement.
|
||||
control, then waits within one shared 30-second window for provider stop and
|
||||
adapter settlement across all affected runs. Before interruption becomes visible,
|
||||
it commits a settlement fence on the exact sandbox lease. Cleanup on this server
|
||||
or another server defers while that fence is pending. If the controller dies,
|
||||
cleanup records exact stop-only retention and a repair hold after the deadline,
|
||||
without claiming a successful restore. The shipped Compose services allow 90
|
||||
seconds for settlement and subsequent shutdown cleanup.
|
||||
The sandbox lease remains available during workspace export and instruction
|
||||
collection. Lease release and recovery classification follow settlement and use
|
||||
the current execution evidence. If settlement exceeds the deadline with an
|
||||
|
||||
@@ -16,6 +16,8 @@ services:
|
||||
# backstop if something leaks anyway — the container hits its own limit and
|
||||
# dies visibly rather than starving the host of pids.
|
||||
pids_limit: 2048
|
||||
# Includes the shared 30s adapter-settlement window and final cleanup.
|
||||
stop_grace_period: 90s
|
||||
ports:
|
||||
- "${PAPERCLIP_PORT:-3100}:3100"
|
||||
environment:
|
||||
|
||||
@@ -28,6 +28,8 @@ services:
|
||||
# this container hits its own ceiling and dies visibly rather than starving
|
||||
# the whole host of pids.
|
||||
pids_limit: 2048
|
||||
# Includes the shared 30s adapter-settlement window and final cleanup.
|
||||
stop_grace_period: 90s
|
||||
ports:
|
||||
- "3100:3100"
|
||||
environment:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { allowLegacyShutdownWorkspaceCleanup } 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";
|
||||
@@ -3888,6 +3889,7 @@ export function environmentRuntimeService(
|
||||
scopeCondition?: ReturnType<typeof and>;
|
||||
failureReason: string;
|
||||
}): Promise<EnvironmentLease | null> {
|
||||
if (!(await allowLegacyShutdownWorkspaceCleanup(db, input.leaseRow))) return null;
|
||||
const now = new Date();
|
||||
const attemptId = randomUUID();
|
||||
// Persist recovery ownership before any provider work. Re-check scope and
|
||||
@@ -4065,8 +4067,14 @@ export function environmentRuntimeService(
|
||||
// error through `onLeaseReleaseError` for its log path. Keep the order
|
||||
// serial.
|
||||
const released: EnvironmentRuntimeLeaseRecord[] = [];
|
||||
for (const leaseRow of leaseRows) {
|
||||
for (let leaseRow of leaseRows) {
|
||||
try {
|
||||
if (!(await allowLegacyShutdownWorkspaceCleanup(db, leaseRow))) continue;
|
||||
if (leaseRow.metadata?.legacyShutdownWorkspaceSettlement) {
|
||||
leaseRow = (await db.select().from(environmentLeases).where(and(
|
||||
eq(environmentLeases.id, leaseRow.id), eq(environmentLeases.companyId, leaseRow.companyId),
|
||||
)))[0] ?? leaseRow;
|
||||
}
|
||||
const environment = leaseRow.environmentId
|
||||
? await environmentsSvc.getById(leaseRow.environmentId)
|
||||
: null;
|
||||
@@ -4211,6 +4219,14 @@ export function environmentRuntimeService(
|
||||
environment: Environment | null;
|
||||
lease: EnvironmentLease;
|
||||
}): Promise<unknown> {
|
||||
if (!(await allowLegacyShutdownWorkspaceCleanup(db, input.lease))) {
|
||||
throw new Error("Shutdown workspace settlement is still pending.");
|
||||
}
|
||||
if (input.lease.metadata?.legacyShutdownWorkspaceSettlement) {
|
||||
const current = await environmentsSvc.getLeaseById(input.lease.id);
|
||||
if (!current) throw new Error("Shutdown workspace source is unavailable.");
|
||||
input = { ...input, lease: current };
|
||||
}
|
||||
const driver = requireDriverKey(getLeaseDriverKey(input.lease, input.environment));
|
||||
if (!driver.retryPendingSandboxTeardown) {
|
||||
throw new Error(
|
||||
@@ -4415,6 +4431,12 @@ export function environmentRuntimeService(
|
||||
},
|
||||
|
||||
async destroyRunLease(input: EnvironmentDriverLeaseInput): Promise<EnvironmentLease | null> {
|
||||
if (input.lease.metadata?.legacyShutdownWorkspaceSettlement) {
|
||||
if (!(await allowLegacyShutdownWorkspaceCleanup(db, input.lease))) return null;
|
||||
const current = await environmentsSvc.getLeaseById(input.lease.id);
|
||||
if (!current || hasStopOnlyCleanup(current)) return null;
|
||||
input = { ...input, lease: current };
|
||||
}
|
||||
const driver = requireDriverKey(getLeaseDriverKey(input.lease, input.environment));
|
||||
if (!driver.destroyRunLease) {
|
||||
throw new Error(`Environment driver "${driver.driver}" does not support lease destroy.`);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createHeartbeatRecovery, type HeartbeatRecoveryDependencies } from "./r
|
||||
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 { adapterExecutionControls, createAdapterExecutionControl } from "../adapter-execution-control.js";
|
||||
|
||||
type Run = typeof heartbeatRuns.$inferSelect;
|
||||
@@ -218,6 +219,62 @@ describePostgres("heartbeat recovery module ownership", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("starts all owned shutdown cancellations within one settlement window", async () => {
|
||||
const runs = await Promise.all([seedRun(), seedRun()]);
|
||||
const controls = runs.map(run => {
|
||||
const control = createAdapterExecutionControl(); adapterExecutionControls.set(run.id, control); return control;
|
||||
});
|
||||
const deps = callbacks(db);
|
||||
deps.setRunStatusIfRunning.mockImplementation(async (id, status, patch) => {
|
||||
const [updated] = await db.update(heartbeatRuns).set({ ...patch, status }).where(eq(heartbeatRuns.id, id)).returning();
|
||||
return { updated: true, run: updated };
|
||||
});
|
||||
const drain = createHeartbeatRecovery(db, deps).drainRunningRunsForShutdown("SIGTERM", new Date(), runs.map(run => run.id));
|
||||
try {
|
||||
await vi.waitFor(() => expect(controls.every(control => control.controller.signal.aborted)).toBe(true));
|
||||
expect(deps.releaseEnvironmentLeasesForRun).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
controls.forEach(control => control.finish());
|
||||
await drain;
|
||||
for (const run of runs) { adapterExecutionControls.delete(run.id); await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); }
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["ephemeral", "reuse_by_environment"] as const)("protects a %s export from another server and pins it after controller loss", async leasePolicy => {
|
||||
const run = await seedRun();
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: run.issueId } }).where(eq(heartbeatRuns.id, run.id));
|
||||
const [lease] = await db.insert(environmentLeases).values({ companyId: run.companyId, heartbeatRunId: run.id,
|
||||
issueId: run.issueId, status: "active", provider: "daytona", providerLeaseId: randomUUID(), leasePolicy,
|
||||
metadata: { driver: "sandbox", sandboxProviderPlugin: true, pluginId: "fixture-plugin", remoteCwd: "/home/daytona/workspace" } }).returning();
|
||||
try {
|
||||
const deadline = new Date(Date.now() + 30_000);
|
||||
await beginLegacyShutdownWorkspaceSettlement(db, run, deadline);
|
||||
await db.update(heartbeatRuns).set({ status: "interrupted", errorCode: "server_shutdown_interrupted", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.id));
|
||||
const foreignDeps = callbacks(db);
|
||||
const foreign = createHeartbeatRecovery(db, foreignDeps);
|
||||
expect(await foreign.sweepOrphanedActiveLeases({ backoffMs: 0 })).toMatchObject({ recovered: 0 });
|
||||
expect(await environmentRuntimeService(db).releaseRunLeases(run.id)).toEqual([]);
|
||||
await db.update(environmentLeases).set({ status: "pending_cleanup" }).where(eq(environmentLeases.id, lease.id));
|
||||
expect(await foreign.sweepPendingCleanupLeases({ backoffMs: 0 })).toMatchObject({ destroyed: 0 });
|
||||
await db.update(environmentLeases).set({ status: "active" }).where(eq(environmentLeases.id, lease.id));
|
||||
let source = (await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0];
|
||||
expect(source.status).toBe("active");
|
||||
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, run.issueId!))).toHaveLength(0);
|
||||
// No local adapter map or timeout handler survives a container SIGKILL.
|
||||
expect(await allowLegacyShutdownWorkspaceCleanup(db, source, new Date(deadline.getTime() + 1))).toBe(true);
|
||||
source = (await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0];
|
||||
expect(source).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure",
|
||||
metadata: { legacyShutdownWorkspaceSettlement: { state: "expired" }, sandboxStopAndRetain: { leaseId: lease.id } } });
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0].resultJson)
|
||||
.toMatchObject({ workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: { leaseIds: [lease.id] } });
|
||||
expect(await foreign.sweepOrphanedActiveLeases({ backoffMs: 0 })).toMatchObject({ recovered: 0 });
|
||||
} finally {
|
||||
await db.delete(environmentLeases).where(eq(environmentLeases.id, lease.id));
|
||||
await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, run.issueId!));
|
||||
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id));
|
||||
}
|
||||
});
|
||||
|
||||
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));
|
||||
@@ -226,6 +283,8 @@ describePostgres("heartbeat recovery module ownership", () => {
|
||||
metadata: { driver: "sandbox", sandboxProviderPlugin: true, pluginId: "fixture-plugin", remoteCwd: "/home/daytona/workspace" } }).returning();
|
||||
const deps = callbacks(db);
|
||||
deps.setRunStatusIfRunning.mockImplementation(async (id, status, patch) => {
|
||||
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0].metadata)
|
||||
.toMatchObject({ legacyShutdownWorkspaceSettlement: { state: "pending", runId: run.id } });
|
||||
const [updated] = await db.update(heartbeatRuns).set({ ...patch, status }).where(eq(heartbeatRuns.id, id)).returning();
|
||||
return { updated: true, run: updated };
|
||||
});
|
||||
|
||||
@@ -73,6 +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 type { environmentService } from "../environments.js";
|
||||
import type { environmentRuntimeService, ProviderResourceDisposition } from "../environment-runtime.js";
|
||||
@@ -1087,12 +1088,13 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
const retryRunIds: string[] = [];
|
||||
const restartSuspendedRunIds: string[] = [];
|
||||
|
||||
for (const { run, agent } of activeRuns) {
|
||||
const settlementDeadline = new Date(Date.now() + 30_000);
|
||||
const settlements = await Promise.allSettled(activeRuns.map(async ({ run, agent }) => {
|
||||
// Shutdown owns only this boot's legacy executions. Expired foreign
|
||||
// owners belong to the reaper, not another container's drain.
|
||||
if (run.runtimeMode === "legacy" && run.controllerBootId &&
|
||||
run.controllerBootId !== legacyControllerBootId) continue;
|
||||
if (isNativeRunnerOwnershipHeld(run)) continue;
|
||||
run.controllerBootId !== legacyControllerBootId) return;
|
||||
if (isNativeRunnerOwnershipHeld(run)) return;
|
||||
if (
|
||||
run.runtimeMode === "native" &&
|
||||
agent.adapterType === "paperclip_runner"
|
||||
@@ -1153,11 +1155,12 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
},
|
||||
});
|
||||
restartSuspendedRunIds.push(run.id);
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
const message = `Interrupted by graceful server shutdown (${signal})`;
|
||||
const running = runningProcesses.get(run.id);
|
||||
const control = run.runtimeMode === "legacy" ? adapterExecutionControls.get(run.id) : undefined;
|
||||
if (control) await beginLegacyShutdownWorkspaceSettlement(db, run, settlementDeadline);
|
||||
try {
|
||||
if (run.runtimeMode === "native") {
|
||||
await cancelHeartbeatNativeRun({
|
||||
@@ -1201,7 +1204,17 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!interruptedStatus.updated || !interruptedStatus.run) continue;
|
||||
if (!interruptedStatus.updated || !interruptedStatus.run) {
|
||||
// A competing terminal write does not prove the owned adapter settled.
|
||||
if (control) {
|
||||
control.controller.abort(new Error(message));
|
||||
try {
|
||||
await waitForAdapterStop(control.settled, Math.max(1, settlementDeadline.getTime() - Date.now()));
|
||||
await finishLegacyShutdownWorkspaceSettlement(db, run);
|
||||
} catch { /* The durable fence retains this source after controller loss. */ }
|
||||
}
|
||||
return;
|
||||
}
|
||||
let interrupted = interruptedStatus.run;
|
||||
if (control) {
|
||||
// Keep the exact lease open while its adapter stops the provider and
|
||||
@@ -1209,10 +1222,11 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
// must not race the adapter's git export or instruction collection.
|
||||
control.controller.abort(new Error(message));
|
||||
try {
|
||||
await waitForAdapterStop(control.settled, 30_000, {
|
||||
await waitForAdapterStop(control.settled, Math.max(1, settlementDeadline.getTime() - Date.now()), {
|
||||
runId: run.id, adapterType: agent.adapterType, runtimeMode: run.runtimeMode,
|
||||
abortRequested: true,
|
||||
}, control);
|
||||
await finishLegacyShutdownWorkspaceSettlement(db, run);
|
||||
} catch {
|
||||
logger.warn({ runId: run.id }, "Shutdown adapter settlement timed out; retaining the sandbox through normal cleanup");
|
||||
const [sandbox] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
||||
@@ -1225,8 +1239,11 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
// An unjoined restore cannot certify saved files. Record the exact
|
||||
// stop-only sources and repair hold before provider cleanup starts.
|
||||
const current = await getRun(run.id, { includeExecutionEvidence: true });
|
||||
if (current) await terminalizeLegacyExecution({ db, run: current, status: current.status,
|
||||
recordRestoreFailureOnly: true, patch: { resultJson: { workspaceRestoreFailure: "restore_failed" } } });
|
||||
if (current) {
|
||||
const preserved = await terminalizeLegacyExecution({ db, run: current, status: current.status,
|
||||
recordRestoreFailureOnly: true, patch: { resultJson: { workspaceRestoreFailure: "restore_failed" } } });
|
||||
if (preserved) await finishLegacyShutdownWorkspaceSettlement(db, run, "expired");
|
||||
}
|
||||
}
|
||||
if (runningProcesses.get(run.id) === running && running) {
|
||||
await terminateHeartbeatRunProcess({ pid: running.child.pid, processGroupId: running.processGroupId,
|
||||
@@ -1280,6 +1297,10 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),
|
||||
});
|
||||
interruptedRunIds.push(interrupted.id);
|
||||
}));
|
||||
for (const [index, settlement] of settlements.entries()) {
|
||||
if (settlement.status === "rejected") logger.warn({ runId: activeRuns[index]!.run.id,
|
||||
errorKind: "shutdown_settlement_failed" }, "Shutdown settlement failed; durable cleanup protection remains in place");
|
||||
}
|
||||
|
||||
if (interruptedRunIds.length > 0) {
|
||||
@@ -1473,6 +1494,10 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
|
||||
let recovered = 0;
|
||||
for (const { lease } of rows) {
|
||||
if (!(await allowLegacyShutdownWorkspaceCleanup(db, lease))) {
|
||||
await deferOrphanedActiveLease(lease.id);
|
||||
continue;
|
||||
}
|
||||
// A provider resource id names one physical sandbox. A different lease
|
||||
// row can still hold that same resource in a live status, so this sweep
|
||||
// must not tear down a sandbox that a different lease still owns.
|
||||
@@ -1591,6 +1616,10 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
let capped = 0;
|
||||
for (const row of rows) {
|
||||
if (pendingCleanupAttemptsInFlight.has(row.id)) continue;
|
||||
if (!(await allowLegacyShutdownWorkspaceCleanup(db, row))) {
|
||||
await deferPendingCleanupLease(row.id);
|
||||
continue;
|
||||
}
|
||||
const metadata = { ...(row.metadata ?? {}) } as Record<string, unknown>;
|
||||
const attempts = readPendingCleanupRetryAttempts(metadata);
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
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 { legacyControllerBootId } from "./legacy-controller-lease.js";
|
||||
|
||||
const SCHEMA = "paperclip.legacy-shutdown-workspace-settlement.v1";
|
||||
type Lease = Pick<typeof environmentLeases.$inferSelect, "id" | "companyId" | "heartbeatRunId" | "metadata">;
|
||||
type Run = Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId">;
|
||||
|
||||
function pending(lease: Lease) {
|
||||
const value = lease.metadata?.legacyShutdownWorkspaceSettlement;
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const marker = value as Record<string, unknown>;
|
||||
return marker.schema === SCHEMA && marker.state === "pending" && marker.runId === lease.heartbeatRunId
|
||||
&& typeof marker.deadlineAt === "string" ? marker : null;
|
||||
}
|
||||
|
||||
/** 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) ||
|
||||
${JSON.stringify({ legacyShutdownWorkspaceSettlement: { schema: SCHEMA, state: "pending", runId: run.id,
|
||||
controllerBootId: legacyControllerBootId, deadlineAt: deadlineAt.toISOString() } })}::jsonb`,
|
||||
}).where(and(eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
|
||||
eq(environmentLeases.status, "active"), ne(environmentLeases.provider, "local"),
|
||||
or(sql`${environmentLeases.metadata}->>'driver' = 'sandbox'`, sql`${environmentLeases.metadata}->>'sandboxProviderPlugin' = 'true'`)));
|
||||
}
|
||||
|
||||
/** The owner joins settlement, or records exact retention before timeout cleanup. */
|
||||
export async function finishLegacyShutdownWorkspaceSettlement(db: Db, run: Run, state: "settled" | "expired" = "settled") {
|
||||
await db.update(environmentLeases).set({ metadata: sql`jsonb_set(${environmentLeases.metadata},
|
||||
'{legacyShutdownWorkspaceSettlement,state}', ${JSON.stringify(state)}::jsonb)` }).where(and(
|
||||
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
|
||||
sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'schema' = ${SCHEMA}`,
|
||||
sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'controllerBootId' = ${legacyControllerBootId}`,
|
||||
sql`${environmentLeases.metadata}->'legacyShutdownWorkspaceSettlement'->>'state' = 'pending'`,
|
||||
));
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
Reference in new issue
Block a user