mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(runner): re-qualify a stale sandbox snapshot proof instead of blocking runs (#22835)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Runner on a Daytona sandbox pins the snapshot that a saved qualification proof measured. > - The proof goes stale when the snapshot, the config or a captured image changes. It also goes stale when a qualification probe stops before it finishes. > - Lease admission then failed every run with `sandbox_snapshot_qualification_required`. Only a person who selected Run test could clear it. > - Recovery must work without a person. A config change or a deploy must not leave runs that need a click. > - This pull request makes lease admission run the same qualification probe by itself, then pin the newly qualified snapshot. > - The benefit is that runs continue after an image change. A run still never starts on an unpinned snapshot name. ## Linked Issues or Issue Description **What happened?** On a hosted staging instance, every Paperclip Runner run on the managed "Paperclip Sandbox" environment failed at setup for about 40 minutes. The error was `sandbox_snapshot_qualification_required: The snapshot qualification is missing or stale. Open the agent's Harness / Runtime page and select Run test`. Three agents were blocked. The run was not retried. The failures stopped only after a person selected Run test. **Expected behavior** A stale saved proof is re-checked automatically. The run continues on the qualified snapshot. No person needs to select Run test. **Steps to reproduce** 1. Use a Daytona snapshot environment that has a saved v2 snapshot proof. 2. Change the snapshot, or interrupt a qualification probe, so that the proof is stale or invalidated. 3. Make sure the managed-image bypass does not apply. For example, a managed row whose provider is not in the live managed config `environments` section. 4. Start a Paperclip Runner run. Before this fix, admission throws `sandbox_snapshot_qualification_required` and does not try again. Root cause: The managed row's saved proof was from 2026-10-28, when a person last selected Run test. The fleet snapshot changed several times after that, so the proof was stale. That had no effect while `usesManagedCloudSandboxImage` returned true. When that check returned false, the stale proof became a hard stop. The check needs the live managed config to list the provider, with no active captured image. The existing `unowned-marker` test shows that this stops the run. I could not read the server environment to confirm which input changed at that time. This fix therefore covers the whole class: a stale proof is re-qualified, whatever made it stale. Refs #18066, Refs #17445 ## What Changed - `acquireRunLease` no longer fails when a saved snapshot proof is stale or invalidated. It runs the same probe as the agent's Run test (`probeEnvironment` with `acquireSandboxRuntimeLease`). It then reads the recorded proof again and pins the qualified snapshot ID. - Only one re-qualification runs for each environment and company at a time in a server process. The in-flight probes are shared by all runtime instances. Admission reads the saved proof again before it probes, so a run that comes after a successful re-check does not probe again. - A failed re-check answers later runs for the same saved config for two minutes. A queue of runs behind a broken snapshot starts one probe sandbox, not one for each run. A config change starts a new probe at once. - If the re-check cannot prove the snapshot, the run still fails before it gets a run lease. The run error uses only controlled text. Raw provider error text, which can contain credentials, stays out of the run error. The message does not tell a person to fix the sandbox. - Tests: a new regression test reproduces the staging case. It also starts a second run through a different runtime while the probe is held open, and checks that only one probe lease starts. A second new test checks that a provider error with a token does not reach the run error, and that two runs one after the other start only one probe after a failure. The `unowned-marker` and `changed-base`/`changed-runtime` cases now check that the only provider lease is the qualification probe (`resolveSnapshotIdentity: true`). No run lease uses an unpinned name. ## Verification - Red/green: the new test `re-qualifies a stale snapshot proof by itself instead of blocking the run until someone selects Run test` fails on master with the exact staging error. It passes with this fix. - `npx vitest run src/__tests__/environment-runtime.test.ts src/__tests__/environment-probe.test.ts src/__tests__/agent-runner-qualification-routes.test.ts src/services/agent-runner-selection.test.ts`: 505 passed on the first commit. `environment-runtime.test.ts`: 217 passed on the final head, two runs in a row. - The single-probe and failure-reuse tests fail when the shared map or the failure reuse is removed. - `tsc --noEmit -p server/tsconfig.json` passes. - After deploy, I will check staging: Paperclip Runner runs on the managed sandbox reach a lease without anyone selecting Run test. ## Risks - When a proof is stale, the first run after the change waits for one extra probe sandbox (boot, `uname`, release) before its own lease. This happens once for each environment and company until the snapshot changes again. Runs with a valid proof, and runs on the managed-image bypass, do not change. - A probe that fails still stops the run with `sandbox_snapshot_qualification_required`. The pinning guarantee does not change. - For two minutes after a failed re-check, runs for that environment fail without a new probe. After that, the next run checks again. - Server replicas do not share in-flight probes. Each replica can start at most one probe, and the first success records the proof for all of them. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, browser for staging forensics). ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d02774f404
commit
fb900bf0fe
2 files changed
+147
-3
No files matched your search
@@ -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<void>(resolve => { releaseProbe = resolve; });
|
||||
let probeStarted!: () => void;
|
||||
const probeRunning = new Promise<void>(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<string, any>)[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([]);
|
||||
|
||||
@@ -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<string, Promise<{ environment: Environment | null; reason: string | null }>>();
|
||||
/** 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 };
|
||||
|
||||
Reference in new issue
Block a user