diff --git a/server/src/__tests__/environment-runtime.test.ts b/server/src/__tests__/environment-runtime.test.ts index 97379964644..394c1d0f48d 100644 --- a/server/src/__tests__/environment-runtime.test.ts +++ b/server/src/__tests__/environment-runtime.test.ts @@ -383,8 +383,12 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { persistedExecutionWorkspace: null, adapterType: "paperclip_runner", }); if (qualification === "unowned-marker") { + // The stale proof is re-checked automatically. That probe cannot prove + // this snapshot, so the run still never starts on an unpinned name. await expect(acquire).rejects.toThrow("sandbox_snapshot_qualification_required"); - expect(worker.call).not.toHaveBeenCalled(); + const leaseCalls = vi.mocked(worker.call).mock.calls.filter(([, method]) => method === "environmentAcquireLease"); + expect(leaseCalls).toHaveLength(1); + expect(leaseCalls[0]![2]).toMatchObject({ resolveSnapshotIdentity: true, config: expect.objectContaining({ archiveOnRelease: true, reuseLease: false }) }); return; } if (qualification === "provider-failure") { @@ -398,6 +402,88 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { expect(acquired.lease.metadata?.snapshot).toBe(config.snapshot); }); + it("re-qualifies a stale snapshot proof by itself instead of blocking the run until someone selects Run test", async () => { + // Staging 2026-11-24: the managed row's provider was not in the live managed + // config, so the managed-image bypass did not apply, and its saved proof was + // for an older snapshot. Every run failed at setup until a person clicked Run test. + vi.stubEnv("PAPERCLIP_MANAGED_CONFIG", JSON.stringify({ ...managedCloudConfig, environments: [] })); + const pluginId = randomUUID(); + const { companyId, environment: baseEnvironment, runId } = await seedEnvironment(); + const config = { provider: "daytona", snapshot: "fleet-sbx-current" }; + const snapshotId = "b7c0f8e1-0997-482b-a572-751ee49f9e10"; + await insertSandboxProviderPlugin(pluginId, { environmentDrivers: [{ driverKey: "daytona", kind: "sandbox_provider", displayName: "Daytona", configSchema: { type: "object" } }] }); + await db.update(environments).set({ driver: "sandbox", config, metadata: { managedByPaperclip: true, + paperclipSandboxPlatformProbes: { [companyId]: { v: 2, companyId, snapshot: "fleet-sbx-previous", template: null, + baseConfigFingerprint: "previous-config", runtimeConfigFingerprint: "previous-config", + snapshotIdentity: { provider: "daytona", requestedRef: "fleet-sbx-previous", id: "a6b9e7d0-f886-471a-b461-640dd03e8d0f", + name: "fleet-sbx-previous", organizationId: "provider-account", createdAt: "2026-10-07T23:19:57.133Z" } } }, + } }).where(eq(environments.id, baseEnvironment.id)); + const environment = (await environmentService(db).getById(baseEnvironment.id))!; + const worker = createFreshPluginLeaseWorker(pluginId); + let leases = 0; + let releaseProbe!: () => void; + const probeHeld = new Promise(resolve => { releaseProbe = resolve; }); + let probeStarted!: () => void; + const probeRunning = new Promise(resolve => { probeStarted = resolve; }); + vi.mocked(worker.call).mockImplementation(async (_id, method, params: any) => { + if (method === "environmentAcquireLease") { + leases += 1; + if (params.resolveSnapshotIdentity) { probeStarted(); await probeHeld; } + return { providerLeaseId: `lease-${leases}`, metadata: { provider: "daytona", snapshot: params.config.snapshot, remoteCwd: "/workspace", + ...(params.resolveSnapshotIdentity ? { snapshotIdentity: { provider: "daytona", requestedRef: config.snapshot, id: snapshotId, + name: config.snapshot, organizationId: "provider-account", createdAt: "2026-11-24T21:00:00.000Z" } } : {}) } }; + } + if (method === "environmentExecute") return { exitCode: 0, signal: null, timedOut: false, stdout: "Linux\nx86_64\nglibc\nglibc 2.39\n", stderr: "" }; + if (method === "environmentReleaseLease") return { providerLeaseId: params.providerLeaseId, state: "archived" }; + throw new Error(`Unexpected ${method}`); + }); + vi.mocked(worker.getWorker).mockReturnValue({ supportedMethods: ["environmentExecute", "environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"] } as never); + // Routes build separate runtimes. A run that arrives through another runtime + // while the probe is still running joins that probe instead of starting one. + const acquire = (heartbeatRunId: string | null) => environmentRuntimeService(db, { pluginWorkerManager: worker }).acquireRunLease({ + companyId, environment, issueId: null, heartbeatRunId, persistedExecutionWorkspace: null, adapterType: "paperclip_runner" }); + const first = acquire(runId); + await probeRunning; + const pendingSecond = acquire(null); + await new Promise(resolve => setTimeout(resolve, 50)); + expect(leases).toBe(1); + releaseProbe(); + const [acquired, second] = await Promise.all([first, pendingSecond]); + expect(acquired.lease.metadata?.snapshot).toBe(snapshotId); + expect(second.lease.metadata?.snapshot).toBe(snapshotId); + expect(vi.mocked(worker.call).mock.calls.filter(([, method, params]: any[]) => method === "environmentAcquireLease" && params.resolveSnapshotIdentity)).toHaveLength(1); + const proof = ((await environmentService(db).getById(environment.id))!.metadata?.paperclipSandboxPlatformProbes as Record)[companyId]; + expect(proof).toMatchObject({ v: 2, snapshot: config.snapshot, snapshotIdentity: { id: snapshotId } }); + expect(proof).not.toHaveProperty("invalidated"); + }); + + it("keeps provider error text out of the run error when automatic re-qualification fails", async () => { + vi.stubEnv("PAPERCLIP_MANAGED_CONFIG", JSON.stringify({ ...managedCloudConfig, environments: [] })); + const pluginId = randomUUID(); + const { companyId, environment: baseEnvironment, runId } = await seedEnvironment(); + await insertSandboxProviderPlugin(pluginId, { environmentDrivers: [{ driverKey: "daytona", kind: "sandbox_provider", displayName: "Daytona", configSchema: { type: "object" } }] }); + await db.update(environments).set({ driver: "sandbox", config: { provider: "daytona", snapshot: "fleet-sbx-current" }, metadata: { managedByPaperclip: true, + paperclipSandboxPlatformProbes: { [companyId]: { v: 2, companyId, snapshot: "fleet-sbx-previous", template: null, invalidated: true } } } }) + .where(eq(environments.id, baseEnvironment.id)); + const environment = (await environmentService(db).getById(baseEnvironment.id))!; + const worker = createFreshPluginLeaseWorker(pluginId); + vi.mocked(worker.call).mockImplementation(async (_id, method) => { + if (method === "environmentAcquireLease") throw new Error("upstream rejected token sk-live-secret-value"); + throw new Error(`Unexpected ${method}`); + }); + const runtime = environmentRuntimeService(db, { pluginWorkerManager: worker }); + // Two runs one after the other: the failed check answers both, so only one probe sandbox boots. + for (const heartbeatRunId of [runId, null]) { + const failure = await runtime.acquireRunLease({ companyId, environment, + issueId: null, heartbeatRunId, persistedExecutionWorkspace: null, adapterType: "paperclip_runner" }).catch((error: Error) => error); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain("sandbox_snapshot_qualification_required"); + expect((failure as Error).message).toContain("The check sandbox could not start."); + expect((failure as Error).message).not.toContain("sk-live-secret-value"); + } + expect(vi.mocked(worker.call).mock.calls.filter(([, method]) => method === "environmentAcquireLease")).toHaveLength(1); + }); + it("forwards the run's warm idle window to the provider worker without changing lease identity", async () => { const pluginId = randomUUID(); const { companyId, environment: baseEnvironment, runId } = await seedEnvironment(); @@ -504,7 +590,9 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { if (state !== "qualified") { expect(result.executionTarget).toBeNull(); expect(result.fallbackChecks).toMatchObject([{ code: "environment_lease_acquire_failed", detail: expect.stringContaining("sandbox_snapshot_qualification_required") }]); - expect(worker.call).not.toHaveBeenCalled(); + const leaseCalls = vi.mocked(worker.call).mock.calls.filter(([, method]) => method === "environmentAcquireLease"); + expect(leaseCalls).toHaveLength(1); + expect(leaseCalls[0]![2]).toMatchObject({ resolveSnapshotIdentity: true }); return; } expect(result.fallbackChecks).toEqual([]); diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts index bbf5cca1120..6731cdc6001 100644 --- a/server/src/services/environment-runtime.ts +++ b/server/src/services/environment-runtime.ts @@ -1332,6 +1332,15 @@ function adaptDuplexChannelHostSession( }; } +/** One automatic snapshot re-qualification per environment and company at a + * time in this process. Routes and services each build their own runtime, so + * the pending probes are shared across all of them: a burst of runs behind one + * stale proof boots one probe sandbox. */ +const sandboxSnapshotRequalifications = new Map>(); +/** A failed re-check answers later runs for the same saved config for this + * long, so a queue of runs behind a broken snapshot boots one probe, not one each. */ +const FAILED_SANDBOX_REQUALIFICATION_REUSE_MS = 2 * 60_000; + function createSandboxEnvironmentDriver( db: Db, options: { @@ -1665,6 +1674,39 @@ function createSandboxEnvironmentDriver( }); } + function requalifyStaleSandboxSnapshot(environment: Environment, companyId: string) { + const environmentId = environment.id; + const key = `${environmentId}:${companyId}:${stableStringify(environment.config)}`; + const pending = sandboxSnapshotRequalifications.get(key); + if (pending) return pending; + const run = (async () => { + const environments = environmentService(db); + const current = await environments.getById(environmentId); + if (!current || current.driver !== "sandbox") return { environment: null, reason: null }; + const { probeEnvironment } = await import("./environment-probe.js"); + const result = await probeEnvironment(db, current, { + companyId, pluginWorkerManager, applyCustomImageTemplate: true, + acquireSandboxRuntimeLease: true, assertCompanyBinding: true, + }); + // Only controlled diagnostics reach the run error; provider exception + // text can carry credentials and stays in the probe result. + const reason = result.ok + ? (typeof result.details?.platformQualificationDiagnostic === "string" ? result.details.platformQualificationDiagnostic : null) + : "The check sandbox could not start. Paperclip tries again in a few minutes."; + return { environment: await environments.getById(environmentId), reason, + recorded: result.ok && result.details?.platformQualificationRecorded === true }; + })().then( + ({ recorded, ...outcome }) => { + if (recorded) sandboxSnapshotRequalifications.delete(key); + else setTimeout(() => sandboxSnapshotRequalifications.delete(key), FAILED_SANDBOX_REQUALIFICATION_REUSE_MS).unref?.(); + return outcome; + }, + (error: unknown) => { sandboxSnapshotRequalifications.delete(key); throw error; }, + ); + sandboxSnapshotRequalifications.set(key, run); + return run; + } + return { driver: "sandbox", @@ -1693,7 +1735,21 @@ function createSandboxEnvironmentDriver( if (input.adapterType === "paperclip_runner" && !usesManagedCloudSandboxImage(configuredEnvironment, selectedTemplate.value)) { pinnedSnapshotId = qualifiedSandboxSnapshotId(configuredEnvironment, input.companyId, parsed.config, selectedTemplate.value); if (!pinnedSnapshotId && hasSandboxSnapshotQualification(configuredEnvironment, input.companyId)) { - throw new Error("sandbox_snapshot_qualification_required: The snapshot qualification is missing or stale. Open the agent's Harness / Runtime page and select Run test before running Paperclip Runner."); + // A saved proof goes stale whenever its snapshot, config or captured + // image changes, or a probe is interrupted. Re-run the same check the + // agent's Run test performs instead of waiting for a person to click it. + // Another run may have just re-qualified it; read the saved proof first. + const saved = await environmentService(db).getById(configuredEnvironment.id); + pinnedSnapshotId = saved ? qualifiedSandboxSnapshotId(saved, input.companyId, parsed.config, selectedTemplate.value) : null; + if (!pinnedSnapshotId) { + const requalified = await requalifyStaleSandboxSnapshot(saved ?? configuredEnvironment, input.companyId); + if (requalified.environment) { + pinnedSnapshotId = qualifiedSandboxSnapshotId(requalified.environment, input.companyId, parsed.config, selectedTemplate.value); + } + if (!pinnedSnapshotId) { + throw new Error(`sandbox_snapshot_qualification_required: Paperclip could not re-check this sandbox image before starting Paperclip Runner.${requalified.reason ? ` ${requalified.reason}` : ""}`); + } + } } } if (input.configuredEnvironment) parsed.config = { ...parsed.config, reuseLease: storedParsed.config.reuseLease, archiveOnRelease: storedParsed.config.archiveOnRelease };