Skip to content

The open-source app everyone uses to manage agents at work

fix(runner): bootstrap fresh sessions in replacement sandboxes (#17320)

Dottabf223596ab78
diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md
index 72afc0345c..4b2df094f3 100644
--- a/doc/execution-semantics.md
+++ b/doc/execution-semantics.md
@@ -1780,6 +1780,15 @@ timeout retain the one-minute host default. A resume failure still preserves
the recorded sandbox unless the provider proves it lost and replacement passes
the existing backup checks.
+A replacement workspace can also host a newly admitted provider session that
+has never run. That session may start without a backup only when its durable
+identity matches the current run, runner and lease, it has no connections or
+committed events, and all commands are pending bootstrap commands. The runner
+must atomically claim an absent remote session directory under real, readable
+parents. Existing session files, prior activity, missing proof or any saved
+backup retain the verified-restore requirement. Workspace replacement alone
+never authorizes a provider-session reset.
+
For the native runner, warm mode requests a reusable sandbox lease **before**
lease acquisition. The environment's explicit runner lifecycle overrides the
agent default; an inherited lifecycle uses the current agent setting on each
diff --git a/maps/agent-access-map/runs-adapters.md b/maps/agent-access-map/runs-adapters.md
index 6453e64178..be3a21b69a 100644
--- a/maps/agent-access-map/runs-adapters.md
+++ b/maps/agent-access-map/runs-adapters.md
@@ -275,6 +275,14 @@ Gaps: Task-session listing and execution-context reset require board agent
management at their HTTP routes. Native `call_api` preserves these denials; native
continuation remains server-owned.
+Scoped source evidence: replacement of a workspace may bootstrap a newly
+admitted provider session only with matching current run/runner/lease identity,
+no prior activity or backup, and an atomic claim of an absent remote session
+directory. Existing sessions retain verified restore. This adds no reset or
+cleanup authority. Follow the [session recipe](../feature-map/runs-adapters.md#session)
+with a board-owned disposable fixture; live provider and actor-access evidence
+remain separate from the executor regressions.
+
Scoped source-only evidence: [configuration changes](../../server/src/services/agent-configuration.ts)
and [native execution/recovery](../../server/src/services/native-runtime/native-session-executor.ts)
retain existing execution on unrelated edits and use recorded run configuration
diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.md
index 564f4598fe..b03352698e 100644
--- a/maps/feature-map/runs-adapters.md
+++ b/maps/feature-map/runs-adapters.md
@@ -46,6 +46,25 @@ turn; do not count a nested discovery interval twice.
Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Record adapter, model, account, native/legacy runtime, and environment. Capabilities vary; one harness result is not a matrix-wide qualification.
+### `session`
+
+For `runs-adapters/session`, complete a task in a disposable warm sandbox and
+retain its saved workspace file. Let the warm session close normally and verify
+that the retained lease has a complete, lease-bound harness backup before
+injecting sandbox loss. Removing a still-warm sandbox before that checkpoint
+exercises the separate acquisition safety gate, which must remain blocked.
+Use a board-authorized session reset, then remove only that fixture's inactive
+provider sandbox. Send a follow-up that
+reads the retained file and appends one new line. Verify a replacement sandbox,
+a new provider session, the exact file contents, successful finalization and no
+stranded task lock. Send another follow-up and verify ordinary session reuse.
+
+Repeat without resetting the session: its replacement must restore verified
+history or remain blocked. Missing backup state must not silently start an
+existing session again. The [executor controls](../../server/src/services/native-runtime/native-session-executor.test.ts)
+cover the bootstrap identity, activity and atomic directory claim; those
+controls do not establish live provider acceptance.
+
### `adapter-setup`
Automated: [adapter validation routes](../../server/src/__tests__/agent-adapter-validation-routes.test.ts) and [model refresh](../../server/src/__tests__/adapter-model-refresh-routes.test.ts) cover server behavior.
diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts
index 0817436873..2dc81a2d16 100644
--- a/server/src/services/native-runtime/native-session-executor.test.ts
+++ b/server/src/services/native-runtime/native-session-executor.test.ts
@@ -79,7 +79,7 @@ import {
import { nativeRuntimeContextFixture } from "./runtime-context.test-fixture.js";
import { nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
import * as nativeSessionResume from "./native-session-resume.js";
-import { buildNativeHeartbeatPreparationSpans } from "./native-run-trace.js";
+import { buildNativeHeartbeatPreparationSpans, createNativeRunTrace } from "./native-run-trace.js";
import { NativeRunnerOwnershipUnverifiedError } from "./native-runner-ownership.js";
import type { AdapterRuntimeEvent } from "../../adapters/index.js";
import type { AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";
@@ -13283,8 +13283,10 @@ describe("runnerd provider runtime wiring", () => {
}
});
- it.each(["fresh", "existing_state", "symlink_parent", "wrong_identity", "connected", "pending_turn", "remote_probe_failed", "backup_present"])(
- "bootstraps only an untouched provider session in a resumed workspace lease: %s", async (scenario) => {
+ it.each(["resumed", "replacement"].flatMap((outcome) =>
+ ["fresh", "existing_state", "symlink_parent", "wrong_identity", "wrong_runner", "wrong_lease", "missing_control_plane", "connected", "committed_event", "committed_command", "pending_turn", "remote_probe_failed", "backup_present"]
+ .map((scenario) => ({ outcome, scenario }))))(
+ "bootstraps only an untouched provider session in a $outcome workspace lease: $scenario", async ({ outcome, scenario }) => {
const remoteCwd = join(isolatedStateDirectory, "remote");
const runtimeRoot = join(remoteCwd, ".paperclip-runtime", "paperclip-runner");
await mkdir(runtimeRoot, { recursive: true });
@@ -13321,14 +13323,16 @@ describe("runnerd provider runtime wiring", () => {
});
const runtimeContext = nativeRuntimeContextFixture();
const executionWithContext = { ...execution, runtimeContext };
+ const onTraceEvent = vi.fn(async (_event: AdapterRuntimeEvent) => undefined);
const backend = await createRunnerdBackend({
db: leaseDb(execution), execution: executionWithContext, runnerInstanceId: "runner-new-in-retained-workspace",
+ trace: createNativeRunTrace({ runId: execution.binding.runId, onEvent: onTraceEvent }),
runnerIngressAuthorized: true,
runnerExecutionTarget: {
kind: "remote", transport: "sandbox", remoteCwd, environmentId: "environment",
leaseId: "lease-resumed", providerKey: "daytona",
effectiveCapabilities: { runnerWebSocketIngress: true },
- sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox-retained" },
+ sandboxLeaseAcquisition: { outcome, providerLeaseId: "sandbox-acquired", reason: outcome === "replacement" ? "not_found" : undefined },
runner: { execute: remoteExecute, syncIn },
} as never,
});
@@ -13341,16 +13345,30 @@ describe("runnerd provider runtime wiring", () => {
await mkdir(join(options.stateDirectory!, "control-plane"), { recursive: true });
await writeFile(join(options.stateDirectory!, "control-plane", "control-plane-state.json"), JSON.stringify({
schema: "paperclip.runner.durable.control-plane-state.v1",
- identity: { ...options.prpIdentity, ...(scenario === "wrong_identity" ? { runId: "other-run" } : {}) },
- connectionCount: scenario === "connected" ? 1 : 0, committedEvents: [],
- commands: [{ type: "run.prepare", status: "pending" }, { type: scenario === "pending_turn" ? "turn.start" : "session.open", status: "pending" }],
+ identity: { ...options.prpIdentity,
+ ...(scenario === "wrong_identity" ? { runId: "other-run" } : {}),
+ ...(scenario === "wrong_runner" ? { runnerInstanceId: "other-runner" } : {}),
+ ...(scenario === "wrong_lease" ? { environmentLeaseId: "other-lease" } : {}) },
+ connectionCount: scenario === "connected" ? 1 : 0,
+ committedEvents: scenario === "committed_event" ? [{ type: "session.opened" }] : [],
+ commands: [{ type: "run.prepare", status: scenario === "committed_command" ? "committed" : "pending" },
+ { type: scenario === "pending_turn" ? "turn.start" : "session.open", status: "pending" }],
}));
+ if (scenario === "missing_control_plane") {
+ await rm(join(options.stateDirectory!, "control-plane", "control-plane-state.json"));
+ }
if (scenario === "backup_present") {
await mkdir(join(options.stateDirectory!, "failover-backups", "current"), { recursive: true });
await writeFile(join(options.stateDirectory!, "failover-backups", "current", "manifest.json"), "{}");
}
if (scenario === "fresh") {
await expect(options.prepareExternalRunnerState()).resolves.toBeUndefined();
+ expect(onTraceEvent).toHaveBeenCalledWith(expect.objectContaining({
+ payload: expect.objectContaining({
+ span: "sandbox.lease.acquisition",
+ stateSource: outcome === "replacement" ? "new_sandbox" : "sandbox_filesystem",
+ }),
+ }));
expect(remoteExecute.mock.calls.some(([command]) => command.args?.[1]?.includes("install -d"))).toBe(false);
expect(syncIn).not.toHaveBeenCalled();
const claimCommand = remoteExecute.mock.calls.find(([command]) => command.args?.[2] === "paperclip-runner-claim-unstarted-session")![0];
@@ -13384,8 +13402,11 @@ describe("runnerd provider runtime wiring", () => {
})]);
expect(remoteExecute.mock.calls.filter(([command]) => command.args?.[2] === "paperclip-runner-claim-unstarted-session")).toHaveLength(1);
} else {
- await expect(options.prepareExternalRunnerState()).rejects.toThrow("runner_harness_state_mismatch");
+ await expect(options.prepareExternalRunnerState()).rejects.toThrow(
+ outcome === "replacement" ? "runner_harness_backup_unavailable" : "runner_harness_state_mismatch",
+ );
expect(remoteExecute.mock.calls.some(([command]) => command.args?.[1]?.includes("install -d"))).toBe(false);
+ expect(syncIn).not.toHaveBeenCalled();
}
});
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index e749ee4831..65fa5c31ed 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -12416,14 +12416,14 @@ async function createRunnerdBackendWithinSessionClaim(
};
};
- const claimUntouchedSessionInResumedLease = async (): Promise<boolean> => {
+ const claimUntouchedRemoteSession = async (): Promise<boolean> => {
if (!remoteCommandRunner || !remoteRuntimeRoot || !remoteSessionRoot) return false;
const identity = readRunnerdDurableIdentity(root);
if (!durableIdentityMatchesExecution(identity, input.execution) ||
identity?.runnerInstanceId !== effectiveRunnerInstanceId ||
identity?.environmentLeaseId !== effectiveEnvironmentLeaseId ||
!runnerdStateProvesIncompleteBootstrap(root)) return false;
- // A reusable workspace may have failed before any harness was created.
+ // Workspace reuse or replacement can acquire a lease for a new session.
// Claim this exact new session atomically under readable real directories.
// Missing files inside an existing session never authorize a fresh start.
const probe = await remoteCommandRunner.execute({
@@ -12609,6 +12609,15 @@ async function createRunnerdBackendWithinSessionClaim(
(candidate) =>
existsSync(resolve(candidate, "manifest.json")),
);
+ // Workspace replacement is independent of provider-session
+ // continuity. Decide the source before recording acquisition.
+ const freshReplacement =
+ sandboxLeaseAcquisition?.outcome === "replacement" &&
+ !backupAvailable && await measureNativeRunnerSpan(
+ input.trace,
+ "harness_state.bootstrap_claim",
+ claimUntouchedRemoteSession,
+ );
const restoreIntoCreatedSandbox =
shouldRestoreNativeHarnessBackupIntoSandbox({
acquisitionOutcome:
@@ -12628,12 +12637,14 @@ async function createRunnerdBackendWithinSessionClaim(
input.execution.session.lifecyclePolicy.mode,
outcome: sandboxLeaseAcquisition?.outcome ?? "unknown",
stateSource:
- sandboxLeaseAcquisition?.outcome === "replacement" ||
- restoreIntoCreatedSandbox
- ? "verified_failover_backup"
- : sandboxLeaseAcquisition?.outcome === "resumed"
- ? "sandbox_filesystem"
- : "new_sandbox",
+ freshReplacement
+ ? "new_sandbox"
+ : sandboxLeaseAcquisition?.outcome === "replacement" ||
+ restoreIntoCreatedSandbox
+ ? "verified_failover_backup"
+ : sandboxLeaseAcquisition?.outcome === "resumed"
+ ? "sandbox_filesystem"
+ : "new_sandbox",
bytesTransferred: 0,
},
});
@@ -12659,7 +12670,7 @@ async function createRunnerdBackendWithinSessionClaim(
!state.providerSessionIdentity
) {
if (state.incompleteReason !== "unavailable" || backupAvailable ||
- !(await claimUntouchedSessionInResumedLease())) {
+ !(await claimUntouchedRemoteSession())) {
throw new Error(`runner_harness_state_mismatch: resumed_${state.incompleteReason}`);
}
} else {
@@ -12674,7 +12685,9 @@ async function createRunnerdBackendWithinSessionClaim(
await measureNativeRunnerSpan(
input.trace,
"sandbox.lease.replacement",
- restoreVerifiedHarnessBackup,
+ async () => {
+ if (!freshReplacement) await restoreVerifiedHarnessBackup();
+ },
{
attributes: {
provider: remoteTarget.providerKey ?? "sandbox",