Files
PaperClipAI/server/src/__tests__/sandbox-creation-operations.test.ts
T
DottaandClaude Opus 5.5 56654adecd perf(server): reuse sandbox provider schemas for five seconds on the remote-run path (#21758)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent runs can use remote sandboxes that a sandbox provider plugin
supplies (for example Daytona)
> - Each sandbox operation resolves the environment config, and that
step reads the provider config schema to find the secret-ref fields
> - On a hosted instance with 7 remote runs, this schema read was the
most frequent statement: 17.95 per second, about 2.5 per second for each
run
> - The server runs all agents on one Node main thread, so each
statement costs main-thread time; at 1,000 agents this read alone is
about 2,500 statements per second
> - This pull request reuses the retained schema for a short, bounded
time and drops it at once when the plugin registry changes a plugin
manifest
> - The benefit is that a live remote run reads the schema about once
per 5 seconds for each provider, not once per operation

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Every plugin sandbox operation (exec, file sync in/out, runner ingress
attach, capability snapshot, workspace realize, lease resume, lease
release) calls `resolveEnvironmentDriverConfigForRuntime`. That call
runs the `with selected_provider as materialized ...` statement in
`resolvePluginSandboxProviderConfigSchema`, every time.

**Subsystem affected**
Server: plugin environment driver
(`server/src/services/plugin-environment-driver.ts`) and the plugin
registry manifest writes.

**Current behavior**
The schema read runs once per operation. A census test that drives the
real runtime calls of one remote run counts 19 schema reads for 19
operations (see the table below). The hosted measurement was 17.95
executions per second with 7 runs.

**Proposed behavior**
The read runs at most once per 5 seconds for each provider and database
client. A plugin install, upgrade or uninstall through the plugin
registry in the same process takes effect on the next operation.

**Reason and benefit**
The schema is instance-wide plugin manifest data. It does not change
during normal runs. Re-reading it per operation spends main-thread and
database time for no new information.

**Breaking changes**
None. No API, schema or saved-state change.

## What Changed

- `resolvePluginSandboxProviderConfigSchema` now returns the retained
schema without a database read when the entry was checked less than
`PROVIDER_SCHEMA_REUSE_MS` (5,000 ms) ago and the plugin manifest
revision did not change. After that, it uses the existing cheap revision
check, as before.
- A lookup sequence number stops an older, slower lookup from replacing
a newer retained entry.
- A missing provider is still never retained, so a provider that becomes
available is used on the next operation.
- New module `plugin-manifest-revision.ts` holds an in-process manifest
revision counter. It is a separate module so that the registry and the
driver do not import each other.
- `plugin-registry.ts`: `install` (both the new-row and the reinstall
paths), `update` and `uninstall` announce a manifest change after the
write completes. This is 5 changed lines plus 1 import line. Status-only
writes do not announce, because the schema read does not use plugin
status.
- `plugin-loader.ts`: `installPlugin` runs `registry.install` inside an
outer transaction. It now announces the manifest change again after that
transaction settles, so a schema read made before the commit cannot be
reused after it. This is 1 changed line plus 1 import line.
- Statement census per operation, before and after. One remote run, one
secret-ref field in the provider config, embedded test database, fake
in-process plugin worker:

| Operation | Count | Schema reads before | Schema reads after | All
statements before | All statements after |
| --- | --- | --- | --- | --- | --- |
| Lease acquire | 1 | 1 | 1 | 26 | 26 |
| Runner attach (ingress endpoint) | 1 | 2 | 0 | 11 | 9 |
| Capability snapshot | 1 | 1 | 0 | 6 | 5 |
| Exec | 10 | 10 | 0 | 50 | 40 |
| File write (sync in) | 1 | 1 | 0 | 5 | 4 |
| File read (sync out) | 1 | 1 | 0 | 5 | 4 |
| Workspace realize | 1 | 1 | 0 | 5 | 4 |
| Lease resume (reattach) | 1 | 1 | 0 | 6 | 5 |
| Lease release | 1 | 1 | 0 | 18 | 17 |
| **Total** | 18 | **19** | **1** | 132 | 114 |

- Other reads that stay on each operation (reported, not changed in this
pull request): each exec resolves each secret-ref field with 3 reads
(secret, binding, version) and 1 `secret_access_events` insert. Runner
attach and the capability snapshot also read the plugin row by id. These
are part of the secret authorization and audit path, so they keep their
own checks.

## Verification

- `cd server && npx vitest run
src/__tests__/plugin-sandbox-provider-schema-census.test.ts` (new). On
master the census test fails with 19 schema reads. With this change it
passes with 1.
- The new tests also prove these points:
- A registry upgrade that changes the secret-ref fields takes effect on
the next call in the same process.
- A direct manifest change (as from another server process) takes effect
after the 5-second bound, and no read occurs inside the bound.
  - A registry uninstall takes effect at once.
- A plugin reinstall through `pluginLoader.installPlugin` takes effect
after its install transaction commits, even when a schema read ran
inside the uncommitted transaction. This test failed before the
post-commit announcement and passes with it.
- A missing provider is not retained. The next call after install reads
and uses it.
- Two companies share the provider schema but each gets only its own
secret values. A cross-company secret id still fails with "Secret must
belong to same company".
  - A new database client (a process restart) starts cold, as before.
- `cd server && npx vitest run src/__tests__/plugin-database.test.ts`:
passed (plugin install transaction paths).
- `cd server && npx vitest run
src/__tests__/sandbox-provider-schema-reads.test.ts`: the existing tests
now step the clock past the bound where they change the database
directly.
- `cd server && npx vitest run
src/__tests__/environment-runtime.test.ts`: 210 passed.
- `cd server && npx vitest run
src/__tests__/bundled-plugin-registration.test.ts
src/__tests__/external-object-refresh-work.test.ts
src/__tests__/plugin-lifecycle-restart.test.ts
src/__tests__/plugin-loader-error-retry.test.ts
src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts
src/__tests__/plugin-sandbox-provider-config-validation.test.ts
src/__tests__/environment-probe.test.ts`: 82 passed, 1 skipped.
- `cd server && pnpm typecheck`: passed.

## Risks

- Staleness bound: a plugin manifest change made by a different server
process (for example during an overlapping deploy) can take up to 5
seconds to apply here. During that time, a secret-ref field that an
upgrade adds is not resolved yet, and a field that an upgrade removes is
still resolved. The bound is short and it applies only to which config
paths are secret refs.
- The retained value is instance-wide plugin manifest data, keyed by
database client and driver key. It contains no company data and no
secret values. It does not take part in an authorization decision.
Secret resolution, the environment binding check and the access audit
still run on each operation for the calling company.
- Memory stays bounded by the existing limits: 32 entries per database
client, 64 KiB per schema.
- `plugin-registry.ts` has a small edit in `install`, `update` and
`uninstall`. Other open work in that file can cause a simple merge
conflict.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit, test runs).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Refs #17581

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:09:04 -06:00

657 lines
47 KiB
TypeScript

import { execFile, spawn } from "node:child_process";
import { createServer } from "node:http";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { randomUUID } from "node:crypto";
import { mkdtemp, readFile, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { eq, sql } from "drizzle-orm";
import { agents, builtInManagedResources, companies, companySecretVersions, createDb, environmentLeases, environments, heartbeatRuns, issues, plugins, sandboxCreationOperations } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { environmentRuntimeService } from "../services/environment-runtime.js";
import { environmentService } from "../services/environments.js";
import { HttpError } from "../errors.js";
import * as secretOwner from "../services/secrets.js";
import { readIdleSleepSafety } from "../services/idle-sleep-safety.js";
import { nextEnvironmentCleanupAt } from "../services/environment-cleanup-state.js";
import { readProcessStartedAt } from "../services/hot-restart.js";
import { hasRemoteTerminationReceipt, remoteTerminationReceipt, resolveRemoteTerminationLease } from "../services/remote-execution-termination.js";
import { createReusableLeaseHandoff } from "../services/environment-lease-handoff.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { announcePluginManifestChange } from "../services/plugin-manifest-revision.js";
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_HISTORY_TEST_DATABASE_URL");
describe("durable sandbox creation through the runtime entry point", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let db: ReturnType<typeof createDb>;
let companyId: string, environmentId: string, pluginId: string, runId: string, spool: string;
let creates: number, destroys: number, loseReply: boolean, failDestroy: boolean, pluginLogin: boolean, generatedLoginId: boolean, foreignReceipt: boolean;
let beforeReply: (() => Promise<void>) | undefined;
const resources = new Map<string, string>();
let workers: PluginWorkerManager;
beforeAll(async () => {
if (!external) database = await startEmbeddedPostgresTestDatabase("sandbox-creation-operations-");
db = createDb(external ?? database!.connectionString, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
}, 90_000);
beforeEach(async () => {
await db.execute(sql`truncate sandbox_creation_operations, companies, environments, plugins cascade`);
announcePluginManifestChange();
companyId = randomUUID(); environmentId = randomUUID(); pluginId = randomUUID(); runId = randomUUID();
const agentId = randomUUID(); creates = 0; destroys = 0; loseReply = false; failDestroy = false; pluginLogin = false; generatedLoginId = false; foreignReceipt = false; beforeReply = undefined; resources.clear();
spool = await mkdtemp(join(tmpdir(), "empty-sandbox-web-"));
await db.insert(companies).values({ id: companyId, name: "Creation fixture", issuePrefix: "CRT" });
await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", role: "engineer", adapterType: "codex_local" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", invocationSource: "manual" });
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox", config: { provider: "creation-fixture", image: "fixture", reuseLease: false } });
await db.insert(plugins).values({ id: pluginId, pluginKey: "paperclip.creation-fixture", packageName: "creation-fixture", version: "1.0.0", apiVersion: 1,
status: "ready", categories: ["automation"], manifestJson: { id: "paperclip.creation-fixture", version: "1.0.0", apiVersion: 1,
displayName: "Creation fixture", description: "Controlled remote provider", author: "Paperclip", categories: ["automation"],
capabilities: ["environment.drivers.register"], entrypoints: { worker: "fixture.js" }, environmentDrivers: [{
driverKey: "creation-fixture", kind: "sandbox_provider", displayName: "Fixture", creationOperationVersion: 1, configSchema: { type: "object" },
}] } });
workers = {
isRunning: () => true,
getWorker: () => ({ supportedMethods: ["environmentAcquireLease", "environmentInspectLease", "environmentDestroyLease"] }),
call: vi.fn(async (_pluginId: string, method: string, input: any) => {
if (method === "environmentAcquireLease") {
expect(await db.select().from(sandboxCreationOperations)).toContainEqual(expect.objectContaining({ id: input.creationOperationId, state: "pending" }));
creates++;
const resource = pluginLogin && !generatedLoginId ? input.creationOperationId : `provider-${input.creationOperationId}`;
resources.set(input.creationOperationId, resource);
await beforeReply?.();
if (loseReply) throw new Error("Lost provider reply");
return { providerLeaseId: resource, metadata: { remoteCwd: "/workspace" } };
}
if (method === "environmentInspectLease") {
const id = input.creationOperation.id;
const resource = resources.get(id);
if (pluginLogin) return resource
? { providerLeaseId: resource, state: "unknown", creationLease: { providerLeaseId: foreignReceipt ? "foreign-resource" : resource, metadata: { purpose: "login", loginCommandKey: "codex" } } }
: { providerLeaseId: id, state: "destroyed" };
if (!resource) return { providerLeaseId: id, state: "unknown" };
return { providerLeaseId: resource, state: "active", creationCleanup: { providerLeaseId: resource,
observedProviderLeaseId: resource, companyId, environmentId, runId: input.creationOperation.runId, attemptId: id,
accountFingerprint: "a".repeat(64), labels: { "paperclip-create-attempt": id } } };
}
if (method === "environmentDestroyLease" || (pluginLogin && method === "environmentReleaseLease")) {
destroys++;
if (failDestroy) throw new Error("Fixture teardown failed");
resources.delete(input.leaseMetadata.creationOperationId);
return { providerLeaseId: input.providerLeaseId, state: "destroyed" };
}
throw new Error(`Unexpected fixture method ${method}`);
}),
} as unknown as PluginWorkerManager;
});
afterEach(async () => {
await db.execute(sql`drop trigger if exists reject_fixture_lease on environment_leases`);
await db.execute(sql`drop trigger if exists reject_fixture_creation on sandbox_creation_operations`);
await rm(spool, { recursive: true, force: true });
});
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); });
function runtime() { return environmentRuntimeService(db, { pluginWorkerManager: workers, orphanCleanupSpoolDir: spool }); }
async function acquire() {
return runtime().acquireRunLease({ companyId, environment: (await environmentService(db).getById(environmentId))!,
heartbeatRunId: runId, issueId: null, persistedExecutionWorkspace: null, assertCompanyBinding: true });
}
async function due() { await db.update(sandboxCreationOperations).set({ nextAttemptAt: new Date(0) }); }
async function rejectWrites(table: "environment_leases" | "sandbox_creation_operations", trigger: string) {
await db.execute(sql`create or replace function reject_fixture_write() returns trigger language plpgsql as $$ begin raise exception 'Fixture database write unavailable'; end $$`);
await db.execute(sql.raw(`create trigger ${trigger} before insert on ${table} for each row execute function reject_fixture_write()`));
}
async function acquirePluginLogin(heartbeatRunId: string | null = null) {
pluginLogin = true;
await db.update(environments).set({ driver: "plugin", config: { pluginKey: "paperclip.creation-fixture", driverKey: "creation-fixture", driverConfig: {} } }).where(eq(environments.id, environmentId));
const [plugin] = await db.select().from(plugins).where(eq(plugins.id, pluginId));
await db.update(plugins).set({ manifestJson: { ...plugin.manifestJson, environmentDrivers: [{ driverKey: "creation-fixture", kind: "environment_driver", displayName: "Computer", creationOperationVersion: 1, configSchema: { type: "object" } }] } }).where(eq(plugins.id, pluginId));
return runtime().acquireRunLease({ companyId, environment: (await environmentService(db).getById(environmentId))!, heartbeatRunId,
issueId: null, persistedExecutionWorkspace: null, purpose: "login", loginCommandKey: "codex", requestedExpiresAt: new Date(Date.now() + 300000) });
}
it.each([false, true])("recovers an interrupted login using its exact receipt (provider-generated ID: %s)", async generated => {
generatedLoginId = generated;
loseReply = true; await expect(acquirePluginLogin()).rejects.toThrow("Lost provider reply");
const [intent] = await db.select().from(sandboxCreationOperations);
expect(intent.metadata).toMatchObject({ purpose: "login", loginCommandKey: "codex", creationHeartbeatRunId: null });
expect(intent.runId).not.toBe(runId);
await due(); await runtime().flushDeferredOrphanCleanups();
const [lease] = await db.select().from(environmentLeases);
expect(lease).toMatchObject({ status: "pending_cleanup", heartbeatRunId: null, providerLeaseId: generated ? `provider-${intent.id}` : intent.id, metadata: { purpose: "login", loginCommandKey: "codex" } });
await runtime().retryPendingSandboxTeardown({ environment: null, lease: (await environmentService(db).getLeaseById(lease.id))! });
expect(resources.size).toBe(0); expect(destroys).toBe(1);
});
it.each([false, true])("preserves an actual heartbeat reference during recovery (legacy intent: %s)", async legacy => {
loseReply = true;
await expect(acquirePluginLogin(runId)).rejects.toThrow("Lost provider reply");
const [intent] = await db.select().from(sandboxCreationOperations);
expect(intent.metadata.creationHeartbeatRunId).toBe(runId);
if (legacy) await db.update(sandboxCreationOperations).set({ metadata: sql`metadata - 'creationHeartbeatRunId'` });
await due(); await runtime().flushDeferredOrphanCleanups();
const [lease] = await db.select().from(environmentLeases);
expect(lease.heartbeatRunId).toBe(runId);
await runtime().retryPendingSandboxTeardown({ environment: null, lease: (await environmentService(db).getLeaseById(lease.id))! });
expect(resources.size).toBe(0); expect(destroys).toBe(1);
});
it("retains ownership when the inspected lease and its receipt disagree", async () => {
generatedLoginId = true; foreignReceipt = true; loseReply = true;
await expect(acquirePluginLogin()).rejects.toThrow("Lost provider reply");
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([]);
expect((await db.select().from(sandboxCreationOperations))[0].state).toBe("pending");
expect(resources.size).toBe(1); expect(destroys).toBe(0);
foreignReceipt = false;
await due(); await runtime().flushDeferredOrphanCleanups();
const [lease] = await db.select().from(environmentLeases);
await runtime().retryPendingSandboxTeardown({ environment: null, lease: (await environmentService(db).getLeaseById(lease.id))! });
expect(resources.size).toBe(0); expect(destroys).toBe(1);
});
it("resolves a never-created login only after its materialization window", async () => {
loseReply = true; await expect(acquirePluginLogin()).rejects.toThrow("Lost provider reply"); resources.clear();
await due(); await runtime().flushDeferredOrphanCleanups();
expect((await db.select().from(sandboxCreationOperations))[0].state).toBe("pending");
await db.update(sandboxCreationOperations).set({ nextAttemptAt: new Date(0), metadata: sql`metadata || '{"creationSettleAt":"2000-01-01T00:00:00Z"}'::jsonb` });
await runtime().flushDeferredOrphanCleanups();
expect((await db.select().from(sandboxCreationOperations))[0].state).toBe("resolved");
expect(destroys).toBe(0);
});
it("can reapply the creation migration without losing a committed intent", async () => {
loseReply = true; await expect(acquire()).rejects.toThrow("Lost provider reply");
const [before] = await db.select().from(sandboxCreationOperations);
const migration = await readFile(new URL("../../../packages/db/src/migrations/0418_curved_lady_mastermind.sql", import.meta.url), "utf8");
for (let attempt = 0; attempt < 2; attempt++) {
for (const statement of migration.split("--> statement-breakpoint").map(value => value.trim()).filter(Boolean)) {
await db.execute(sql.raw(statement));
}
}
expect(await db.select().from(sandboxCreationOperations)).toEqual([before]);
expect(creates).toBe(1);
// The later migration narrowed the key to unresolved operations; a reapply keeps that.
const indexes = await db.execute(sql`select indexdef from pg_indexes where indexname = 'sandbox_creation_operations_owner_idx'`);
expect([...indexes].map(row => String((row as { indexdef: unknown }).indexdef))).toEqual([
expect.stringContaining("WHERE (state <> 'resolved'::text)"),
]);
});
it("fails before the external action when the durable admission write fails", async () => {
await rejectWrites("sandbox_creation_operations", "reject_fixture_creation");
await expect(acquire()).rejects.toThrow();
expect(creates).toBe(0); expect(resources.size).toBe(0); expect(await readdir(spool)).toEqual([]);
});
it("attaches once and reuses the committed transfer after a lost response", async () => {
const first = await acquire();
const retry = await acquire();
expect(retry.lease.id).toBe(first.lease.id); expect(creates).toBe(1); expect(destroys).toBe(0);
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toHaveLength(1);
expect(await nextEnvironmentCleanupAt(db)).toBeNull();
});
describe("same-run recovery after the attached lease closes", () => {
type Lease = Awaited<ReturnType<typeof acquire>>["lease"];
const stopReceipt = (lease: Lease) => remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" });
const operations = () => db.select().from(sandboxCreationOperations);
async function acquirePlugin() {
await db.update(environments).set({ driver: "plugin", config: { pluginKey: "paperclip.creation-fixture", driverKey: "creation-fixture", driverConfig: {} } }).where(eq(environments.id, environmentId));
const [plugin] = await db.select().from(plugins).where(eq(plugins.id, pluginId));
await db.update(plugins).set({ manifestJson: { ...plugin.manifestJson, environmentDrivers: [{ driverKey: "creation-fixture", kind: "environment_driver", displayName: "Computer", creationOperationVersion: 1, configSchema: { type: "object" } }] } }).where(eq(plugins.id, pluginId));
return runtime().acquireRunLease({ companyId, environment: (await environmentService(db).getById(environmentId))!,
heartbeatRunId: runId, issueId: null, persistedExecutionWorkspace: null });
}
/** The closing write left the operation attached; the next creation with the
* same key proves the stop, resolves it, and creates exactly one replacement. */
async function expectOneReplacement(first: { lease: Lease }, acquireLease: () => Promise<{ lease: Lease }>) {
const [before] = await operations();
expect(before).toMatchObject({ state: "attached", leaseId: first.lease.id });
const second = await acquireLease();
expect(second.lease.id).not.toBe(first.lease.id);
expect(second.lease.providerLeaseId).not.toBe(first.lease.providerLeaseId);
expect(creates).toBe(2);
expect(await operations()).toEqual(expect.arrayContaining([
expect.objectContaining({ id: before!.id, state: "resolved", leaseId: first.lease.id }),
expect.objectContaining({ state: "attached", leaseId: second.lease.id, runId, requestKey: before!.requestKey }),
]));
// A retry of the replacement replays it instead of creating again.
expect((await acquireLease()).lease.id).toBe(second.lease.id);
expect(creates).toBe(2);
}
it.each([["sandbox", acquire], ["plugin", acquirePlugin]] as const)("creates one replacement once a stop receipt closes the %s lease", async (_driver, acquireLease) => {
const first = await acquireLease();
expect(await environmentService(db).releaseLease(first.lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: stopReceipt(first.lease) }))
.toMatchObject({ status: "released" });
await expectOneReplacement(first, acquireLease);
});
it("creates one replacement after the Runner complete operation stops a retained reusable lease", async () => {
const first = await acquirePlugin();
await db.update(environmentLeases).set({ status: "retained", leasePolicy: "reuse_by_environment", releasedAt: null })
.where(eq(environmentLeases.id, first.lease.id));
// The same write the `complete` operation makes for each reusable owner of a
// stopped task: no releaseLease call.
const [owner] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, first.lease.id));
await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success",
metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({
remoteExecutionTermination: remoteTerminationReceipt(owner!, { providerLeaseId: owner!.providerLeaseId, state: "stopped" }),
runnerTaskExecutionStopped: true })}::jsonb` }).where(eq(environmentLeases.id, first.lease.id));
await expectOneReplacement(first, acquirePlugin);
});
it("creates one replacement when only the destroyed successor proves an expired reusable lease stopped", async () => {
const first = await acquire();
const [{ agentId }] = await db.select({ agentId: agents.id }).from(agents).where(eq(agents.companyId, companyId));
const issueId = randomUUID(), successorRunId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Reused sandbox", status: "done" });
await db.insert(heartbeatRuns).values({ id: successorRunId, companyId, agentId, invocationSource: "on_demand", status: "succeeded" });
const acquiredAt = new Date(Date.now() - 2000), handoffAt = new Date(Date.now() - 1000);
const [previous] = await db.update(environmentLeases).set({ status: "expired", leasePolicy: "reuse_by_environment", issueId,
acquiredAt, releasedAt: handoffAt, cleanupStatus: "success", metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({ agentId })}::jsonb` })
.where(eq(environmentLeases.id, first.lease.id)).returning();
const successor = { ...previous!, id: randomUUID(), heartbeatRunId: successorRunId, acquiredAt: handoffAt,
status: "released" as const, releasedAt: new Date(), metadata: { agentId } };
const handoff = createReusableLeaseHandoff(previous!, successor);
await db.update(environmentLeases).set({ metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({ reusableLeaseSuccessor: handoff })}::jsonb` })
.where(eq(environmentLeases.id, first.lease.id));
await db.insert(environmentLeases).values({ ...successor, metadata: { agentId, reusableLeasePredecessor: handoff,
remoteExecutionTermination: remoteTerminationReceipt(successor, { providerLeaseId: successor.providerLeaseId, state: "destroyed" }) } });
const [stored] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, first.lease.id));
// No receipt is stored on the expired lease; recovery computes it from the successor.
expect(hasRemoteTerminationReceipt(stored!)).toBe(false);
expect(hasRemoteTerminationReceipt(await resolveRemoteTerminationLease(db, stored!))).toBe(true);
await expectOneReplacement(first, acquire);
});
it.each([
["failed cleanup", "failed", { cleanupStatus: "failed", receipt: true }],
["cleanup success without a receipt", "released", { cleanupStatus: "success", receipt: false }],
["a receipt for another lease", "released", { cleanupStatus: "success", receipt: "foreign" }],
["a receipt for another provider task", "released", { cleanupStatus: "success", receipt: "other-task" }],
["a retained lease", "retained", { cleanupStatus: "success", receipt: true }],
["pending cleanup", "pending_cleanup", { cleanupStatus: "failed", receipt: false }],
] as const)("keeps the creation key after %s", async (_case, status, options) => {
const first = await acquire();
const receipt = options.receipt === "foreign" ? stopReceipt({ ...first.lease, id: randomUUID() })
: options.receipt === "other-task" ? { ...stopReceipt(first.lease), providerLeaseId: "other-task" }
: options.receipt ? stopReceipt(first.lease) : undefined;
await environmentService(db).releaseLease(first.lease.id, status, { cleanupStatus: options.cleanupStatus,
...(receipt ? { remoteExecutionTermination: receipt } : {}) });
await expect(acquire()).rejects.toThrow("Sandbox creation has already transferred ownership");
expect(await operations()).toEqual([expect.objectContaining({ state: "attached", leaseId: first.lease.id })]);
expect(creates).toBe(1);
});
it("keeps an earlier task's operation when the lease now holds a replacement task", async () => {
const first = await acquire();
await db.update(sandboxCreationOperations).set({ metadata: sql`metadata || '{"creationProviderLeaseId":"earlier-task"}'::jsonb` });
await environmentService(db).releaseLease(first.lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: stopReceipt(first.lease) });
await expect(acquire()).rejects.toThrow("Sandbox creation has already transferred ownership");
expect(await operations()).toEqual([expect.objectContaining({ state: "attached", leaseId: first.lease.id })]);
expect(creates).toBe(1);
});
it("lets only one of two concurrent recoveries create the replacement", async () => {
const first = await acquire();
await environmentService(db).releaseLease(first.lease.id, "released", { cleanupStatus: "success", remoteExecutionTermination: stopReceipt(first.lease) });
// Hold whichever recovery reaches the provider until the other one has settled.
let settleOther!: () => void;
const otherSettled = new Promise<void>(resolve => { settleOther = resolve; });
beforeReply = () => otherSettled;
const outcomes = [acquire(), acquire()].map(attempt => attempt.then(
value => ({ value, error: undefined }), (error: unknown) => ({ value: undefined, error })));
const loser = await Promise.race(outcomes);
settleOther();
const settled = await Promise.all(outcomes);
expect(loser.error).toEqual(expect.objectContaining({ message: "Sandbox creation requires reconciliation before another attempt" }));
expect(settled.filter(outcome => outcome.value)).toHaveLength(1);
expect(creates).toBe(2);
expect((await operations()).filter(operation => operation.state !== "resolved")).toEqual([
expect.objectContaining({ state: "attached", leaseId: settled.find(outcome => outcome.value)!.value!.lease.id }),
]);
expect(await operations()).toHaveLength(2);
});
});
it("recovers a failed lease write with a fresh receiver and empty web disk", async () => {
await rejectWrites("environment_leases", "reject_fixture_lease");
await expect(acquire()).rejects.toThrow();
expect(creates).toBe(1); expect(await readdir(spool)).toEqual([]);
expect(await db.select().from(sandboxCreationOperations)).toEqual([expect.objectContaining({ state: "pending" })]);
await db.execute(sql`drop trigger reject_fixture_lease on environment_leases`);
await due();
await Promise.all([runtime().flushDeferredOrphanCleanups(), runtime().flushDeferredOrphanCleanups()]);
const leases = await db.select().from(environmentLeases);
expect(leases).toEqual([expect.objectContaining({ status: "pending_cleanup", providerLeaseId: [...resources.values()][0] })]);
expect(creates).toBe(1);
failDestroy = true;
await expect(runtime().retryPendingSandboxTeardown({ environment: null, lease: (await environmentService(db).getLeaseById(leases[0]!.id))! })).rejects.toThrow("Fixture teardown failed");
expect(resources.size).toBe(1);
failDestroy = false;
await runtime().retryPendingSandboxTeardown({ environment: null, lease: (await environmentService(db).getLeaseById(leases[0]!.id))! });
expect(resources.size).toBe(0); expect(destroys).toBe(2);
});
it("reconstructs ownership in a replacement receiver process with a different empty web disk", async () => {
const provider = createServer(async (request, response) => {
try {
let body = ""; for await (const chunk of request) body += chunk.toString();
const { method, input } = JSON.parse(body);
response.setHeader("content-type", "application/json");
response.end(JSON.stringify(await (workers.call as any)(pluginId, method, input)));
} catch { response.statusCode = 500; response.end("{}"); }
});
await new Promise<void>(resolve => provider.listen(0, "127.0.0.1", resolve));
const address = provider.address() as { port: number };
const replacementDisk = await mkdtemp(join(tmpdir(), "replacement-sandbox-web-"));
const fixture = fileURLToPath(new URL("./fixtures/sandbox-creation-receiver.ts", import.meta.url));
async function receiver(action: string, disk: string) {
const result = await promisify(execFile)(process.execPath, ["--import", fileURLToPath(import.meta.resolve("tsx")), fixture], {
cwd: fileURLToPath(new URL("../../..", import.meta.url)), timeout: 60_000,
env: { ...process.env, CREATION_FIXTURE_ACTION: action, CREATION_FIXTURE_EMPTY_DISK: disk,
CREATION_FIXTURE_DATABASE_URL: external ?? database!.connectionString, CREATION_FIXTURE_PROVIDER_URL: `http://127.0.0.1:${address.port}`,
CREATION_FIXTURE_COMPANY_ID: companyId, CREATION_FIXTURE_ENVIRONMENT_ID: environmentId, CREATION_FIXTURE_RUN_ID: runId },
});
return result.stdout;
}
try {
await rejectWrites("environment_leases", "reject_fixture_lease");
expect(await receiver("acquire", spool)).toContain('"ok":false');
expect(creates).toBe(1); expect(resources.size).toBe(1); expect(await readdir(spool)).toEqual([]);
await db.execute(sql`drop trigger reject_fixture_lease on environment_leases`);
await due();
expect(await receiver("recover", replacementDisk)).toContain('"ok":true');
expect(await receiver("recover", replacementDisk)).toContain('"ok":true');
expect(await db.select().from(environmentLeases)).toEqual([
expect.objectContaining({ status: "pending_cleanup", providerLeaseId: [...resources.values()][0] }),
]);
expect(creates).toBe(1); expect(await readdir(replacementDisk)).toEqual([]);
} finally {
await new Promise<void>((resolve, reject) => provider.close(error => error ? reject(error) : resolve()));
await rm(replacementDisk, { recursive: true, force: true });
}
}, 180_000);
it("never repeats creation after a lost provider reply", async () => {
loseReply = true;
await expect(acquire()).rejects.toThrow("Lost provider reply");
await expect(acquire()).rejects.toThrow("requires reconciliation");
expect(creates).toBe(1);
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([expect.objectContaining({ status: "pending_cleanup" })]);
});
it("retains cleanup ownership when the environment is deleted during creation", async () => {
beforeReply = async () => { await environmentService(db).remove(environmentId); };
await expect(acquire()).rejects.toThrow();
expect(await db.select().from(sandboxCreationOperations)).toEqual([expect.objectContaining({ environmentId: null, originalEnvironmentId: environmentId, state: "pending" })]);
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([expect.objectContaining({ environmentId: null, status: "pending_cleanup" })]);
});
it("rejects attachment after a company rebind and retains cleanup", async () => {
beforeReply = async () => {
const foreign = randomUUID(); await db.insert(companies).values({ id: foreign, name: "Foreign", issuePrefix: "FOR" });
await db.insert(builtInManagedResources).values({ companyId: foreign, bundleKey: "managed-environment", resourceKind: "environment",
resourceKey: "sandbox", resourceId: environmentId, stockVersion: "1", stockHash: "fixture" });
};
await expect(acquire()).rejects.toMatchObject({ status: 403 });
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([expect.objectContaining({ companyId, status: "pending_cleanup" })]);
});
it("backs off a failed lookup and recovers unrelated creations in the same pass", async () => {
loseReply = true; await expect(acquire()).rejects.toThrow("Lost provider reply");
const [first] = await db.select().from(sandboxCreationOperations);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
runId = randomUUID(); await db.insert(heartbeatRuns).values({ ...run!, id: runId });
await expect(acquire()).rejects.toThrow("Lost provider reply");
const originalCall = workers.call;
(workers as any).call = vi.fn(async (plugin: string, method: string, params: any, timeout: any) => {
if (method === "environmentInspectLease" && params.creationOperation.id === first!.id) throw new Error("Transient fixture lookup");
return originalCall(plugin, method as any, params, timeout);
});
await due(); await runtime().flushDeferredOrphanCleanups();
const rows = await db.select().from(sandboxCreationOperations);
expect(rows.find(value => value.id === first!.id)).toMatchObject({ state: "pending" });
expect(rows.find(value => value.id === first!.id)!.nextAttemptAt.getTime()).toBeGreaterThan(Date.now());
expect(rows.filter(value => value.state === "cleanup_pending")).toHaveLength(1);
});
it("does not attach a sandbox to a run stopped during creation", async () => {
beforeReply = async () => { await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, runId)); };
await expect(acquire()).rejects.toThrow("run authority changed");
expect(await db.select().from(environmentLeases)).toHaveLength(0);
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([expect.objectContaining({ status: "pending_cleanup" })]);
});
it.each(["before lookup", "during lookup", "lookup fails after deletion"])("records manual reconciliation when the company is deleted %s", async (deletion) => {
loseReply = true; await expect(acquire()).rejects.toThrow("Lost provider reply");
async function deleteCompany() {
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
await db.delete(agents).where(eq(agents.companyId, companyId));
await db.delete(companies).where(eq(companies.id, companyId));
}
if (deletion === "before lookup") await deleteCompany();
const originalCall = workers.call;
const calls = vi.fn(async (plugin: string, method: string, params: any, timeout: any) => {
if (method === "environmentInspectLease" && deletion !== "before lookup") {
await deleteCompany();
if (deletion === "lookup fails after deletion") throw new Error("Company credential no longer exists");
}
return originalCall(plugin, method as any, params, timeout);
});
(workers as any).call = calls;
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(sandboxCreationOperations)).toEqual([
expect.objectContaining({ companyId, state: "needs_reconciliation", metadata: expect.objectContaining({ creationReconciliationReason: "company_deleted" }) }),
]);
expect(await db.select().from(environmentLeases)).toEqual([]);
expect(calls.mock.calls.filter(value => value[1] === "environmentInspectLease")).toHaveLength(deletion === "before lookup" ? 0 : 1);
const count = calls.mock.calls.length;
await runtime().flushDeferredOrphanCleanups(); await runtime().flushDeferredOrphanCleanups();
expect(calls).toHaveBeenCalledTimes(count);
expect(await nextEnvironmentCleanupAt(db)).toBeNull(); expect(creates).toBe(1);
expect(await readdir(spool)).toEqual([]);
});
async function savedCreationCredential(providerConfigId?: string) {
const secrets = secretOwner.secretService(db);
const secret = await secrets.create(companyId, {
name: `creation-key-${randomUUID()}`, provider: "local_encrypted", providerConfigId, value: "fixture-private-key",
});
await secrets.createBinding({ companyId, secretId: secret.id, targetType: "environment", targetId: environmentId, configPath: "apiKey" });
await db.update(plugins).set({ manifestJson: sql`jsonb_set(${plugins.manifestJson}, '{environmentDrivers,0,configSchema}',
'{"type":"object","properties":{"apiKey":{"type":"string","format":"secret-ref"}}}'::jsonb)` }).where(eq(plugins.id, pluginId));
announcePluginManifestChange();
await db.update(environments).set({ config: { provider: "creation-fixture", image: "fixture", reuseLease: false, apiKey: secret.id } })
.where(eq(environments.id, environmentId));
loseReply = true;
await expect(acquire()).rejects.toThrow("Lost provider reply");
return secret;
}
it.each(["deleted", "disabled", "archived", "version-disabled", "vault-disabled", "vault-coming-soon"] as const)(
"retains a %s creation credential with a quiet worker while sleep remains blocked across restart", async state => {
const secrets = secretOwner.secretService(db);
const vault = state.startsWith("vault-") ? await secrets.createProviderConfig(companyId, {
provider: "local_encrypted", displayName: "Creation vault", status: "ready", config: {},
}) : undefined;
const secret = await savedCreationCredential(vault?.id);
if (state === "deleted") await secrets.remove(secret.id);
else if (state === "disabled" || state === "archived") await secrets.update(secret.id, { status: state });
else if (state === "version-disabled") await db.update(companySecretVersions).set({ status: "disabled" })
.where(eq(companySecretVersions.secretId, secret.id));
else await secrets.updateProviderConfig(vault!.id, { status: state === "vault-disabled" ? "disabled" : "coming_soon" });
const inspectCalls = () => vi.mocked(workers.call).mock.calls.filter(value => value[1] === "environmentInspectLease").length;
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(sandboxCreationOperations)).toEqual([
expect.objectContaining({ companyId, state: "needs_reconciliation",
metadata: expect.objectContaining({ creationReconciliationReason: "creation_identity_unavailable" }) }),
]);
expect(resources.size).toBe(1);
expect(await db.select().from(environmentLeases)).toEqual([]);
expect(inspectCalls()).toBe(0);
expect(await nextEnvironmentCleanupAt(db)).toBeNull();
const restarted = runtime();
await restarted.flushDeferredOrphanCleanups(); await restarted.flushDeferredOrphanCleanups();
expect(inspectCalls()).toBe(0); expect(creates).toBe(1); expect(destroys).toBe(0);
expect(await nextEnvironmentCleanupAt(db)).toBeNull();
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
const ownerId = randomUUID();
const hold = { ownerId, draining: true, startedAt: new Date(Date.now() - 1000), expiresAt: new Date(Date.now() + 60_000), activeRuns: 0, pendingWakes: 0 };
// A quiet plugin worker cannot discharge the retained creation uncertainty.
expect(await readIdleSleepSafety(db, () => hold, Date.now, ownerId, async () => "none"))
.toEqual({ version: 1, backgroundWork: "present" });
expect(await readIdleSleepSafety(db, () => hold, Date.now, ownerId, async () => "none",
async () => ({ backgroundWork: "none", pluginIds: [pluginId] })))
.toEqual({ version: 1, backgroundWork: "present" });
expect(await readdir(spool)).toEqual([]);
});
it("retries a temporary creation credential resolution failure without losing ownership", async () => {
await savedCreationCredential();
const original = secretOwner.secretService;
const resolution = vi.fn(async () => { throw new HttpError(503, "Temporary credential provider failure"); });
const owner = vi.spyOn(secretOwner, "secretService").mockImplementation(client => ({
...original(client), resolveSecretValueForSandboxCleanup: resolution,
}));
try {
await due(); await runtime().flushDeferredOrphanCleanups();
expect(resolution).toHaveBeenCalledTimes(1);
expect(await db.select().from(sandboxCreationOperations)).toEqual([
expect.objectContaining({ state: "pending", nextAttemptAt: expect.any(Date) }),
]);
expect(await nextEnvironmentCleanupAt(db)).toBeGreaterThan(Date.now());
expect(vi.mocked(workers.call).mock.calls.filter(value => value[1] === "environmentInspectLease")).toHaveLength(0);
} finally { owner.mockRestore(); }
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(sandboxCreationOperations)).toEqual([expect.objectContaining({ state: "cleanup_pending" })]);
expect(await db.select().from(environmentLeases)).toHaveLength(1);
expect(creates).toBe(1); expect(destroys).toBe(0); expect(await readdir(spool)).toEqual([]);
});
it("makes unsupported uncertain outcomes explicit without another creation", async () => {
loseReply = true; await expect(acquire()).rejects.toThrow();
await db.update(plugins).set({ manifestJson: sql`${plugins.manifestJson} #- '{environmentDrivers,0,creationOperationVersion}'` }).where(eq(plugins.id, pluginId));
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(sandboxCreationOperations)).toEqual([expect.objectContaining({ state: "needs_reconciliation" })]);
expect(await nextEnvironmentCleanupAt(db)).toBeNull();
await expect(acquire()).rejects.toThrow("requires reconciliation"); expect(creates).toBe(1);
});
describe("after the creating server exits mid-acquire", () => {
async function exitedPid(): Promise<number> {
const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" });
await new Promise(resolve => child.once("exit", resolve));
return child.pid!;
}
// The provider allocated the sandbox; the server exited before committing the lease.
async function interruptedCreation(controller: (current: Record<string, unknown>) => Promise<Record<string, unknown>>) {
loseReply = true;
await expect(acquire()).rejects.toThrow("Lost provider reply");
const [operation] = await db.select().from(sandboxCreationOperations);
expect(operation).toMatchObject({ state: "pending" });
expect(operation!.nextAttemptAt.getTime()).toBeGreaterThan(Date.now() + 25 * 60_000);
const current = operation!.metadata.creationController as Record<string, unknown>;
await db.update(sandboxCreationOperations).set({ metadata: { ...operation!.metadata, creationController: await controller(current) } })
.where(eq(sandboxCreationOperations.id, operation!.id));
return operation!;
}
const inspections = () => vi.mocked(workers.call).mock.calls.filter(value => value[1] === "environmentInspectLease");
it("destroys the sandbox on the next sweep instead of waiting for the settle deadline", async () => {
const pid = await exitedPid();
const operation = await interruptedCreation(async current => ({ ...current, bootId: randomUUID(), pid }));
await runtime().flushDeferredOrphanCleanups();
const [lease] = await db.select().from(environmentLeases);
expect(lease).toMatchObject({ status: "pending_cleanup", companyId, providerLeaseId: resources.get(operation.id),
failureReason: "interrupted_sandbox_creation" });
expect(await db.select().from(sandboxCreationOperations)).toEqual([expect.objectContaining({ state: "cleanup_pending", leaseId: lease!.id })]);
await runtime().retryPendingSandboxTeardown({ environment: null, lease: (await environmentService(db).getLeaseById(lease!.id))! });
expect(resources.size).toBe(0); expect(destroys).toBe(1); expect(creates).toBe(1);
});
it("pages past more unprovable creations than one settle page (200) to find an abandoned one", async () => {
const pid = await exitedPid();
const operation = await interruptedCreation(async current => ({ ...current, bootId: randomUUID(), pid }));
const { id: _id, runId: _runId, ...row } = operation;
// Sorted ahead of the abandoned intent: creators on another host cannot be judged.
await db.insert(sandboxCreationOperations).values(Array.from({ length: 205 }, (_, index) => ({ ...row,
id: `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`, runId: randomUUID(),
metadata: { ...row.metadata, creationController: { ...(row.metadata.creationController as object), bootId: randomUUID(), pid, hostHash: "f".repeat(32) } } })));
await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([expect.objectContaining({ status: "pending_cleanup",
providerLeaseId: resources.get(operation.id) })]);
});
it("reclaims an issue-bound creation after its run failed and the issue finished on a later run", async () => {
// Mirrors a kept chaos database: the server was SIGKILLed 0.5 s after the
// intent committed, the run ended process_lost, and a later run finished
// the task. The intent stayed pending with no lease.
const pid = await exitedPid();
const operation = await interruptedCreation(async current => ({ ...current, bootId: randomUUID(), pid }));
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
const issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Restart-crossing task", status: "done" });
await db.update(sandboxCreationOperations).set({ issueId }).where(eq(sandboxCreationOperations.id, operation.id));
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "process_lost", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, runId));
await db.insert(heartbeatRuns).values({ ...run!, id: randomUUID(), status: "succeeded", finishedAt: new Date() });
expect(await db.select().from(sandboxCreationOperations)).toEqual([
expect.objectContaining({ state: "pending", leaseId: null, issueId, runId }),
]);
await runtime().flushDeferredOrphanCleanups();
const [lease] = await db.select().from(environmentLeases);
expect(lease).toMatchObject({ status: "pending_cleanup", companyId, providerLeaseId: resources.get(operation.id) });
await runtime().retryPendingSandboxTeardown({ environment: null, lease: (await environmentService(db).getLeaseById(lease!.id))! });
expect(resources.size).toBe(0); expect(destroys).toBe(1); expect(creates).toBe(1);
});
it("treats a restarted server that reused the creator PID as a different process", async () => {
await interruptedCreation(async current => ({ ...current, bootId: randomUUID(),
processStartedAt: new Date(Date.parse(String(current.processStartedAt)) - 60_000).toISOString() }));
await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([expect.objectContaining({ status: "pending_cleanup" })]);
});
it("leaves a creation owned by this live server untouched until its deadline", async () => {
await interruptedCreation(async current => current);
await runtime().flushDeferredOrphanCleanups();
expect(inspections()).toHaveLength(0);
expect(await db.select().from(environmentLeases)).toEqual([]);
expect(await db.select().from(sandboxCreationOperations)).toEqual([expect.objectContaining({ state: "pending" })]);
expect(resources.size).toBe(1); expect(destroys).toBe(0);
});
it("leaves a creation owned by another live server process untouched", async () => {
const pid = process.ppid;
const startedAt = await readProcessStartedAt(pid);
await interruptedCreation(async current => ({ ...current, bootId: randomUUID(), pid, processStartedAt: startedAt }));
await runtime().flushDeferredOrphanCleanups();
expect(inspections()).toHaveLength(0);
expect(await db.select().from(environmentLeases)).toEqual([]);
expect(resources.size).toBe(1);
});
it("does not judge a creator on another host", async () => {
const pid = await exitedPid();
await interruptedCreation(async current => ({ ...current, bootId: randomUUID(), pid, hostHash: "f".repeat(32) }));
await runtime().flushDeferredOrphanCleanups();
expect(inspections()).toHaveLength(0);
expect(await db.select().from(environmentLeases)).toEqual([]);
expect(resources.size).toBe(1);
});
it("keeps ownership when an early lookup finds no sandbox yet", async () => {
const pid = await exitedPid();
const operation = await interruptedCreation(async current => ({ ...current, bootId: randomUUID(), pid }));
const resource = resources.get(operation.id)!;
resources.delete(operation.id); // Not materialized at the provider yet.
await runtime().flushDeferredOrphanCleanups();
expect(inspections()).toHaveLength(1);
const [pending] = await db.select().from(sandboxCreationOperations);
expect(pending).toMatchObject({ state: "pending" });
expect(pending!.nextAttemptAt.getTime()).toBeGreaterThan(Date.now());
// A late allocation is still found and removed by the retained owner.
resources.set(operation.id, resource);
await due(); await runtime().flushDeferredOrphanCleanups();
expect(await db.select().from(environmentLeases)).toEqual([expect.objectContaining({ status: "pending_cleanup", providerLeaseId: resource })]);
});
it("never touches a sandbox whose lease was committed", async () => {
const { lease } = await acquire();
const pid = await exitedPid();
const [operation] = await db.select().from(sandboxCreationOperations);
expect(operation).toMatchObject({ state: "attached" });
await db.update(sandboxCreationOperations).set({ metadata: { ...operation!.metadata,
creationController: { ...(operation!.metadata.creationController as object), bootId: randomUUID(), pid } } });
await runtime().flushDeferredOrphanCleanups();
expect(inspections()).toHaveLength(0);
expect(await environmentService(db).getLeaseById(lease.id)).toMatchObject({ status: "active" });
expect(resources.size).toBe(1); expect(destroys).toBe(0);
});
});
});