Repository navigation
feat(sandbox): retain E2B sandboxes between calls #3413
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
59dfa1a
57a239f
3496b96
c750376
a9d0933
b0ffd84
f011df7
1cc69bf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -72,6 +72,10 @@ public class E2bSandbox extends AbstractBaseSandbox implements SandboxFileTransf | |
| */ | ||
| private NativeSnapshotPlan nativeSnapshotPlan = NativeSnapshotPlan.DEFAULT; | ||
|
|
||
| // Only this start's allocation may be destroyed if initialization fails. | ||
| private String sandboxCreatedDuringStart; | ||
| private boolean workspaceProbeFailed; | ||
|
|
||
| public E2bSandbox(E2bSandboxState state, E2bSandboxClientOptions opt) { | ||
| super(alignWorkspaceRoot(state)); | ||
| this.e2bState = state; | ||
|
|
@@ -93,14 +97,34 @@ private static E2bSandboxState alignWorkspaceRoot(E2bSandboxState state) { | |
|
|
||
| @Override | ||
| public void start() throws Exception { | ||
| sandboxCreatedDuringStart = null; | ||
| workspaceProbeFailed = false; | ||
| if (WorkspaceMountSupport.hasBindMounts(e2bState.getWorkspaceSpec())) { | ||
| log.warn( | ||
| "[sandbox-e2b] WorkspaceSpec contains bind_mount entries; " | ||
| + "E2B does not apply host bind mounts — paths are not mounted."); | ||
| } | ||
| nativeSnapshotPlan = NativeSnapshotPlan.DEFAULT; | ||
| boolean workspaceReadyBeforeStart = e2bState.isWorkspaceRootReady(); | ||
| String projectionBeforeStart = e2bState.getWorkspaceProjectionHash(); | ||
| // Connection failures have not touched workspace metadata. Keep them outside the | ||
| // workspace-start recovery path; a confirmed expiry may already have invalidated it. | ||
| ensureSandbox(); | ||
| super.start(); | ||
| try { | ||
| super.start(); | ||
| } catch (Exception e) { | ||
| if (workspaceProbeFailed && sandboxCreatedDuringStart == null) { | ||
| // Only a failed read-only probe proves initialization never began. Once the probe | ||
| // succeeds, setup, restore, entries or projection may have partially changed files. | ||
| e2bState.setWorkspaceRootReady(workspaceReadyBeforeStart); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Warning] Preserving |
||
| e2bState.setWorkspaceProjectionHash(projectionBeforeStart); | ||
| } else { | ||
| // AbstractBaseSandbox has already marked the workspace unready. Also invalidate | ||
| // its projection so retry cannot skip reapplying it over a restored snapshot. | ||
| e2bState.setWorkspaceProjectionHash(null); | ||
| } | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
|
|
@@ -134,6 +158,42 @@ public void stop() throws Exception { | |
| } | ||
| } | ||
|
|
||
| /** | ||
| * Returns whether this local handle is between successful start and stop, and has not been | ||
| * explicitly deleted. This is not a remote liveness probe: a retained instance can still exist | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Info] Closing the loop on the two
|
||
| * after stop has made this method return false. | ||
| */ | ||
| @Override | ||
| public boolean isRunning() { | ||
| // Explicit deletion bypasses stop() so it never uploads a final workspace snapshot. | ||
| return super.isRunning() && e2bState.getSandboxId() != null; | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Info] |
||
| } | ||
|
|
||
| /** Attempts snapshot pruning without destroying the retained instance. */ | ||
| @Override | ||
| public void onRetained() { | ||
| if (e2bState.isSandboxOwned()) { | ||
| // stop() has persisted the latest snapshot. Locked templates remain recorded so a | ||
| // later retained release or explicit shutdown can retry; never drop failed deletions. | ||
| cleanupSnapshots(); | ||
| } | ||
| } | ||
|
|
||
| /** Destroys only the instance allocated by this start; existing retained instances survive. */ | ||
| @Override | ||
| public void cleanupAfterStartFailure() throws Exception { | ||
| if (e2bState.isSandboxOwned() && sandboxCreatedDuringStart != null) { | ||
| platform.killSandbox(sandboxCreatedDuringStart); | ||
| if (sandboxCreatedDuringStart.equals(e2bState.getSandboxId())) { | ||
| e2bState.setSandboxId(null); | ||
| e2bState.setWorkspaceRootReady(false); | ||
| e2bState.setWorkspaceProjectionHash(null); | ||
| } | ||
| sandboxCreatedDuringStart = null; | ||
| // No snapshot GC: the stored archive still belongs to the previous successful call. | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void shutdown() throws Exception { | ||
| if (!e2bState.isSandboxOwned()) { | ||
|
|
@@ -145,8 +205,9 @@ public void shutdown() throws Exception { | |
| // A successful kill invalidates the id and avoids a dead reconnect on resume. | ||
| e2bState.setSandboxId(null); | ||
| } | ||
| // Only after killSandbox are the snapshot templates unlocked by E2B (deleting them while a | ||
| // sandbox restored from one runs returns 400), so clean up here to converge to retention. | ||
| e2bState.setWorkspaceRootReady(false); | ||
| e2bState.setWorkspaceProjectionHash(null); | ||
| // Destroying the sandbox unlocks templates that a retained release could not prune. | ||
| cleanupSnapshots(); | ||
| } | ||
|
|
||
|
|
@@ -163,7 +224,28 @@ protected boolean probeWorkspaceRootForPreservedResume() { | |
| // recreations, so treat it as preserved without probing. | ||
| return true; | ||
| } | ||
| return super.probeWorkspaceRootForPreservedResume(); | ||
| try { | ||
| ExecResult result = | ||
| doExec( | ||
| null, | ||
| "test -d " + shellSingleQuote(getWorkspaceRoot()), | ||
| PROBE_TIMEOUT_SECONDS); | ||
| if (result.exitCode() == 0) { | ||
| return true; | ||
| } | ||
| if (result.exitCode() == 1) { | ||
| return false; | ||
| } | ||
| throw new SandboxException.ExecException( | ||
| result.exitCode(), result.stdout(), result.stderr()); | ||
| } catch (Exception e) { | ||
| workspaceProbeFailed = true; | ||
| // A failed probe does not prove files are missing. Restoring here could overwrite them. | ||
| throw new SandboxException.SandboxRuntimeException( | ||
| SandboxErrorCode.WORKSPACE_START_ERROR, | ||
| "Cannot probe retained E2B workspace", | ||
| e); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
|
|
@@ -298,8 +380,10 @@ public byte[] downloadFile(String absolutePath) throws Exception { | |
|
|
||
| private void ensureSandbox() throws Exception { | ||
| JsonNode sandbox; | ||
| boolean created = false; | ||
| if (e2bState.getSandboxId() == null || e2bState.getSandboxId().isBlank()) { | ||
| sandbox = createSandboxForRestore(); | ||
| created = true; | ||
| } else if (!e2bState.isSandboxOwned()) { | ||
| sandbox = platform.getSandbox(e2bState.getSandboxId()); | ||
| if (sandbox.hasNonNull("sandboxID") | ||
|
|
@@ -313,17 +397,23 @@ private void ensureSandbox() throws Exception { | |
| platform.connectSandbox( | ||
| e2bState.getSandboxId(), opt.getSandboxTimeoutSeconds()); | ||
| nativeSnapshotPlan = NativeSnapshotPlan.DEFAULT; | ||
| } catch (Exception e) { | ||
| if (!opt.isRecreateOnConnectFailure()) { | ||
| } catch (E2bPlatformHttp.PlatformHttpException e) { | ||
| // Only a confirmed expiry may replace the instance. Other errors keep the existing | ||
| // id, which may belong to a retained and still running sandbox, for a retry. | ||
| if (e.statusCode() != 404 || !opt.isRecreateOnConnectFailure()) { | ||
| throw e; | ||
| } | ||
| log.warn("[sandbox-e2b] connect failed, recreating sandbox: {}", e.getMessage()); | ||
| log.warn("[sandbox-e2b] sandbox expired, recreating: {}", e.getMessage()); | ||
| sandbox = createSandboxForRestore(); | ||
| created = true; | ||
| e2bState.setWorkspaceRootReady(false); | ||
| e2bState.setWorkspaceProjectionHash(null); | ||
| } | ||
| } | ||
| platform.applySandboxFields(e2bState, sandbox); | ||
| if (created) { | ||
| sandboxCreatedDuringStart = e2bState.getSandboxId(); | ||
| } | ||
| applyDefaultDomain(); | ||
| envd = null; | ||
| } | ||
|
|
@@ -476,6 +566,7 @@ private void restoreSandboxFromSnapshotTemplate(String snapshotTemplateId, byte[ | |
| String oldId = e2bState.getSandboxId(); | ||
| JsonNode created = createFromSnapshot(snapshotTemplateId, archive); | ||
| platform.applySandboxFields(e2bState, created); | ||
| sandboxCreatedDuringStart = e2bState.getSandboxId(); | ||
| applyDefaultDomain(); | ||
| if (e2bState.isSandboxOwned() | ||
| && oldId != null | ||
|
|
@@ -496,8 +587,8 @@ private void cleanupSnapshots() { | |
| return; | ||
| } | ||
| // One-shot correction regardless of any earlier residue: keep the last retention ids by | ||
| // insertion order (most recent last) and delete the rest. E2B only unlocks the | ||
| // templates after killSandbox, so this runs on shutdown. | ||
| // insertion order (most recent last) and delete the rest. Templates still in use may | ||
| // reject deletion; the platform helper keeps failed ids for a later retry. | ||
| try { | ||
| List<String> kept = platform.cleanupSnapshots(e2bState.getSnapshotIds(), retention); | ||
| e2bState.setSnapshotIds(kept); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,6 +18,7 @@ | |
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import io.agentscope.harness.agent.sandbox.Sandbox; | ||
| import io.agentscope.harness.agent.sandbox.SandboxClient; | ||
| import io.agentscope.harness.agent.sandbox.SandboxErrorCode; | ||
| import io.agentscope.harness.agent.sandbox.SandboxException; | ||
| import io.agentscope.harness.agent.sandbox.SandboxState; | ||
| import io.agentscope.harness.agent.sandbox.WorkspaceSpec; | ||
|
|
@@ -130,8 +131,31 @@ public Sandbox resume(SandboxState state) { | |
| return new E2bSandbox(e2b, resumed); | ||
| } | ||
|
|
||
| /** | ||
| * Destroys an owned E2B sandbox without creating a final snapshot. Safe to retry after expiry; | ||
| * failures are propagated and keep the sandbox id available for retry. Snapshot pruning obeys | ||
| * snapshotRetention; this does not erase retained backups or the harness state-store entry. | ||
| * Non-owned instances are left unchanged. | ||
| */ | ||
| @Override | ||
| public void delete(Sandbox sandbox) { | ||
| if (!(sandbox instanceof E2bSandbox)) { | ||
| throw new IllegalArgumentException("Expected an E2bSandbox"); | ||
| } | ||
| try { | ||
| // Do not stop/snapshot here: explicit deletion must also work after provider expiry. | ||
| sandbox.shutdown(); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Info] |
||
| } catch (Exception e) { | ||
| throw new SandboxException.SandboxRuntimeException( | ||
| SandboxErrorCode.WORKSPACE_STOP_ERROR, "Failed to delete E2B sandbox", e); | ||
| } | ||
| } | ||
|
|
||
| /** E2B supports reusing live instances between SDK-managed calls. */ | ||
| @Override | ||
| public void delete(Sandbox sandbox) {} | ||
| public boolean supportsRetention() { | ||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public String serializeState(SandboxState state) { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Info] Correct fix for the over-broad metadata preservation, and the narrowing holds in both directions.
workspaceProbeFailedis reachable only from the catch inprobeWorkspaceRootForPreservedResume(), i.e. from the read-onlytest -dbefore anything is written, so the preserve branch now covers exactly the failures that provably cannot have mutated the tree. Everything later (doSetupWorkspace,snapshot.restore, spec apply, projection apply) falls into the else branch, and nulling the projection hash there is the right pairing with theworkspaceRootReady=falseAbstractBaseSandbox.start()already applied — otherwise a retry could take Branch A off a stale hash and skip reapplying a projection over a restored snapshot.Three edge cases I traced and found clean, so you do not have to re-check them:
ExecExceptioninside the try, is caught by that same catch, so the flag is still set andabnormalProbeExitPreservesWorkspaceAndCanRetrykeeps its meaning;ensureSandbox()out of the try does not strand a new allocation: ifapplyDefaultDomain()throws aftersandboxCreatedDuringStartis set,SandboxLifecycleMiddleware's catch still routes RETAIN failures throughSandboxManager.discard()→cleanupAfterStartFailure(), which kills only that id; and metadata is left untouched, which is precisely the outcome you want for a connect failure;ensureSandbox()throws after already clearingready/projection, the next attempt keeps the old expired id, re-connects, gets 404 again and recreates — it converges, and re-projection is forced rather than skipped.failedProbeOfNewAllocationDoesNotRestoreStaleReadyMetadatais the case I was actually worried about (a fresh allocation inheritingready=truefrom the instance it replaced) and the parameterizedretryAfterWorkspaceMutationFailureRestoresInsteadOfTrustingPartialTreecovers the three mutation stages separately, including theentriescase wherefirst.txtis deliberately asserted to survive. Good tests.