Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.agentscope.harness.agent.filesystem.spec.SandboxFilesystemSpec;
import io.agentscope.harness.agent.sandbox.SandboxClient;
import io.agentscope.harness.agent.sandbox.SandboxClientOptions;
import io.agentscope.harness.agent.sandbox.SandboxReleasePolicy;
import io.agentscope.harness.agent.sandbox.WorkspaceSpec;
import io.agentscope.harness.agent.sandbox.snapshot.NoopSnapshotSpec;
import io.agentscope.harness.agent.sandbox.snapshot.SandboxSnapshotSpec;
Expand All @@ -33,6 +34,12 @@ public class E2bFilesystemSpec extends SandboxFilesystemSpec {
private WorkspaceSpec defaultWorkspaceSpec;
private boolean explicitWorkspaceRoot;

@Override
public E2bFilesystemSpec releasePolicy(SandboxReleasePolicy policy) {
super.releasePolicy(policy);
return this;
}

public E2bFilesystemSpec client(SandboxClient<?> client) {
this.client = client;
return this;
Expand Down Expand Up @@ -160,7 +167,7 @@ public E2bFilesystemSpec maxRetries(int maxRetries) {
}

/**
* Maximum number of snapshots created by this session that are kept on shutdown; {@code <= 0}
* Target number of snapshots created by this session kept after release; {@code <= 0}
* disables pruning. Defaults to {@code 0} (disabled), matching the historical no-pruning
* behaviour. See {@link E2bSandboxClientOptions#setSnapshotRetention(int)} for the full
* contract.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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) {

Copy link
Copy Markdown
Collaborator

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.

workspaceProbeFailed is reachable only from the catch in probeWorkspaceRootForPreservedResume(), i.e. from the read-only test -d before 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 the workspaceRootReady=false AbstractBaseSandbox.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:

  • a non-0/1 probe exit throws ExecException inside the try, is caught by that same catch, so the flag is still set and abnormalProbeExitPreservesWorkspaceAndCanRetry keeps its meaning;
  • hoisting ensureSandbox() out of the try does not strand a new allocation: if applyDefaultDomain() throws after sandboxCreatedDuringStart is set, SandboxLifecycleMiddleware's catch still routes RETAIN failures through SandboxManager.discard() → cleanupAfterStartFailure(), which kills only that id; and metadata is left untouched, which is precisely the outcome you want for a connect failure;
  • if the 404-expiry recreate inside ensureSandbox() throws after already clearing ready/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.

failedProbeOfNewAllocationDoesNotRestoreStaleReadyMetadata is the case I was actually worried about (a fresh allocation inheriting ready=true from the instance it replaced) and the parameterized retryAfterWorkspaceMutationFailureRestoresInsteadOfTrustingPartialTree covers the three mutation stages separately, including the entries case where first.txt is deliberately asserted to survive. Good tests.

// 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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] Preserving workspaceRootReady whenever sandboxCreatedDuringStart == null also covers failures that happen after the workspace was already mutated. Reaching super.start() with workspaceRootReady == true and a probe that returns true still runs applyWorkspaceSpec(...)/projection work; if that throws mid-way, the tree is partially initialized while the restored flag now claims it is intact. On the next call Branch A applies only ephemeral entries, so a half-restored workspace is silently treated as good. Could the preserve be narrowed to the pre-mutation phase (failure from ensureSandbox() or the probe) — e.g. a workspaceMutated flag set right before doSetupWorkspace()/doHydrateWorkspace()/applyWorkspaceSpec() — and keep the old setWorkspaceRootReady(false) behaviour for everything after that point?

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;
}
}

/**
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Closing the loop on the two Info items from the previous pass:

  • this javadoc is the fix I was after for isRunning() — AbstractBaseSandbox.stop() clears running on a successful RETAIN, so the method reports local handle state and not remote existence, and saying so here is better than making the method try to be a liveness probe. The new retention test asserts the same semantics from outside (assertFalse(first.isRunning(), ...) with the remote instance still alive), which keeps the wording honest;
  • PROBE_TIMEOUT_SECONDS going private → protected and being referenced here instead of a second 10 removes the silent-coupling risk, and AgentRunSandbox's override keeps its own literal, so nothing else moved.

delete()'s added Non-owned instances are left unchanged line answers the last one too.

* 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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] AbstractBaseSandbox.stop() already sets running = false, so a retained sandbox reports isRunning() == false right after a successful RETAIN release, and this override adds a second condition that is only false in the never-started case. If isRunning() is meant to mean "the remote instance is reachable", consider a distinct method (e.g. hasRemoteInstance()); as written the two semantics are conflated and callers cannot tell "retained and alive" from "gone".

}

/** 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()) {
Expand All @@ -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();
}

Expand All @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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;
}
Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] delete() now delegates to sandbox.shutdown(), which returns immediately when !e2bState.isSandboxOwned(), so deleting a non-owned/external sandbox is a silent no-op while the method's javadoc reads as an unconditional destroy. Worth saying "only when the SDK owns the instance" in the javadoc. Minor: the failure is wrapped as a generic SandboxRuntimeException(WORKSPACE_STOP_ERROR, ...) although the existing SandboxException.WorkspaceStopException carries the same code plus the cause type — using it would keep error handling consistent with the rest of the backend.

} 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,20 +63,24 @@ public class E2bSandboxClientOptions extends SandboxClientOptions {
private int maxRetries = 3;

/**
* Maximum number of snapshots created by this session that are kept on shutdown; {@code <= 0}
* Target number of snapshots created by this session kept after release; {@code <= 0}
* disables pruning. Defaults to {@code 0} (disabled), matching the historical no-pruning
* behaviour.
*
* <p>Pruning runs once in {@link E2bSandbox#shutdown} after the sandbox is killed (E2B locks a
* snapshot template while a sandbox restored from it is running, so deleting earlier returns
* HTTP 400). The session records every snapshot id it creates in {@link
* <p>Pruning runs in {@link E2bSandbox#shutdown} after destruction, or in
* {@link E2bSandbox#onRetained} after successful snapshot persistence under RETAIN. E2B locks a
* template while a sandbox restored from it runs; failed deletions remain recorded for retry.
* Retention is therefore a best-effort target, not a hard bound while a sandbox is retained.
* Provider expiry alone does not run cleanup: another release or explicit delete must do so.
* The session records every snapshot id it creates in {@link
* E2bSandboxState#getSnapshotIds()} in creation order (most recent last); cleanup keeps the
* last {@code snapshotRetention} recorded ids and deletes the rest via {@code DELETE
* /templates/{snapshotId}} (404 is treated as already deleted). Snapshots never recorded in
* this list — e.g. created by other sessions, or by a run whose state was never persisted —
* are never touched. Blank ids are dropped and duplicates collapsed (first occurrence wins)
* before counting. A snapshot whose deletion fails is kept in the record so a later
* shutdown can retry, which may temporarily leave more than {@code snapshotRetention} ids
* release or explicit delete can retry, which may temporarily leave more than
* {@code snapshotRetention} ids
* recorded. A failed stop removes the id its own persist recorded, so the record always
* matches the archive and unconditional cleanup never removes the referenced snapshot (ids
* recorded concurrently by another session over the same state are left alone); the price is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ void clientMergeOverridesAndNullHandling() throws Exception {
assertTrue(e.getMessage().contains("Expected E2bSandboxState"));
}

// delete is no-op
// Deleting a not-yet-started sandbox requires no remote request
client.delete(s);
// serialize/deserialize round-trip with snapshotIds
E2bSandboxState withIds = new E2bSandboxState();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ void tearDown() throws Exception {

@Test
void recreateClearsStaleWorkspaceProjectionState() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
server.enqueue(
new MockResponse()
.setResponseCode(200)
Expand Down Expand Up @@ -102,7 +102,7 @@ void reconnectPreservesWorkspaceProjectionState() throws Exception {

@Test
void startFallsBackToTemplateWhenNativeSnapshotIsMissing() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("snapshot not found"));
server.enqueue(sandboxResponse("fresh-sandbox"));
server.enqueue(envdStartResponse());
Expand All @@ -127,7 +127,7 @@ void startFallsBackToTemplateWhenNativeSnapshotIsMissing() throws Exception {

@Test
void startFailsOnSnapshotCreateServerErrorWithoutTemplateFallback() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
server.enqueue(new MockResponse().setResponseCode(500).setBody("snapshot unavailable"));
E2bSandboxState state = stateForResumeWithNativeSnapshot("snap-123");

Expand All @@ -149,7 +149,7 @@ void startFailsOnSnapshotCreateServerErrorWithoutTemplateFallback() throws Excep

@Test
void startFailsWhenSnapshotArchiveCannotBeRestoredWithoutTemplateFallback() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
E2bSandboxState state = stateForResumeWithNativeSnapshot("snap-123");
state.setSnapshot(
new FakeSnapshot(nativeArchive("snap-123"), true) {
Expand All @@ -175,7 +175,7 @@ public InputStream restore() throws Exception {

@Test
void startFailsWhenSnapshotRestorabilityCheckFailsWithoutTemplateFallback() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
E2bSandboxState state = stateForResumeWithNativeSnapshot("snap-123");
state.setSnapshot(
new FakeSnapshot(nativeArchive("snap-123"), true) {
Expand All @@ -201,7 +201,7 @@ public boolean isRestorable() throws Exception {

@Test
void startFailsWhenNativeSnapshotReferenceIsCorruptWithoutTemplateFallback() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
E2bSandboxState state = stateForResumeWithNativeSnapshot("snap-123");
byte[] corruptArchive =
(new String(E2bSnapshotRefs.MAGIC_PREFIX, StandardCharsets.UTF_8)
Expand All @@ -225,7 +225,7 @@ void startFailsWhenNativeSnapshotReferenceIsCorruptWithoutTemplateFallback() thr

@Test
void startFallsBackToTemplateWhenSnapshotIsConfirmedNotRestorable() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
server.enqueue(sandboxResponse("fresh-sandbox"));
server.enqueue(envdStartResponse());
E2bSandboxState state = stateForResumeWithNativeSnapshot("snap-123");
Expand Down Expand Up @@ -346,7 +346,7 @@ void startPropagatesConfigurationFailureWithoutRelabelingItAsSnapshotLoss() thro

@Test
void startRestoresSnapshotAfterConnectFailureWithoutReopeningSnapshotStore() throws Exception {
server.enqueue(new MockResponse().setResponseCode(500).setBody("connect failed"));
server.enqueue(new MockResponse().setResponseCode(404).setBody("sandbox expired"));
server.enqueue(sandboxResponse("restored-sandbox"));
server.enqueue(envdStartResponse());
E2bSandboxState state = stateForResumeWithNativeSnapshot("snap-123");
Expand Down
Loading
Loading