mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
fix: cancel stalled sandbox startup without waiting for setup (#13352)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Sandbox runs prepare credentials and files before an agent starts. > - Stop must work during that preparation. > - ACPX registered cancellation, but did not handle it while a setup command was waiting. > - Daytona cleanup waited for that same command before stopping the sandbox. > - This change stops the run's sandbox first and requires proof before abandoning setup. ## Linked Issues or Issue Description **What happened?** Stop left a sandbox run active when remote credential setup stalled. The run kept its connection lease until the sandbox was stopped separately. **Expected behavior** Stop terminates the selected run's sandbox, prevents later setup from launching the agent, and lets run cleanup finish. It must not report success without proof from the provider. **Steps to reproduce** 1. Start an ACPX agent in Daytona. 2. Hold a command during remote credential or file setup. 3. Select Stop before the agent starts. 4. Before this fix, cleanup waits for the held command and never reaches sandbox stop. Related: #13351 exposed this during connection acceptance testing. #12150 addresses scheduler load and session initialization limits, a separate startup problem. ## What Changed - Handle cancellation during ACPX sandbox preparation with a host-owned stop callback. - Pass an explicit active-work cancellation flag through environment cleanup. - Stop Daytona before draining setup commands. Keep normal graceful cleanup. - Require an exact run and lease termination receipt. Keep ownership of outstanding requests when stop cannot be verified. - Reject late setup work and defer sandbox resume until old requests settle. - Add regression tests and document the cancellation boundary. ## Verification - Red: both the stalled ACPX setup test and the Daytona cancellation test failed before the fix because Stop never reached the provider. - Green: adapter and Daytona suites passed, along with cancellation boundary and database-backed receipt/isolation tests. - Two real Daytona probes ran a five-minute setup command. Cancellation returned matching stopped receipts in 6.01 and 6.533 seconds. No later setup command ran. Both test sandboxes were deleted. - Repository typecheck and build passed locally. The full required CI suite passed, including all server/workspace tests, browser shards, Paperclip Runner verification, and canary packaging. The duplicate local full-suite run was interrupted after CI passed; it is not claimed as a completed local pass. - No UI changes. The live probe uses the actual adapter cancellation boundary and Daytona plugin; it is not a browser acceptance test. ## Risks - Provider stop failures remain unacknowledged. The adapter keeps ownership while its original requests remain active. - A retry can receive a settling-work error until old provider requests finish. - Cancelled sandboxes are stopped and retained under their existing provider expiry policy. - Local execution and cancellation after the agent turn starts keep their current behavior. - Other providers must return an exact termination receipt to permit early setup cancellation. No database migration. ## Model Used OpenAI GPT-6 through Codex, with code execution and tool use. The exact deployment identifier and context window are not exposed in this session. ## 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 Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
c9e3bb7ca4
commit
827ba8a434
14 files changed
+450
-18
No files matched your search
@@ -255,6 +255,20 @@ describe("environmentRunOrchestrator — realizeForRun", () => {
|
||||
mockLogActivity.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it.each([false, true])("only requests active-work cancellation for explicit Stop: %s", async (cancelActiveWork) => {
|
||||
const releaseRunLeases = vi.fn().mockResolvedValue([]);
|
||||
const runtime = makeMockRuntime({ releaseRunLeases });
|
||||
const orchestrator = environmentRunOrchestrator(mockDb, { environmentRuntime: runtime });
|
||||
await orchestrator.releaseForRun({
|
||||
heartbeatRunId: "run-1", companyId: "company-1", agentId: "agent-1",
|
||||
providerResourceDisposition: "stop_and_retain", cancelActiveWork,
|
||||
});
|
||||
expect(releaseRunLeases).toHaveBeenCalledWith(
|
||||
"run-1", "released", expect.any(Function), "stop_and_retain",
|
||||
...(cancelActiveWork ? [true] : []),
|
||||
);
|
||||
});
|
||||
|
||||
it("happy path: returns lease, executionTarget, and remoteExecution on successful realization", async () => {
|
||||
const executionTarget = { kind: "local", environmentId: "env-1", leaseId: "lease-1" };
|
||||
const remoteExecution = { kind: "local", environmentId: "env-1", leaseId: "lease-1" };
|
||||
|
||||
@@ -39,6 +39,7 @@ import * as sandboxProviderRuntime from "../services/sandbox-provider-runtime.ts
|
||||
import * as environmentsModule from "../services/environments.ts";
|
||||
import { logger } from "../middleware/logger.ts";
|
||||
import { environmentService } from "../services/environments.ts";
|
||||
import { remoteExecutionHasStopped } from "../services/remote-execution-termination.ts";
|
||||
import { heartbeatService } from "../services/heartbeat.ts";
|
||||
import { secretService } from "../services/secrets.ts";
|
||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.ts";
|
||||
@@ -463,6 +464,34 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
|
||||
return { pluginId, companyId, agentId, environment, runId, executionWorkspaceId, reusableLease };
|
||||
}
|
||||
|
||||
it.each(["stopped", "missing", "wrong-lease", "error"])(
|
||||
"startup cancellation is run-scoped and needs a matching receipt: %s",
|
||||
async (outcome) => {
|
||||
const { pluginId, companyId, runId, reusableLease, environment } = await seedReusablePluginSandboxLease();
|
||||
const other = await environmentService(db).acquireLease({
|
||||
companyId, environmentId: environment.id, heartbeatRunId: null,
|
||||
leasePolicy: "ephemeral", provider: "fake-plugin", providerLeaseId: "other-sandbox",
|
||||
});
|
||||
const call = vi.fn(async () => {
|
||||
if (outcome === "error") throw new Error("provider unavailable");
|
||||
if (outcome === "missing") return undefined;
|
||||
return { providerLeaseId: outcome === "wrong-lease" ? "other-sandbox" : reusableLease.providerLeaseId, state: "stopped" };
|
||||
});
|
||||
const workerManager = {
|
||||
isRunning: () => true, call,
|
||||
getWorker: () => ({ supportedMethods: ["environmentReleaseLease"] }),
|
||||
} as unknown as PluginWorkerManager;
|
||||
const runtimeWithPlugin = environmentRuntimeService(db, { pluginWorkerManager: workerManager });
|
||||
await runtimeWithPlugin.releaseRunLeases(runId, "released", undefined, "stop_and_retain", true);
|
||||
expect(call).toHaveBeenCalledWith(pluginId, "environmentReleaseLease", expect.objectContaining({
|
||||
companyId, providerLeaseId: reusableLease.providerLeaseId, cancelActiveWork: true,
|
||||
}), expect.any(Number));
|
||||
expect(call).toHaveBeenCalledOnce();
|
||||
expect(await remoteExecutionHasStopped(db, companyId, runId)).toBe(outcome === "stopped");
|
||||
await expect(environmentService(db).getLeaseById(other.id)).resolves.toMatchObject({ status: "active" });
|
||||
},
|
||||
);
|
||||
|
||||
it("retains a successful reusable sandbox lease without stopping the provider resource", async () => {
|
||||
const { pluginId, runId, reusableLease } = await seedReusablePluginSandboxLease();
|
||||
const workerManager = {
|
||||
|
||||
@@ -584,6 +584,8 @@ export function environmentRunOrchestrator(
|
||||
agentId: string;
|
||||
status?: Extract<EnvironmentLeaseStatus, "released" | "expired" | "failed">;
|
||||
failureReason?: string;
|
||||
/** Explicit Stop during adapter startup; never used for ordinary cleanup. */
|
||||
cancelActiveWork?: boolean;
|
||||
/** Explicit paperclip_runner resource lifecycle. Omitted for legacy adapters. */
|
||||
providerResourceDisposition?: ProviderResourceDisposition;
|
||||
nativeLifecycleTelemetry?: {
|
||||
@@ -606,6 +608,7 @@ export function environmentRunOrchestrator(
|
||||
status,
|
||||
(leaseId, error) => result.errors.push({ leaseId, error }),
|
||||
input.providerResourceDisposition,
|
||||
...(input.cancelActiveWork ? [true] as const : []),
|
||||
);
|
||||
} catch (err) {
|
||||
result.errors.push({ leaseId: "*", error: err });
|
||||
|
||||
@@ -477,6 +477,8 @@ export interface EnvironmentDriverAcquireInput {
|
||||
}
|
||||
|
||||
export interface EnvironmentDriverReleaseInput {
|
||||
/** Explicit Stop may terminate in-flight setup rather than drain it. */
|
||||
cancelActiveWork?: boolean;
|
||||
environment: Environment;
|
||||
lease: EnvironmentLease;
|
||||
status: Extract<EnvironmentLeaseStatus, "released" | "expired" | "failed">;
|
||||
@@ -3032,9 +3034,11 @@ function createSandboxEnvironmentDriver(
|
||||
config: stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig),
|
||||
providerLeaseId: input.lease.providerLeaseId,
|
||||
leaseMetadata: metadata,
|
||||
...(input.cancelActiveWork ? { cancelActiveWork: true } : {}),
|
||||
}, resolvePluginSandboxRpcTimeoutMs(stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig))),
|
||||
);
|
||||
termination = remoteTerminationReceipt(input.lease, receipt);
|
||||
if (input.cancelActiveWork && !termination) cleanupStatus = "failed";
|
||||
} catch {
|
||||
cleanupStatus = "failed";
|
||||
}
|
||||
@@ -3699,6 +3703,7 @@ export function environmentRuntimeService(
|
||||
status: Extract<EnvironmentLeaseStatus, "released" | "expired" | "failed"> = "released",
|
||||
onLeaseReleaseError?: (leaseId: string, error: unknown) => void,
|
||||
providerResourceDisposition?: ProviderResourceDisposition,
|
||||
cancelActiveWork?: boolean,
|
||||
): Promise<EnvironmentRuntimeLeaseRecord[]> {
|
||||
const leaseRows = await db
|
||||
.select()
|
||||
@@ -3781,6 +3786,7 @@ export function environmentRuntimeService(
|
||||
})
|
||||
: driver
|
||||
? await driver.releaseRunLease({
|
||||
...(cancelActiveWork ? { cancelActiveWork: true } : {}),
|
||||
environment,
|
||||
lease: leaseSnapshot,
|
||||
// A stopped reusable provider resource must remain eligible
|
||||
|
||||
@@ -23724,6 +23724,26 @@ export function heartbeatService(
|
||||
},
|
||||
onDispatch: markDispatchStarted,
|
||||
signal: executionControl.controller.signal,
|
||||
...(executionTarget?.kind === "remote" && executionTarget.transport === "sandbox" ? {
|
||||
stopRemoteStartup: async () => {
|
||||
// Scope comes from the running host invocation, never agent
|
||||
// config. Keep adapter ownership until setup has unwound.
|
||||
if (!executionControl.controller.signal.aborted) {
|
||||
throw new Error("Remote startup stop requires a cancelled run");
|
||||
}
|
||||
const release = await envOrchestrator.releaseForRun({
|
||||
heartbeatRunId: run.id,
|
||||
companyId: agent.companyId,
|
||||
agentId: agent.id,
|
||||
status: "released",
|
||||
providerResourceDisposition: "stop_and_retain",
|
||||
cancelActiveWork: true,
|
||||
});
|
||||
if (release.errors.length || !await remoteExecutionHasStopped(db, agent.companyId, run.id)) {
|
||||
throw new Error("Could not verify remote startup stopped");
|
||||
}
|
||||
},
|
||||
} : {}),
|
||||
onCancellationReady: async () => {
|
||||
await registerAdapterExecutionControl(run.id, executionControl);
|
||||
const current = await getRun(run.id);
|
||||
|
||||
Reference in new issue
Block a user