mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 21:24:45 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agent runs execute on environment leases, and `createOwnedSandbox` records each sandbox creation so that a lost reply never creates a second sandbox > - The record key is company, environment, run and request key. The plugin request key is the environment fingerprint, so it is the same for every attempt of one run > - A same-run recovery can need a new environment after the first lease is closed with successful cleanup and a termination receipt > - The old record is still `attached` to the closed lease, so the recovery fails with "Sandbox creation has already transferred ownership" before the provider is called > - This pull request lets the creation fence accept the same stop proof that recovery already requires. A creation record whose sandbox is proven stopped becomes resolved, and a resolved record no longer holds its key > - The benefit is that same-run recovery gets one replacement sandbox, while unconfirmed cleanup still blocks a second sandbox ## Linked Issues or Issue Description Fixes #21214 Refs #20755. That pull request fixes the same failure with a different rule. It retries under a new key generation (`<key>#2`, `#3`, ...) when the recorded lease has ended, and it accepts any ended status, including `failed`, without a termination receipt. A lease whose cleanup is not confirmed can then produce a second sandbox while the first one can still run. This pull request keeps the original key and requires the same stop proof that Core uses elsewhere (`hasRemoteTerminationReceipt`). It does not add a key generation. ## What Changed - `server/src/services/sandbox-creation-operations.ts`: when `createOwnedSandbox` finds the key held by an `attached` operation whose lease is not active, it checks the same stop proof that same-run recovery requires before it acquires: `hasRemoteTerminationReceipt(resolveRemoteTerminationLease(lease))`, for the sandbox that this operation created (`creationProviderLeaseId`, or the lease's `providerLeaseId`). - With that proof, it runs the same admission transaction one more time. That transaction first marks the old operation `resolved` (`WHERE id AND state = 'attached' AND lease_id`), and then inserts the new operation. - Without that proof, it throws exactly as before. - The check covers every source of a stop receipt: `releaseLease`, the Runner `complete` operation (which writes receipts with direct SQL for reusable leases), stop-and-retain settlement, and the receipt that `resolveRemoteTerminationLease` derives for an expired reusable lease. - A task replacement can leave an earlier operation attached to a lease that now holds another sandbox. That operation is not proven and keeps its key. - Concurrent recoveries serialize on the row update. The second one updates nothing, finds the first one's unresolved operation through the partial index, and replays or refuses as before. There is one provider call. - Migration `0475_sandbox_creation_owner_unresolved.sql` recreates `sandbox_creation_operations_owner_idx` under the same name as a partial unique index (`state <> 'resolved'`). The drop and the create are in one migration transaction. The Drizzle schema matches. - The conflict lookup in `createOwnedSandbox` ignores resolved rows. An active attached lease is still replayed. Pending and `needs_reconciliation` rows still refuse. `releaseLease` does not change. - `doc/DATABASE.md` and `doc/idle-environment-cleanup.md` describe the operation lifecycle. ## Verification - `pnpm --filter @paperclipai/db generate` - `pnpm --filter @paperclipai/db typecheck` and `pnpm --filter @paperclipai/server typecheck` - `vitest run src/migration-snapshot-drift.test.ts` (db) - `vitest run src/__tests__/sandbox-creation-operations.test.ts`: 48/48. With the service change reverted, the 5 replacement tests fail. - The 9 other server test files that read `sandbox_creation_operations`, plus `environment-runtime.test.ts`: 564/564 - `pnpm check:migrations` passes New tests in `sandbox-creation-operations.test.ts`: - A stop receipt from `releaseLease` (sandbox driver, and the plugin driver through `acquireRunLease` in the #21214 sequence), from the `complete` operation's direct write on a retained reusable lease, and derived only from the destroyed successor of an expired reusable lease each let the next creation resolve the old operation and create exactly one replacement. A retry replays that replacement. These tests fail before the fix. - Failed cleanup, success without a receipt, a receipt for another lease or another provider task, a retained lease, and pending cleanup each still throw "transferred ownership" with no provider call. - An earlier task's operation that a task replacement left attached keeps its key. - Two concurrent recoveries make one provider call. This test fails before the fix. - Reapplying migration 0418 keeps the partial index. I did not run `pnpm verify` or the full suite locally. CI runs them. ## Risks - Migration: the drop and the rebuild of the index take an exclusive lock on `sandbox_creation_operations`. The table has one small row for each sandbox creation, so the lock is short. - Rolling deploy: the migration is marked `online_compatible`. The previous release uses an untargeted `ON CONFLICT DO NOTHING`, which also matches a partial unique index. Its conflict lookup has no state filter, so it can find a resolved row and throw. That fails closed and never creates a second sandbox. - A legacy runner-task operation without `creationProviderLeaseId` matches any lease it is attached to. Runner-task operations record this field before they attach, so this is only a theoretical gap. - An operation stays `attached` until the next creation with the same key checks it. This is the same as before when no recovery comes. - Stop-and-retain settlement is not tested directly. The shared receipt check covers it. - The fence is unchanged for every case without a stop receipt. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, sub-agents) and extended thinking. One sub-agent wrote the change. A second session reviewed it before this pull request. ## 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>
309 lines
21 KiB
TypeScript
309 lines
21 KiB
TypeScript
import { collectSecretRefPaths, isUuidSecretRef, parseSecretRefBindingObject, readConfigValueAtPath } from "./json-schema-secret-refs.js";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { and, eq, lte, ne, or, sql } from "drizzle-orm";
|
|
import { currentControllerProcess } from "./controller-process-identity.js";
|
|
import { companies, environmentLeases, environments, heartbeatRuns, sandboxCreationOperations, type Db } from "@paperclipai/db";
|
|
import { readEnvironmentCreationCleanupError, type PluginEnvironmentLease, type PluginEnvironmentLeaseObservation } from "@paperclipai/plugin-sdk";
|
|
import { assertEnvironmentCompanyBinding, environmentService } from "./environments.js";
|
|
import { ENVIRONMENT_CLEANUP_RETRY_MS, recoverableSandboxCreationCondition } from "./environment-cleanup-state.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { notifyEnvironmentCleanup, writeEnvironmentCleanup } from "./environment-cleanup-notifications.js";
|
|
import { crashPoint } from "@paperclipai/shared/crash-points";
|
|
import { hasRemoteTerminationReceipt, resolveRemoteTerminationLease } from "./remote-execution-termination.js";
|
|
|
|
export type SandboxCreationOperation = typeof sandboxCreationOperations.$inferSelect;
|
|
|
|
// A live creator may still be waiting for the provider, and a provider may still
|
|
// materialize an aborted request. Absence is conclusive only after this delay.
|
|
const CREATION_SETTLE_FLOOR_MS = 30 * 60_000;
|
|
|
|
function creationAbsenceInconclusive(operation: SandboxCreationOperation): boolean {
|
|
const settleAt = Date.parse(typeof operation.metadata.creationSettleAt === "string" ? operation.metadata.creationSettleAt : "");
|
|
return operation.metadata.creationControllerLost === true && Number.isFinite(settleAt) && Date.now() < settleAt;
|
|
}
|
|
|
|
export function recoverableTaskCreation(operation: Pick<SandboxCreationOperation, "metadata">): boolean {
|
|
const metadata = operation.metadata;
|
|
return metadata.runnerTaskLease === true && metadata.creationOperationVersion === 1 &&
|
|
typeof metadata.runnerTaskCreationContextId === "string" && metadata.runnerTaskCreationContextId.length > 0 &&
|
|
metadata.providerMetadata !== null && typeof metadata.providerMetadata === "object" && !Array.isArray(metadata.providerMetadata);
|
|
}
|
|
|
|
/** Plugin allocations can return their exact creation lease after a lost reply. */
|
|
export function recoverablePluginCreation(operation: Pick<SandboxCreationOperation, "metadata">): boolean {
|
|
return recoverableTaskCreation(operation) || (operation.metadata.driver === "plugin" && operation.metadata.purpose === "login");
|
|
}
|
|
|
|
type CreationOwner = {
|
|
companyId: string;
|
|
environmentId: string;
|
|
executionWorkspaceId?: string | null;
|
|
issueId?: string | null;
|
|
heartbeatRunId?: string | null;
|
|
provider: string;
|
|
pluginId?: string;
|
|
driverKey: string;
|
|
config: Record<string, unknown>;
|
|
metadata: Record<string, unknown>;
|
|
timeoutMs?: number;
|
|
requestKey?: string;
|
|
configSchema?: Record<string, unknown> | null;
|
|
resolvedConfig?: Record<string, unknown>;
|
|
};
|
|
|
|
export async function createOwnedSandbox(
|
|
db: Db, owner: CreationOwner,
|
|
create: (identity: { id: string; runId: string }) => Promise<PluginEnvironmentLease>,
|
|
): Promise<PluginEnvironmentLease> {
|
|
const credentialHashes: Record<string, string> = {};
|
|
for (const path of collectSecretRefPaths(owner.configSchema)) {
|
|
const value = readConfigValueAtPath(owner.config, path);
|
|
if (value != null && value !== "" && !(typeof value === "string" && isUuidSecretRef(value)) && !parseSecretRefBindingObject(value)) {
|
|
throw new Error("Sandbox creation requires saved secret references");
|
|
}
|
|
if (value != null && value !== "") {
|
|
const resolved = readConfigValueAtPath(owner.resolvedConfig ?? {}, path);
|
|
if (typeof resolved !== "string") throw new Error("Sandbox creation credential identity is unavailable");
|
|
credentialHashes[path] = createHash("sha256").update(resolved).digest("hex");
|
|
}
|
|
}
|
|
const id = randomUUID();
|
|
const runId = owner.heartbeatRunId ?? randomUUID();
|
|
const settleAt = new Date(Date.now() + Math.max(CREATION_SETTLE_FLOOR_MS, (owner.timeoutMs ?? 0) + 60_000));
|
|
const creationController = await currentControllerProcess();
|
|
const admit = (stopped?: SandboxCreationOperation) => db.transaction(async tx => {
|
|
await notifyEnvironmentCleanup(tx, { companyId: owner.companyId, runId: owner.heartbeatRunId ?? undefined });
|
|
await assertEnvironmentCompanyBinding(tx as unknown as Db, owner.environmentId, owner.companyId);
|
|
// Only one concurrent attempt resolves the stopped operation; any other one
|
|
// then meets the replacement below and is fenced exactly as before.
|
|
if (stopped) await tx.update(sandboxCreationOperations).set({ state: "resolved", updatedAt: new Date() }).where(and(
|
|
eq(sandboxCreationOperations.id, stopped.id), eq(sandboxCreationOperations.state, "attached"),
|
|
eq(sandboxCreationOperations.leaseId, stopped.leaseId!)));
|
|
const [inserted] = await tx.insert(sandboxCreationOperations).values({
|
|
id, companyId: owner.companyId, environmentId: owner.environmentId, originalEnvironmentId: owner.environmentId,
|
|
runId, requestKey: owner.requestKey ?? "run", issueId: owner.issueId, executionWorkspaceId: owner.executionWorkspaceId,
|
|
provider: owner.provider, pluginId: owner.pluginId, driverKey: owner.driverKey,
|
|
config: owner.config, metadata: { ...owner.metadata, creationHeartbeatRunId: owner.heartbeatRunId ?? null, creationCredentialHashes: credentialHashes,
|
|
creationController, creationSettleAt: settleAt.toISOString() },
|
|
nextAttemptAt: settleAt,
|
|
}).onConflictDoNothing().returning();
|
|
if (inserted) return inserted;
|
|
const [existing] = await tx.select().from(sandboxCreationOperations).where(and(
|
|
eq(sandboxCreationOperations.companyId, owner.companyId), eq(sandboxCreationOperations.originalEnvironmentId, owner.environmentId),
|
|
eq(sandboxCreationOperations.runId, runId), eq(sandboxCreationOperations.requestKey, owner.requestKey ?? "run"),
|
|
ne(sandboxCreationOperations.state, "resolved"),
|
|
));
|
|
if (!existing) throw new Error("Sandbox creation ownership was not recorded");
|
|
return existing;
|
|
});
|
|
let operation = await admit();
|
|
if (operation.id !== id && await createdSandboxStopped(db, operation)) operation = await admit(operation);
|
|
if (operation.id !== id) {
|
|
if (operation.state !== "attached" || !operation.leaseId) throw new Error("Sandbox creation requires reconciliation before another attempt");
|
|
const existing = await environmentService(db).getLeaseById(operation.leaseId);
|
|
if (!existing || existing.status !== "active" || !existing.providerLeaseId) throw new Error("Sandbox creation has already transferred ownership");
|
|
return { providerLeaseId: existing.providerLeaseId, expiresAt: existing.expiresAt?.toISOString(),
|
|
metadata: { ...existing.metadata, creationOperationId: operation.id } };
|
|
}
|
|
try {
|
|
crashPoint("sandbox.create.after_intent_before_provider");
|
|
const lease = await create({ id, runId });
|
|
crashPoint("sandbox.create.after_provider_before_lease");
|
|
return { ...lease, metadata: { ...lease.metadata, creationOperationId: id } };
|
|
} catch (error) {
|
|
if (recoverablePluginCreation(operation)) {
|
|
try {
|
|
await writeEnvironmentCleanup(db, tx => tx.update(sandboxCreationOperations).set({ nextAttemptAt: new Date(), updatedAt: new Date() })
|
|
.where(and(eq(sandboxCreationOperations.id, id), recoverableSandboxCreationCondition())),
|
|
{ companyId: operation.companyId, runId: owner.heartbeatRunId ?? undefined });
|
|
} catch {
|
|
logger.warn({ errorKind: "task_creation_recovery_wakeup_failed", operationId: id, companyId: operation.companyId },
|
|
"Task creation recovery retains its saved deadline");
|
|
}
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** An attached operation is finished once its closed lease carries the same
|
|
* stop proof same-run recovery requires (remoteExecutionHasStopped) for the
|
|
* sandbox this operation created. A task replacement can leave an earlier
|
|
* operation attached to a lease that now holds another sandbox; that operation
|
|
* is not proven and keeps its key. */
|
|
async function createdSandboxStopped(db: Db, operation: SandboxCreationOperation): Promise<boolean> {
|
|
if (operation.state !== "attached" || !operation.leaseId) return false;
|
|
const [lease] = await db.select().from(environmentLeases).where(and(
|
|
eq(environmentLeases.id, operation.leaseId), eq(environmentLeases.companyId, operation.companyId)));
|
|
if (!lease || lease.status === "active" || !lease.providerLeaseId) return false;
|
|
const created = operation.metadata.creationProviderLeaseId ?? lease.providerLeaseId;
|
|
return created === lease.providerLeaseId && hasRemoteTerminationReceipt(await resolveRemoteTerminationLease(db, lease));
|
|
}
|
|
|
|
/** Keep an already returned resource identity even when task attachment fails.
|
|
* This enriches the existing owner; it never transfers or reopens ownership. */
|
|
export async function recordSandboxCreationResource(db: Db, input: {
|
|
id: string; companyId: string; environmentId: string; providerLeaseId: string;
|
|
providerMetadata?: Record<string, unknown>;
|
|
}): Promise<void> {
|
|
await writeEnvironmentCleanup(db, async tx => {
|
|
const [recorded] = await tx.update(sandboxCreationOperations).set({
|
|
nextAttemptAt: sql`case when ${sandboxCreationOperations.state} = 'needs_reconciliation' then clock_timestamp() else ${sandboxCreationOperations.nextAttemptAt} end`,
|
|
metadata: sql`coalesce(${sandboxCreationOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ creationProviderLeaseId: input.providerLeaseId, ...(input.providerMetadata ? { creationProviderMetadata: input.providerMetadata } : {}) })}::jsonb`,
|
|
updatedAt: new Date(),
|
|
}).where(and(eq(sandboxCreationOperations.id, input.id), eq(sandboxCreationOperations.companyId, input.companyId),
|
|
eq(sandboxCreationOperations.originalEnvironmentId, input.environmentId),
|
|
or(sql`${sandboxCreationOperations.metadata}->>'creationProviderLeaseId' is null`,
|
|
sql`${sandboxCreationOperations.metadata}->>'creationProviderLeaseId' = ${input.providerLeaseId}`),
|
|
)).returning({ id: sandboxCreationOperations.id });
|
|
if (!recorded) throw new Error("Sandbox creation resource identity changed");
|
|
}, { companyId: input.companyId });
|
|
}
|
|
|
|
export async function queueSandboxCreationCleanup(db: Db, input: {
|
|
id: string; companyId: string; environmentId: string; providerLeaseId: string;
|
|
providerMetadata?: Record<string, unknown>;
|
|
}): Promise<void> {
|
|
await db.transaction(async tx => {
|
|
await tx.select({ id: environments.id }).from(environments).where(eq(environments.id, input.environmentId)).for("update");
|
|
const [operation] = await tx.select().from(sandboxCreationOperations).where(and(eq(sandboxCreationOperations.id, input.id),
|
|
eq(sandboxCreationOperations.companyId, input.companyId), eq(sandboxCreationOperations.originalEnvironmentId, input.environmentId))).for("update");
|
|
if (!operation || (operation.metadata.creationProviderLeaseId && operation.metadata.creationProviderLeaseId !== input.providerLeaseId)) {
|
|
throw new Error("Sandbox creation cleanup ownership changed");
|
|
}
|
|
if (["attached", "cleanup_pending", "resolved"].includes(operation.state)) return;
|
|
const contextId = operation.metadata.runnerTaskLease === true && typeof operation.metadata.runnerTaskCreationContextId === "string"
|
|
? operation.metadata.runnerTaskCreationContextId : null;
|
|
if (operation.state !== "pending" && !(operation.state === "needs_reconciliation" && contextId &&
|
|
operation.metadata.creationProviderLeaseId === input.providerLeaseId)) throw new Error("Sandbox creation cleanup ownership changed");
|
|
// The non-null runId also correlates agentless creation attempts. Only the
|
|
// original optional heartbeat reference belongs in the lease's foreign key.
|
|
// Older task intents predate that explicit field; retain their relationship
|
|
// only when an actual same-company heartbeat row still exists.
|
|
const heartbeatReference = Object.hasOwn(operation.metadata, "creationHeartbeatRunId")
|
|
? operation.metadata.creationHeartbeatRunId : operation.runId;
|
|
const [heartbeat] = typeof heartbeatReference === "string"
|
|
? await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, heartbeatReference), eq(heartbeatRuns.companyId, operation.companyId),
|
|
)).for("key share")
|
|
: [];
|
|
const heartbeatRunId = heartbeat?.id ?? null;
|
|
await notifyEnvironmentCleanup(tx, { companyId: operation.companyId, runId: heartbeatRunId ?? undefined });
|
|
const lease = await environmentService(tx as unknown as Db).insertPendingCleanupLease({
|
|
companyId: operation.companyId, environmentId: operation.originalEnvironmentId,
|
|
heartbeatRunId, issueId: operation.issueId, executionWorkspaceId: operation.executionWorkspaceId,
|
|
provider: operation.provider, providerLeaseId: input.providerLeaseId,
|
|
metadata: { ...operation.metadata, creationOperationId: operation.id, environmentId: operation.originalEnvironmentId,
|
|
providerMetadata: input.providerMetadata ?? operation.metadata.creationProviderMetadata ?? {},
|
|
...(operation.metadata.runnerTaskLease === true ? { runnerTaskRetiring: true } : {}),
|
|
...(contextId ? { runnerTaskStartupCleanup: { contextId, requiresPreparationStop: false } } : {}) },
|
|
failureReason: operation.metadata.purpose === "login" ? "interrupted_login_creation" : "interrupted_task_creation",
|
|
});
|
|
await tx.update(sandboxCreationOperations).set({ state: "cleanup_pending", leaseId: lease.id, updatedAt: new Date(),
|
|
metadata: { ...operation.metadata, creationProviderLeaseId: input.providerLeaseId,
|
|
creationProviderMetadata: input.providerMetadata ?? operation.metadata.creationProviderMetadata ?? {} },
|
|
}).where(eq(sandboxCreationOperations.id, operation.id));
|
|
});
|
|
}
|
|
|
|
export async function recoverSandboxCreations(db: Db,
|
|
inspect: (operation: SandboxCreationOperation) => Promise<PluginEnvironmentLeaseObservation | null>,
|
|
onTaskRecovered?: (operation: SandboxCreationOperation) => void | Promise<void>,
|
|
): Promise<void> {
|
|
// After a restart, an intent whose creator is proven gone cannot still be in
|
|
// flight there: the shared ownership path makes it due now. Absence stays
|
|
// inconclusive until the settle deadline (creationAbsenceInconclusive).
|
|
const { settleOwnableKind } = await import("./recovery/ownership-invariant-report.js");
|
|
await settleOwnableKind(db, "sandbox_creation_intent").catch(() => {
|
|
logger.warn({ errorKind: "sandbox_creation_intent_settle_failed" }, "Sandbox creation intents keep their saved deadlines");
|
|
});
|
|
const due = await db.select().from(sandboxCreationOperations).where(and(
|
|
recoverableSandboxCreationCondition(), lte(sandboxCreationOperations.nextAttemptAt, new Date()),
|
|
)).limit(100);
|
|
for (const candidate of due) {
|
|
try {
|
|
if (candidate.metadata.runnerTaskLease === true && typeof candidate.metadata.runnerTaskCreationContextId === "string" &&
|
|
typeof candidate.metadata.creationProviderLeaseId === "string") {
|
|
await queueSandboxCreationCleanup(db, { id: candidate.id, companyId: candidate.companyId,
|
|
environmentId: candidate.originalEnvironmentId, providerLeaseId: candidate.metadata.creationProviderLeaseId });
|
|
if (recoverableTaskCreation(candidate)) await onTaskRecovered?.(candidate);
|
|
continue;
|
|
}
|
|
const [existingCompany] = await db.select({ id: companies.id }).from(companies).where(eq(companies.id, candidate.companyId)).limit(1);
|
|
const observation = existingCompany ? await inspect(candidate) : null;
|
|
if (existingCompany && recoverablePluginCreation(candidate) && observation?.creationLease) {
|
|
const lease = observation.creationLease;
|
|
// The inspect call is scoped to this creation operation. Providers may
|
|
// assign a different resource ID; require the receipt/envelope to agree,
|
|
// then let the durable resource record reject any changed identity.
|
|
if (typeof lease.providerLeaseId !== "string" || lease.providerLeaseId.length === 0 || lease.providerLeaseId !== observation.providerLeaseId ||
|
|
!lease.metadata || typeof lease.metadata !== "object" || Array.isArray(lease.metadata)) {
|
|
throw new Error("Plugin allocation creation recovery returned foreign ownership");
|
|
}
|
|
const identity = { id: candidate.id, companyId: candidate.companyId, environmentId: candidate.originalEnvironmentId,
|
|
providerLeaseId: lease.providerLeaseId, providerMetadata: lease.metadata };
|
|
await recordSandboxCreationResource(db, identity);
|
|
await queueSandboxCreationCleanup(db, identity);
|
|
await onTaskRecovered?.(candidate);
|
|
continue;
|
|
}
|
|
if (existingCompany && candidate.metadata.purpose === "login" && observation?.state === "destroyed" && observation.providerLeaseId === candidate.id) {
|
|
const settledAt = Date.parse(typeof candidate.metadata.creationSettleAt === "string" ? candidate.metadata.creationSettleAt : "");
|
|
if (!Number.isFinite(settledAt) || Date.now() < settledAt) throw new Error("Login allocation creation has not settled yet");
|
|
await writeEnvironmentCleanup(db, tx => tx.update(sandboxCreationOperations).set({ state: "resolved", updatedAt: new Date() })
|
|
.where(and(eq(sandboxCreationOperations.id, candidate.id), eq(sandboxCreationOperations.state, "pending"))), { companyId: candidate.companyId });
|
|
continue;
|
|
}
|
|
if (existingCompany && recoverablePluginCreation(candidate)) throw new Error("Plugin allocation creation identity is not available yet");
|
|
const cleanup = observation?.creationCleanup ? readEnvironmentCreationCleanupError({ data: {
|
|
schema: "paperclip/environment-creation-cleanup/v1", cleanup: observation.creationCleanup,
|
|
} }) : null;
|
|
if (cleanup && (cleanup.companyId !== candidate.companyId || cleanup.environmentId !== candidate.originalEnvironmentId ||
|
|
cleanup.runId !== candidate.runId || cleanup.attemptId !== candidate.id || cleanup.providerLeaseId !== observation!.providerLeaseId)) {
|
|
throw new Error("Sandbox creation recovery returned foreign ownership");
|
|
}
|
|
// An early lookup after a lost creator may precede provider materialization.
|
|
if (existingCompany && !cleanup && creationAbsenceInconclusive(candidate)) {
|
|
throw new Error("Sandbox creation has not settled yet");
|
|
}
|
|
await db.transaction(async tx => {
|
|
const [company] = await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, candidate.companyId)).for("key share");
|
|
await tx.select({ id: environments.id }).from(environments).where(eq(environments.id, candidate.originalEnvironmentId)).for("update");
|
|
const [operation] = await tx.select().from(sandboxCreationOperations)
|
|
.where(eq(sandboxCreationOperations.id, candidate.id)).for("update");
|
|
if (!operation || operation.state !== "pending") return;
|
|
await notifyEnvironmentCleanup(tx, { companyId: operation.companyId });
|
|
if (!company || !cleanup) {
|
|
logger.warn({ errorKind: "sandbox_creation_needs_reconciliation", operationId: operation.id, companyId: operation.companyId },
|
|
"Sandbox creation could not be identified; operator reconciliation is required");
|
|
await tx.update(sandboxCreationOperations).set({ state: "needs_reconciliation", updatedAt: new Date(),
|
|
metadata: { ...operation.metadata, creationReconciliationReason: company ? "creation_identity_unavailable" : "company_deleted" },
|
|
})
|
|
.where(eq(sandboxCreationOperations.id, operation.id));
|
|
return;
|
|
}
|
|
const lease = await environmentService(tx as unknown as Db).insertPendingCleanupLease({
|
|
companyId: operation.companyId, environmentId: operation.originalEnvironmentId,
|
|
provider: operation.provider, providerLeaseId: cleanup.providerLeaseId,
|
|
metadata: { ...operation.metadata, creationOperationId: operation.id, failedCreateCleanup: cleanup },
|
|
failureReason: "interrupted_sandbox_creation",
|
|
});
|
|
await tx.update(sandboxCreationOperations).set({ state: "cleanup_pending", leaseId: lease.id, updatedAt: new Date() })
|
|
.where(eq(sandboxCreationOperations.id, operation.id));
|
|
});
|
|
} catch {
|
|
const retry = await db.transaction(async tx => {
|
|
const [company] = await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, candidate.companyId)).for("key share");
|
|
await notifyEnvironmentCleanup(tx, { companyId: candidate.companyId });
|
|
await tx.update(sandboxCreationOperations).set(company
|
|
? { nextAttemptAt: new Date(Date.now() + ENVIRONMENT_CLEANUP_RETRY_MS), updatedAt: new Date() }
|
|
: { state: "needs_reconciliation", updatedAt: new Date(),
|
|
metadata: sql`coalesce(${sandboxCreationOperations.metadata}, '{}'::jsonb) || '{"creationReconciliationReason":"company_deleted"}'::jsonb` })
|
|
.where(and(eq(sandboxCreationOperations.id, candidate.id), recoverableSandboxCreationCondition()));
|
|
return Boolean(company);
|
|
});
|
|
logger.warn({ errorKind: retry ? "sandbox_creation_recovery_failed" : "sandbox_creation_needs_reconciliation", operationId: candidate.id, companyId: candidate.companyId },
|
|
retry ? "Sandbox creation recovery will retry at its saved deadline" : "Sandbox creation company was deleted; operator reconciliation is required");
|
|
}
|
|
}
|
|
}
|