Skip to content

[Bug]: DockerSandbox container name is deterministic while liveness is keyed by containerId — a state/daemon divergence wedges a sandbox session permanently (docker run exit=125 on every turn) #3644

Open

Description

@BeginnerCong

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:

  1. docker run is executed as a child process and the new container id is read from its stdout after the process exits.
  2. If waitFor(CONTAINER_START_TIMEOUT_SECONDS) times out, the code calls process.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 (or null) while the name is already taken.
  3. The run command carries no --rm (docker rm --force appears only in shutdown() and in a docker exec … rm -rf for the workspace path), so the orphaned container remains on the daemon holding agentscope-sandbox-<sessionId>.
  4. 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.
  1. shutdown() cannot clean it up either: it only removes the container identified by containerId, 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 inspect answers "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: SandboxErrorCode offers only the coarse WORKSPACE_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 from WorkspaceSpec"), 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

  1. 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>.

  2. 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
  3. 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 ….

  4. 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

  1. added
    bug
    on Oct 18, 2026
  2. ZhaoYJ9 commented on Oct 19, 2026

    @ZhaoYJ9

    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:

    • Reproduce the failure when the stored containerId becomes stale while the expected container name is still occupied.
    • Add a safe reconciliation mechanism to detect and recover the existing container before attempting to create a new one.
    • Ensure the recovery logic preserves existing sandbox state and does not interfere with unrelated containers.
    • Add regression tests covering stale container IDs, stopped containers, and normal container creation.
      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.
  3. wahllllll commented on Oct 31, 2026

    @wahllllll
    Contributor

    Reproduced from the source and fixed in #3890.

    doEnsureContainerRunning (DockerSandbox.java:497) really does decide usability from the persisted containerId alone, and createAndStartContainer derives 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 answers docker run ... --name agentscope-sandbox-<session> with

    docker run failed (exit=125): Conflict. The container name "/agentscope-sandbox-<session>"
    is already in use by container "live-id".
    

    and 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 run succeeding 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:

    • inspectContainerState collapsed "the daemon reports no such object" and "the probe could not answer" into one UNKNOWN. A failed inspect was 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.
    • To test the lifecycle without a live daemon, every CLI call now goes through one seam (runDockerCli, returning the exit code and both streams) instead of inspect and container creation each building a ProcessBuilder. That is the first commit; behaviour there is unchanged.

    DockerSandboxContainerReconcileTest drives 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 the exit=125 above and the fourth creates a duplicate container under the claimed name.

    Regression: DockerSandbox* 30 tests green (the 9 daemon-backed integration tests still skip), full agentscope-harness suite 1587 tests green.

    shutdown() is untouched — docker rm on an already-removed container is already tolerated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions