agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

fix(sandbox-e2b): E2bEnvdProcessClient drops the end event when exit_code is 0 - every successful command is reported as a failure

Open fenghc66 opened this issue 3 months ago • 5 comments

Summary

E2bEnvdProcessClient (agentscope-extensions-sandbox-e2b) uses proto3 field-presence APIs (getAllFields() / hasField()) to decide whether an end event exists and whether exit_code was set. exit_code is a proto3 singular scalar without explicit presence, so the value 0 is indistinguishable from "absent" through those APIs. The result inverts the meaning of success:

  • a command that exits with 0 (success) → the end event is dropped / the exit code is never read → the caller sees the initial sentinel Integer.MIN_VALUE → ExecException: Command exited with code -2147483648;
  • a command that exits with non-zero (failure) → everything works normally.

Every successful command is reported as a failure. Since sandbox/workspace bootstrap itself runs commands that exit 0, the E2B backend cannot even hand out a sandbox handle when the envd endpoint speaks JSON.

Affected versions

  • 2.0.1, 2.0.2, 2.0.2-subagent-bugfix — E2bEnvdProcessClient.class is byte-identical across these three releases on Maven Central.
  • Still present on main as of 2026-08-20 (checked at 643905e6).

Environment where it bites

Any e2b-compatible envd that serves JSON frames. Concretely reproduced against Alibaba Cloud FC's e2b-compatible service (*.e2b.fc.aliyuncs.com): FC's envd rejects the PROTO codec with HTTP 400 and only speaks JSON, so the JSON parsing path is mandatory there.

Server-side evidence that the endpoint is fine: the same request sent with curl returns three complete frames —

{"event":{"start":{...}}}
{"event":{"data":{"stdout":"aGkK"}}}
{"event":{"end":{"exitCode":0}}}

The end frame is present with exitCode: 0; it is the client that discards it.

Standalone reproduction (no network, unmodified Central artifact)

A minimal project with a single dependency on io.agentscope:agentscope-extensions-sandbox-e2b:2.0.1 feeds the exact envd JSON frames above into parseJsonStartResponse via reflection. Output:

== Part 1: the proto3 fact the bug rests on (pure protobuf, no agentscope logic) ==
EndEvent builder after setField(exit_code, 0) -> getAllFields().isEmpty() = true
EndEvent builder after setField(exit_code, 1) -> getAllFields().isEmpty() = false

== Part 2: agentscope 2.0.1 parseJsonStartResponse on real envd JSON frames ==
envd frame: {"event":{"end":{"exitCode":0}}}
  end event survives parsing : false   <== END EVENT DROPPED BY THE CLIENT
  exit code the caller sees  : -2147483648   <== ExecException: Command exited with code -2147483648
envd frame: {"event":{"end":{"exitCode":1}}}
  end event survives parsing : true
  exit code the caller sees  : 1

The exitCode:1 control case shows the parser is otherwise fine — the failure is specific to the success value 0.

Root cause — two spots, same mistake

1. JSON → DynamicMessage assembly, parseJsonStartResponse:

JsonNode exitCodeNode = endNode.path("exitCode");
if (exitCodeNode.canConvertToInt()) {
    endBuilder.setField(exitCodeField, exitCodeNode.intValue());
}
if (!endBuilder.getAllFields().isEmpty()) {           // <-- bug
    event.setField(processEventDesc.findFieldByName("end"), endBuilder.build());
}

exit_code is a proto3 singular int32 without explicit presence. After setField(exitCodeField, 0), endBuilder.getAllFields() is empty — that is documented proto3 behavior, not a protobuf bug. So the presence of the end event is judged from the wrong place, and the event is attached only when the exit code is non-zero.

2. Stream draining, drainStartStream:

if (pe.hasField(peEndF)) {
    DynamicMessage end = (DynamicMessage) pe.getField(peEndF);
    Descriptors.FieldDescriptor ec =
            end.getDescriptorForType().findFieldByName("exit_code");
    if (end.hasField(ec)) {                            // <-- bug
        Object v = end.getField(ec);
        exit = v instanceof Integer ? (Integer) v : ((Long) v).intValue();
    }
}

Same presence trap on the read side: for exit_code == 0, hasField() is false and exit keeps its Integer.MIN_VALUE initializer. Note this read-side guard is wrong even for the binary PROTO path — proto3 wire format omits default-valued singular scalars, so a server that legitimately encodes exit_code = 0 also trips it.

Suggested fix

parseJsonStartResponse — judge presence from the JSON, not from getAllFields():

JsonNode exitCodeNode = endNode.path("exitCode");
boolean hasExitCode = exitCodeNode.canConvertToInt();
if (hasExitCode) {
    endBuilder.setField(exitCodeField, exitCodeNode.intValue());
}
if (hasExitCode || !endBuilder.getAllFields().isEmpty()) {
    event.setField(processEventDesc.findFieldByName("end"), endBuilder.build());
}

drainStartStream — read unconditionally; the proto3 default for an absent field is 0, which is exactly the right value here:

Object v = end.getField(ec);
exit = v instanceof Integer ? (Integer) v : ((Long) v).intValue();

We have been running both changes as a local patch in production use against FC's e2b service; happy to turn this into a PR if the approach looks right to you.

Regression test suggestion

A unit test in the same package pins the behavior without any network:

@Test
void anExitCodeOfZeroSurvivesJsonParsing() throws Exception {
    E2bSandboxClientOptions options = new E2bSandboxClientOptions();
    options.setApiKey("test-only-not-used");
    E2bEnvdProcessClient client = new E2bEnvdProcessClient(options);

    byte[] frame = "{\"event\":{\"end\":{\"exitCode\":0}}}"
            .getBytes(StandardCharsets.UTF_8);
    DynamicMessage response = /* invoke parseJsonStartResponse(frame) */;

    Descriptors.FieldDescriptor eventField =
            response.getDescriptorForType().findFieldByName("event");
    assertThat(response.hasField(eventField)).isTrue();

    DynamicMessage event = (DynamicMessage) response.getField(eventField);
    Descriptors.FieldDescriptor endField =
            event.getDescriptorForType().findFieldByName("end");
    assertThat(event.hasField(endField)).isTrue();   // fails before the fix

    DynamicMessage end = (DynamicMessage) event.getField(endField);
    Object exitCode = end.getField(
            end.getDescriptorForType().findFieldByName("exit_code"));
    assertThat(((Number) exitCode).intValue()).isZero();
}

The negative control that documents the proto3 fact this bug rests on: build an EndEvent via DynamicMessage.newBuilder(endDesc), setField(exit_code, 0), and assert builder.getAllFields() is empty — while setField(exit_code, 1) makes it non-empty. That is why the getAllFields().isEmpty() heuristic can never work for this field.

fenghc66 avatar Aug 20 '26 14:08 fenghc66

Issue Evaluation

Category: bug | Status: Already fixed on main (verified at 3c1c29c01, 2026-09-24)

The proto3 presence reasoning in the report is correct, and it did describe the shipped behaviour of E2bCodec.JSON at the time this issue was filed (2026-08-20). The client-side handling has since been fixed on main:

  • E2bEnvdProcessClient.java:341-350 — the JSON decoder now checks the end node for presence (!endNode.isMissingNode() && !endNode.isNull()) and, whenever the parsed exitCode canConvertToInt(), sets the field and attaches the enclosing end message. An explicit exitCode: 0 therefore survives, instead of being dropped by getAllFields()/scalar-presence checks.
  • E2bEnvdProcessClient.java:203-209 — the shared (protobuf) path reads the exit code from the present end message with end.getField(ec) rather than testing scalar presence, so a proto3 default of 0 is read as 0.
  • E2bEnvdProcessClient.java:168,215-218 — exit starts as null; a stream that really ends without an exit code now raises IOException("envd process stream ended before receiving a process exit code") instead of leaking the Integer.MIN_VALUE sentinel as Command exited with code -2147483648.
  • E2bEnvdProcessClientTest.java:196-205 (jsonCodecPreservesZeroExitCode) — the exact case in this report, {"end":{"exitCode":0}}, is asserted to drain to exit code 0.

The fix landed in PR #2609 (merge 3e096a00d, 2026-08-21), one day after this issue was opened; it covers the same defect reported in #2601/#2602/#2603, and #2828 hardened the "stream ended without exit code" path afterwards.

Impact / action: no further code change needed on main. Anyone still hitting Command exited with code -2147483648 is running a build cut before 3e096a00d (2.0.1 / 2.0.2 per the report) and should upgrade to a release containing that merge. @fenghc66 could you confirm against a current main snapshot and, if you agree, close this as resolved by #2609?


Automated evaluation by github-manager-bot

oss-maintainer avatar Sep 25 '26 06:09 oss-maintainer

Independent check on current main — agreed, this is resolved by #2609 and looks closable.

Verified the citations directly rather than taking the evaluation on trust:

  • E2bEnvdProcessClient.java:168 — Integer exit = null;, so the Integer.MIN_VALUE sentinel is gone, and :215-217 now raises IOException("envd process stream ended before receiving a process exit code") for a stream that really ends without one, instead of leaking Command exited with code -2147483648.
  • :203-209 — the protobuf path reads the exit code with end.getField(ec) rather than testing scalar presence, so a proto3 default of 0 is read back as 0.
  • :341-350 — the JSON path tests the end node for presence and, when exitCodeNode.canConvertToInt(), both sets the field and attaches the enclosing end message, so {"end":{"exitCode":0}} survives.
  • E2bEnvdProcessClientTest.java:197 — jsonCodecPreservesZeroExitCode pins exactly this case.
  • 3e096a00 on main — fix(sandbox): preserve zero exit code in E2B JSON stream (#2609).

For what it's worth, the rest of this family is already closed: the duplicates #2601, #2602 and #2603 are all in CLOSED state, and they cover the same defect that the same PR fixed.

So there's no code change left here — anyone still seeing Command exited with code -2147483648 is on a build cut before 3e096a00 (the 2.0.1 / 2.0.2 line named in the report) and needs to upgrade. Closing as resolved by #2609 seems right.

wahllllll avatar Oct 03 '26 16:10 wahllllll

Hi, I'd like to work on this (I recently touched the same client for #2974). The proto3-presence analysis is precise: hasField/getAllFields cannot distinguish an unset singular exit_code from 0. Fix: stop relying on field presence for the end/exit_code decision — treat a received end event as terminal and read exit_code with a 0 default (proto3 scalar semantics), keeping the MIN_VALUE sentinel unreachable. Test: JSON-mode end event with exit_code 0 reports exit 0. PR coming shortly.

aiyili avatar Oct 22 '26 03:10 aiyili

Withdrawal — apologies for the noise: I claimed this before reading the full thread. wahllllll's independent check and the evaluation confirm it's already fixed on main by #2609 (the current E2bEnvdProcessClient reads exit_code via getField with the proto3-default comment, exactly as you both describe); the issue just needs closing. Nothing to do here.

aiyili avatar Oct 22 '26 03:10 aiyili

Closing as fixed by #3606 (merged): the end event is now read for exit code 0 from Connect-JSON, so successful commands are no longer reported as failures. The duplicate report #3607 was closed by the same PR. Reopen if it still reproduces.

juruoO-o avatar Nov 12 '26 11:11 juruoO-o