Repository navigation
Description
AgentScope-Java is an open-source project. To involve a broader community, we recommend asking your questions in English.
Version: v2.0.4 — agentscope-harness/.../agent/sandbox/impl/docker/DockerSandbox.java
Describe the bug
DockerSandbox derives the container name deterministically from the sandbox session id, but decides whether that container is usable only by the persisted containerId. When the two stop agreeing, the code concludes "container missing" and issues docker run with a name the daemon still has claimed. Nothing ever corrects the state, so every later turn repeats the same decision and the sandbox session can never start again.
doEnsureContainerRunning() (DockerSandbox.java:489-517):
/**
* Ensures the Docker container is running.
*
* <p>Priority:
* <ol>
* <li>If container exists and is running — reuse it.</li>
* <li>If container exists and is stopped — restart it.</li>
* <li>If container is missing or unknown — create a new container, reset
* {@code workspaceRootReady} to force full workspace reinitialisation.</li>
* </ol>
*/
private void doEnsureContainerRunning() throws Exception {
String containerId = dockerState.getContainerId();
if (containerId != null && !containerId.isBlank()) {
ContainerState state = inspectContainerState(containerId);
if (state == ContainerState.RUNNING) {
return;
} else if (state == ContainerState.STOPPED) {
runDockerCliBlocking(CONTAINER_START_TIMEOUT_SECONDS, "docker", "start", containerId);
return;
}
// Container not found — fall through to create a new one
log.warn("[sandbox-docker] Container {} not found, creating a new one", containerId);
dockerState.setWorkspaceRootReady(false);
}
createAndStartContainer();
}createAndStartContainer() (DockerSandbox.java:519-567) — the name comes from the persisted sandbox session id, which is stable for the whole session:
String containerName = "agentscope-sandbox-" + dockerState.getSessionId();
dockerState.setContainerName(containerName);
List<String> cmd = buildDockerRunCommand(containerName);
...
boolean exited = process.waitFor(CONTAINER_START_TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (!exited) {
process.destroyForcibly();
drainer.shutdownNow();
throw new SandboxException.SandboxRuntimeException(
SandboxErrorCode.WORKSPACE_START_ERROR,
"docker run timed out for image: " + dockerState.getImage());
}
...
if (exitCode != 0) {
throw new SandboxException.SandboxRuntimeException(
SandboxErrorCode.WORKSPACE_START_ERROR,
"docker run failed (exit=" + exitCode + "): " + stderr);
}The assumption behind branch 3 of the javadoc — "container missing" ⇒ "the name is free" — does not hold. Container names are scoped to the whole daemon, and no code path reconciles them: within this file containerName is assigned from the session id (520-521), handed to the run command (523 → cmd.add(containerName) at 591), and otherwise only appears as a log argument (582). Every liveness probe addresses a container id instead (e.g. line 671: docker inspect -f {{.State.Running}} containerId). There is no docker ps, no --filter name=…, and no by-name inspect.
How the state and the daemon diverge
The framework itself can produce the divergence:
docker runis executed as a child process and the new container id is read from its stdout after the process exits.- If
waitFor(CONTAINER_START_TIMEOUT_SECONDS)times out, the code callsprocess.destroyForcibly()and throws — that kills the CLI, not the container the daemon may already have created.dockerState.setContainerId(...)is never reached, so the state keeps the previous id (ornull) while the name is already taken. - The run command carries no
--rm(docker rm --forceappears only inshutdown()and in adocker exec … rm -rffor the workspace path), so the orphaned container remains on the daemon holdingagentscope-sandbox-<sessionId>. - The next turn resolves
inspectContainerState(oldContainerId)⇒ "not found" ⇒ falls through ⇒docker run --name agentscope-sandbox-<same sessionId>⇒ the daemon rejects the name:
docker: Error response from daemon: Conflict. The container name
"/agentscope-sandbox-f1f4c568-dd60-4b56-b952-059001a3c6d7" is already in use by container "a40415e5…".
You have to remove (or rename) that container to be able to reuse that name.
shutdown()cannot clean it up either: it only removes the container identified bycontainerId, which is precisely the value the state does not have.
Any other divergence between the persisted containerId and the container occupying the name reaches the same dead loop. A freshly created sandbox cannot hit this — DockerSandboxClient.create() assigns a random UUID session id, so the conflict is only ever reachable through the resume path (SandboxManager, which loads persisted state and calls client.resume(state)).
Impact
- Failure is immediate and permanent for the affected session:
docker inspectanswers "not found" and the daemon rejects the name at once, so each turn fails in well under a second rather than ever starting a sandbox. - Retrying, waiting, or re-sending the message cannot recover; the only escapes are deleting the occupying container out-of-band or discarding the persisted sandbox state (which also discards the session's workspace readiness).
- The condition is indistinguishable from any other start-up failure to a caller:
SandboxErrorCodeoffers only the coarseWORKSPACE_START_ERROR, so a name conflict can currently only be detected by matching the daemon's message text. - The documented recovery model makes this worse rather than better: with the default
NoopSnapshotSpec, the "container gone" branch is supposed to end in a cold start ("No snapshot → full init fromWorkspaceSpec"), so this is the framework's own designed happy path failing, not an exotic configuration. Nothing in the sandbox documentation tells the embedder to pre-clean names or to avoid the deterministic naming.
To Reproduce
-
Start a sandbox-backed session and let it create its container once. The name is logged:
[sandbox-docker] Creating container: image=…, name=agentscope-sandbox-<sessionId>. -
Make the daemon hold that name with a different container, simulating the orphan left by step 2 of the divergence above:
docker run -d --name agentscope-sandbox-<sessionId> --entrypoint /bin/sleep <sandbox-image> 1800
-
Send another turn in the same session. It fails with
docker run failed (exit=125): … Conflict. The container name "/agentscope-sandbox-<sessionId>" is already in use …. -
Repeat step 3: it fails identically every time, because the state is never reconciled.
Unit-level expectation of the current behaviour: resuming a DockerSandboxState whose containerId points at a non-existent container while a different container owns agentscope-sandbox-<sessionId> throws SandboxRuntimeException(WORKSPACE_START_ERROR) — and keeps throwing it on every subsequent turn.
Activity
ZhaoYJ9 commentedon Oct 19, 2026
Hi maintainers, I'd like to work on this issue.
I'll investigate the DockerSandbox container lifecycle and implement a focused fix for the inconsistency between the persisted container ID and the actual Docker container state.
My plan is to:
I'll keep the changes scoped to Docker sandbox lifecycle recovery and submit a PR once the fix is validated.
Please let me know if there are any concerns with this approach.
wahllllll commentedon Oct 31, 2026
Reproduced from the source and fixed in #3890.
doEnsureContainerRunning(DockerSandbox.java:497) really does decide usability from the persistedcontainerIdalone, andcreateAndStartContainerderives the name from the session id, so your reading of the failure mode holds. I could reproduce the wedge downstream of the branch you pointed at: the daemon answersdocker run ... --name agentscope-sandbox-<session>withand since nothing records a new id, the same decision repeats on every turn.
One part of the mechanism I would sharpen: the way the divergence appears in practice is
docker runsucceeding while persisting its returned id fails. The container is then on the daemon under the deterministic name, and the state file has either nothing or an id that is gone. That match is what makes the wedge self-sustaining.Two things beyond the by-name reconciliation:
inspectContainerStatecollapsed "the daemon reports no such object" and "the probe could not answer" into oneUNKNOWN. A failedinspectwas therefore treated as evidence that the container was gone. The fix keeps the two apart: a stale id is cleared only when the daemon explicitly says the object does not exist; on a transport failure the id is kept, because the next command will surface the real error rather than the sandbox racing to build a second container.runDockerCli, returning the exit code and both streams) instead ofinspectand container creation each building aProcessBuilder. That is the first commit; behaviour there is unchanged.DockerSandboxContainerReconcileTestdrives a fake daemon that refuses a claimed name like the CLI does: stale id + name running (adopt), stale id + name stopped (start), stale id + free name (create), probe cannot answer (keep the id). Against the previous code the first three fail with theexit=125above and the fourth creates a duplicate container under the claimed name.Regression:
DockerSandbox*30 tests green (the 9 daemon-backed integration tests still skip), fullagentscope-harnesssuite 1587 tests green.shutdown()is untouched —docker rmon an already-removed container is already tolerated.