Skip to content

fix(e2b): harden envd process streaming response parsing [1/3] - #3341

Merged
jujn merged 6 commits into
agentscope-ai:mainfrom
chcodex:split/e2b-a-envd-parsing
Oct 11, 2026
Merged

jujn merged 6 commits into
agentscope-ai:mainfrom
chcodex:split/e2b-a-envd-parsing

Conversation

@chcodex

@chcodex chcodex commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PR 1/3 — merge this one first

Split from #2196. Merge order: #3341 → #3343 → #3344.

Self-contained: it only touches envd streaming-response parsing and can be reviewed and merged on its own. It has to land first because #3343/#3344 drive runShell(), which throws ExecException on any non-zero exit code — under the pre-fix parser a successful tar was reported as Integer.MIN_VALUE and threw regardless.

#3343 and #3344 are based on main (GitHub rejects a PR base that points at a branch in the fork), so they carry this commit in their history. Once this PR merges, their diffs shrink automatically to:

PR Remaining diff
#3343 2 files, +306 / -2
#3344 2 files, +304 / -33

Fixes #3338

Split from #2196 (standalone: based on current main, no dependency on fix/e2b-envd-client).

What

Harden E2bEnvdProcessClient.drainStartStream Connect streaming parsing:

  • Parse end-stream envelopes (flags 0x02) as EndStreamMessage JSON: throw SandboxRuntimeException(WORKSPACE_START_ERROR) on error, break cleanly otherwise.
  • error key presence alone signals failure (mirrors Python SDK ServerStreamParser); falls back to raw error JSON when code/message are absent.
  • Reject compressed frames (0x01) with IOException; skip reserved flag bits (0xFC).
  • Message-Length per spec: 4-byte unsigned big-endian (drop erroneous & 0x7FFFFFFF mask).
  • Read proto3 exit_code via getField() so exit 0 is no longer misreported; always retain end event even when sub-fields are empty.
  • Forward EndEvent.error (e.g. signal: killed, exit status N) to stderr.
  • Extract buildEnvdRequest to share header construction (no behavior change).

Tests

  • E2bEnvdProcessClientTest: 26/26 pass (9 existing + 17 new).
  • E2bEnvdProcessClientIntegrationTest (real E2B service, gated by E2B_API_KEY): end-stream flags 0x02 set / 0x01 unset; SIGKILL yields non-zero exit with signal: killed in stderr.
  • Cross-checked against official Python e2b SDK on live sandbox: exit 0 -> (0, None), exit 42 -> (42, 'exit status 42'), kill -9 -> (-1, 'signal: killed'), failed ls -> (2, 'exit status 2') — all consistent with Java behavior.

@codecov

codecov Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.23077% with 28 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/extensions/sandbox/e2b/E2bEnvdProcessClient.java 69.23% 18 Missing and 10 partials ⚠️

📢 Thoughts on this report? Let us know!

@oss-maintainer oss-maintainer left a comment

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.

Summary

Hardens the envd Start Connect stream decoder — end-stream envelopes, compressed/reserved flag handling, unsigned 4-byte Message-Length, proto3 exit_code presence, and EndEvent.error forwarding. The direction is right and the test additions are substantial (module tests pass locally). CLA is signed.

Leaving this as comments rather than an approval: four robustness gaps around flag validation ordering, truncated-stream acceptance, unbounded capture memory, and one credential leak in a test log. None block the fix itself, but the first two can turn a malformed / attacker-controlled stream into a silent "success".

Findings

  • [Warning] E2bEnvdProcessClient.java:186 — combined flag bits (0x06, 0x07) reach the end-stream branch and bypass the compressed-frame rejection.
  • [Warning] E2bEnvdProcessClient.java:181 — a truncated envelope after EndEvent is accepted and reported as success.
  • [Warning] E2bEnvdProcessClient.java:240 — the per-frame size cap does not bound total captured bytes (unbounded ByteArrayOutputStream).
  • [Warning] E2bEnvdProcessClientIntegrationTest.java:73 — envdAccessToken is logged; bearer-style credential leak.

Not covered

The live E2B integration path was not exercised (no credentials available); this review is based on the diff plus the unit/integration tests.


Automated review by github-manager-bot

// Connect protocol: flags bit 1 = end_stream — final envelope carries EndStreamMessage
// JSON
// https://connectrpc.com/docs/protocol/#streaming-rpcs
if ((flags & 0x02) != 0) {

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.

Flags are matched before compression/reserved-bit validation, so combined flag values such as 0x06 (end-stream + compressed) and 0x07 (end-stream + compressed + reserved) fall into the end-stream branch and terminate the stream — 0x07 also bypasses the 0x01 compressed-frame rejection. Please validate the compression and reserved bits first (or mask to the known bits) and add a test for combined flag values.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Resolved in the rebuilt branch: end_stream is now checked before the compressed bit, so 0x06/0x07 land in the end-stream branch intentionally (per Connect spec the final envelope always carries bit 1). Thanks for confirming in the re-review.

}
byte[] data = in.readNBytes(len);
if (data.length < len) {
break;

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.

A truncated header or payload after the EndEvent falls through here with a non-null exit code, so a stream whose end-stream envelope is missing/cut short is accepted as a successful run. Consider failing fast (throw SandboxRuntimeException(WORKSPACE_START_ERROR)) when an envelope is incomplete, so a truncated protocol stream cannot be reported as success.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping current behavior for SDK parity. Official connectrpc EnvelopeReader silently drops truncated trailing bytes (_envelope.py::_read_messages returns on short buffer without error), and e2b command_handle.wait() only raises when no EndEvent was ever received ("Command ended without an end event"). Post-EndEvent truncation is therefore accepted as success upstream too; failing fast here would diverge from the SDK.

// https://github.com/e2b-dev/e2b/blob/main/packages/python-sdk/e2b/sandbox_sync/commands/command_handle.py#L115
Descriptors.FieldDescriptor errF = endDesc.findFieldByName("error");
if (errF != null && end.hasField(errF)) {
stderr.write(

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.

The per-frame size limit does not bound total capture memory: stdout/stderr (and the end-event error) keep accumulating in ByteArrayOutputStream until the peer closes, and the truncation check only runs afterwards. A long-lived but individually-valid stream can still exhaust heap. Please cap total captured bytes (with an explicit truncate/discard marker) while draining.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same parity position: the official SDK accumulates all stdout/stderr chunks in memory (_stdout_chunks/_stderr_chunks, joined at the end; read_max_bytes caps single frames only). Java additionally truncates at OUTPUT_TRUNCATE_BYTES when materializing the result string. Streaming-time capping would be a behavior change beyond this split; happy to track it as a follow-up issue.

"sandboxId={} domain={} envdAccessToken={}",
state.getSandboxId(),
state.getSandboxDomain(),
state.getEnvdAccessToken());

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.

envdAccessToken is a bearer-style sandbox credential — logging it will leak it into CI output whenever this test runs with credentials enabled. Please log only its presence/length (or nothing at all).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 12afb30: both occurrences now log only envdAccessTokenPresent (boolean), never the credential.

Parse EndStreamResponse envelopes (flags 0x02), reject compressed
frames, skip reserved flag bits, read proto3 exit_code via getField
so exit 0 is no longer misreported, and forward EndEvent.error to
stderr. Treat bare error object as failure (Python SDK parity),
extract buildEnvdRequest to share header construction.
@chcodex
chcodex force-pushed the split/e2b-a-envd-parsing branch from 9c35827 to 064c77b Compare September 28, 2026 15:16
@chcodex chcodex changed the title fix(e2b): harden envd process streaming response parsing fix(e2b): harden envd process streaming response parsing [1/3] Sep 28, 2026
@chcodex chcodex changed the title fix(e2b): harden envd process streaming response parsing [1/3] fix(e2b): harden envd process streaming response parsing Sep 28, 2026
@chcodex chcodex changed the title fix(e2b): harden envd process streaming response parsing fix(e2b): harden envd process streaming response parsing [1/3] Sep 28, 2026

@oss-maintainer oss-maintainer left a comment

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.

Summary

Re-review of the rebuilt branch (064c77b5, stacked 1/3). The envelope parsing is in good shape: flag handling now checks end_stream before the compressed bit, so the earlier 0x06/0x07 bypass concern is resolved, and endianness, reserved-flag rejection, exit_code presence handling and stream closing all look correct. Three points still need attention — one of them a credential leak in the new integration test, so I am leaving this as a comment rather than an approval.

Findings

  • [Critical] E2bEnvdProcessClientIntegrationTest.java:74 — envdAccessToken logged at INFO; sandbox bearer credential ends up in test/CI logs.
  • [Warning] E2bEnvdProcessClient.java:181 — a truncated/absent EndStream envelope after EndEvent is still accepted as success.
  • [Warning] E2bEnvdProcessClient.java:132 — per-frame cap does not bound total captured bytes (unbounded stdout/stderr buffers).

Also worth a look while you are here: no test pins the truncated-trailer case or the reserved-flag rejection, both of which are exactly the behavior this PR is hardening.


Automated review by github-manager-bot

state.getSandboxId(),
state.getSandboxDomain(),
state.getEnvdAccessToken());

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.

Integration test logs state.getEnvdAccessToken() at INFO level, leaking the sandbox credential to test logs and CI output. Remove the token from the log statement or replace it with a redacted/masked value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 12afb30: replaced with envdAccessTokenPresent boolean at both log sites (captureRawConnectFrames and signalKillViaRunShell).

}
byte[] data = in.readNBytes(len);
if (data.length < len) {
break;

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.

A truncated or missing EndStream envelope after the process EndEvent is accepted as success because exit is already set and the final if (exit == null) check is skipped. After EndEvent, require a valid EndStream envelope (or treat EOF/truncated trailer as an IOException) so a severed connection cannot mask a stream-level error.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same as my reply on the first-round thread: official SDK accepts post-EndEvent truncation as success (envelope layer drops short trailing bytes silently; wait() raises only when _result is None). Current break-and-return-exit behavior matches; no change made.

@@ -126,19 +130,7 @@ private ShellCapture runShellCapture(
String host = envdHost(state);
String url = host + "/process.Process/Start";
byte[] envelope = encodeStartRequestEnvelope(shellCommand, cwd);

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.

stdout and stderr are unbounded ByteArrayOutputStream instances that accumulate every data frame. The per-frame 64 MB cap does not limit total captured bytes, so a long-running or chatty process can exhaust heap. Bound the total bytes written to each stream (e.g., with a counting/wrapping stream) and/or apply OUTPUT_TRUNCATE_BYTES during streaming, not only when converting to string.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same as first-round thread: parity with official SDK accumulation; Java additionally truncates at OUTPUT_TRUNCATE_BYTES on materialization. Propose follow-up issue if streaming-time capping is desired.

@jujn jujn self-assigned this Sep 29, 2026
jujn and others added 2 commits September 29, 2026 22:20
- parseEndStreamResponse: only a non-empty error object signals
  failure, mirroring connectrpc ConnectEnvelopeReader
  (if error: raise — empty object is falsy, i.e. success).
- Integration test: log only envdAccessToken presence, never the
  bearer credential itself.
@chcodex

chcodex commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

Re-review follow-up (12afb30): fixed the credential log (presence-only boolean at both sites) and corrected my earlier end-stream change — an empty error object is now treated as success, mirroring connectrpc handle_end_message (if error: raise, empty dict is falsy); added endStreamResponseWithEmptyErrorObjectBreaksCleanly to lock it. Truncation/memory threads answered with SDK-parity evidence; no code change there. Unit tests 26/26 + Spotless pass.

@oss-maintainer oss-maintainer left a comment

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.

Summary

Re-review of 12afb30c. The credential leak is fixed properly (presence-only boolean at both log sites) and I am satisfied with your SDK-parity answers on the truncation and buffer-cap threads — the connectrpc/e2b-python references you cite are accurate, so I am withdrawing both as non-issues. Two of my three prior warnings were also addressed with new tests (reservedFlagsFrameIsSkipped, compressedFrameThrowsIOException, jsonCodecRejects*), which is the right response.

One regression is left, and it comes from the end-stream change itself: removing EndStreamMessage.errorPresent while narrowing hasError() to code != null means the parser and the predicate now use different notions of "is there an error". A non-empty error object that carries no code — {"error":{"message":"boom"}}, {"error":"boom"}, or {"error":{"details":[...]}} — is parsed into a populated EndStreamMessage, then reported as not an error, and the stream ends as a success. That is a behaviour change relative to 064c77b5 (where any present error raised) and it also diverges from the if error: rule the new comment claims to mirror: in Python all three of those values are truthy.

The single-line version of the fix is code != null || message != null, but the inline comment explains why deriving presence from the node is the more durable shape — it makes the empty-object case fall out of one predicate instead of two coordinated ones.

  • [Warning] E2bEnvdProcessClient.java:296-306 — message-only / code-less error treated as success; existing tests cannot observe it because they never pair such a trailer with a prior EndEvent.
  • [Info] E2bEnvdProcessClient.java:279 — the two comment blocks above parseEndStreamResponse now state two different rules, neither of which is what the code does.

Not requesting changes: the affected payloads are the non-canonical error shapes, so the common {code, message} path is correct and CI is green on the checks that completed. But I would want the message-only case pinned by a test before merge, since it is exactly the silent-success class this PR was opened to eliminate.

Assessment is static reading only — no JDK 17 or Maven in this environment, so nothing was compiled or executed here. The behaviour table above is derived from reading parseEndStreamResponse/hasError(); the one-command repro is endStreamResponseWithEmptyErrorObjectBreaksCleanly with connectFrame(endEventJson(0, null)) prepended, via mvn -T1 -pl agentscope-extensions/agentscope-extensions-sandbox/agentscope-extensions-sandbox-e2b test -Dtest=E2bEnvdProcessClientTest.


Automated review by github-manager-bot

Comment on lines +296 to +306
String code = errorNode.path("code").asText(null);
String message = errorNode.path("message").asText(null);
if (code == null && message == null) {
return new EndStreamMessage(null, null);
}
return new EndStreamMessage(code, message);
}

private record EndStreamMessage(String code, String message) {
boolean hasError() {
return code != 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.

Dropping the errorPresent flag left parseEndStreamResponse and hasError() disagreeing, so a message-only end-stream error is now reported as success.

The guard at :298 only returns "no error" when both fields are null, so {"error":{"message":"sandbox VM died"}} falls through and builds EndStreamMessage(null, "sandbox VM died"). But hasError() here reads code only, so that fully-populated error object is reported as not an error. drainStartStream then takes the plain break at :197 as if the stream had ended cleanly — and if an EndEvent with exitCode: 0 arrived first, runShell returns 0 for a process the server explicitly failed.

trailer if error: (connectrpc) this parser result here
{"error":{"code":"internal","message":"x"}} raise error throws ✓
{"error":{}} falsy → no raise no error clean break ✓
{"error":{"message":"boom"}} raise error built hasError() false → exit code kept ✗
{"error":"boom"} raise both fields null clean break ✗
{"error":{"details":[…]}} raise both fields null clean break ✗

Rows 3-5 are all non-empty error values, which Python treats as truthy and raises on — the very rule the comment at :291-295 says this method mirrors. The boolean errorPresent field removed in 12afb30c was what made rows 3-5 correct before; extracting code alone re-opened the gap while narrowing the semantics to "has a code".

Decide "is this an error?" from the node, not from which fields happened to be extractable, then read the fields out of it:

boolean errorPresent = !(errorNode.isMissingNode() || errorNode.isNull())
        && !(errorNode.isContainerNode() && errorNode.isEmpty())
        && !(errorNode.isTextual() && errorNode.asText().isEmpty());
if (!errorPresent) {
    return new EndStreamMessage(null, null);
}
String code = errorNode.path("code").asText(null);
String message = errorNode.isObject() ? errorNode.path("message").asText(null) : errorNode.asText(null);
if (code == null && message == null) {
    message = errorNode.toString(); // non-empty error with nothing extractable: surface it verbatim
}
return new EndStreamMessage(code, message);

With that shape hasError() can go back to a real flag, or stay as code != null || message != null — the important part is that the "no error" decision and the "is there an error" decision come from the same predicate.

Rows 3 and 4 are currently untested, and both would pass today: the existing tests pair {"error":{…}} only with either no EndEvent (where :253 throws for an unrelated reason and masks the result) or with {}. A connectFrame(endEventJson(0, null)) + {"error":{"message":"boom"}} case asserting a SandboxRuntimeException fails against HEAD and passes against the fix above.

// if EnvelopeFlags.end_stream in flags:
// data = json.loads(data)
// if "error" in data: raise make_error(data["error"])
// return # no error → stop iteration

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] Two comment blocks in this method now state two different rules, and neither matches the code.

:274-281 still documents the Python SDK rule if "error" in data: raise — a key-presence test, which is precisely what 12afb30c moved away from. :291-295 directly below it documents the connectrpc rule if error: raise — a truthiness test. The implementation follows neither (it tests "is code non-null").

Since the whole point of this change is SDK parity, it is worth collapsing the two blocks into one that states the rule actually implemented, with the reference link. Divergent comments are what make the next person re-derive the semantics from scratch — and this method's semantics are subtle enough (0x02 checked before 0x01, proto3 default exit_code, corrupt data frame skipped vs corrupt trailer propagated) that the prose is load-bearing.

- parseEndStreamResponse: truthiness-based hasError matching
  connectrpc (empty object/string/0/false mean success; 1e999-style
  infinities raise via SandboxRuntimeException, never NumberFormatException).
- Skip null code/message parts in the failure message (Connect Error
  allows code-only or message-only).
- Fail closed on end events carrying neither exit code nor textual
  error (JSON); proto-wire empty end reads 0 (indistinguishable bits,
  same as official SDK).
- Separate EndEvent.error from preceding stderr with a newline.
- Narrow corrupt-frame catch to parseStartResponseFrame.
- Integration test: EnabledIfEnvironmentVariable gate, presence-only
  token log, opt-in diagnostics note.

@chcodex chcodex left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Follow-up on the re-review (d9152ac) — you were right on the regression, fixed plus the adjacent issues:

Your three counter-examples now throw. hasError judges the error node's Python truthiness instead of key-presence or code-presence: {"message":"boom"}, "boom", {"details":[...]} all raise; {}, "", 0, false break cleanly. New tests: endStreamResponseWithMessageOnlyErrorThrows, endStreamResponseWithStringErrorThrows, endStreamResponseWithFalsyErrorBreaksCleanly.

1e999 crash fixed. Number branch uses asDouble() == 0.0 (infinities stay infinite/truthy); locked by endStreamResponseWithInfiniteErrorThrows, which asserts SandboxRuntimeException so any future escape as NumberFormatException fails loudly.

Null-part messages fixed. {"code":"unavailable"} now renders Process start failed: unavailable (no : null); message-only symmetric.

Empty-end fail-closed (JSON) with one correction to my plan. {"end":{}} and error-less codeless ends no longer fabricate exit 0 (emptyEndEventThrows); endEventErrorWrittenToStderr rewritten to the real signal-kill shape (-1, signal: killed). But the proto-side guard I planned is not in the final diff: exit_code=0 is bit-identical to a field-less EndEvent on the wire (verified: setField(sint32, 0) \u2192 hasField()=false, getAllFields()={}), so no implementation — including the official SDK's direct end.exit_code read — can distinguish them. Proto empty-end therefore reads 0 (emptyEndEventReadsZeroProto locks it, with the wire-indistinguishability rationale in comments). JSON stays fail-closed since text form is distinguishable.

Also in: stderr newline separator (endEventErrorSeparatedFromStderr), try narrowed to parseStartResponseFrame, MSB regression test (highBitFrameLengthThrowsIOException), @EnabledIfEnvironmentVariable gate, diagnostics note on captureRawConnectFrames.

Deliberately unchanged: post-EndEvent truncation acceptance and unbounded accumulation (SDK-parity evidence in prior threads); docs (sandbox.md/release-notes carry no user-visible API change from this fix).

Unit tests 33/33 + Spotless pass.

@chcodex

chcodex commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

@oss-maintainer please re-review at your convenience. Head is now d9152ac: the end-stream regression is fixed (truthiness-based hasError with new tests), plus the adjacent fixes from your thread (1e999 crash, null-part messages, empty-end fail-closed on JSON, stderr separator, narrowed catch, MSB test, env-var gate). Details in my review reply above. Unit tests 33/33 + Spotless pass.

@oss-maintainer oss-maintainer left a comment

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.

Summary

Re-reviewed d9152ac2. The end-stream error semantics are now correct — isFalsy + errorPresent judge the error node the way connectrpc does, description() can no longer render a literal null, the corrupt-frame try is narrowed to parseStartResponseFrame, and the JSON path no longer fabricates exit 0 for an end event carrying neither code nor error. All of it is locked by tests (endStreamResponseWith*, emptyEndEvent*, highBitFrameLengthThrowsIOException), and the proto/JSON asymmetry is now explained in comments instead of being accidental. CI green on ubuntu + windows, CLA signed, mergeable.

Two items left, both local: the JSON exitCode lookup is camelCase-only and the new fail-closed guard turns that assumption into a hard error, and corrupt data frames are now skipped with no trace at all.

Verdict: COMMENT — small fixes; happy to re-review the next push.

Findings

  • [Warning] E2bEnvdProcessClient.java:487 — "retain end only when a part is present" makes the camelCase-only lookup observable: a peer emitting proto field names (exit_code, which protojson accepts on the wire) used to yield a silent exit 0, and now yields IOException("... ended before receiving a process exit code") for a command that really exited 42.
  • [Warning] E2bEnvdProcessClient.java:213 — the narrowed catch (IOException ignored) has the right shape but logs nothing, so dropped stdout/stderr is invisible: "output empty" and "output lost" look identical to the caller.

Items from my previous thread

Accepted, not re-filing:

  • Post-EndEvent truncation acceptance and unbounded stdout/stderr accumulation — your SDK-parity rationale is reasonable and both are pre-existing, not introduced here. If you ever want the cheap version of the memory bound: a counting wrapper that flips the existing OUTPUT_TRUNCATE_BYTES flag while draining rather than only at toString gives the same visible outcome without touching the parse loop.
  • Flags matched before compression/reserved-bit validation (:186 still precedes :202/:207) — still open, but exposure is low since a 0x06/0x07 envelope fails JSON parsing and surfaces as IOException, so I have not anchored it again. It is the one item from the previous thread that was neither fixed nor explicitly declined in your follow-up: a one-line reorder, or a comment saying you want to keep the current precedence, closes it.

Docs unchanged: agreed, nothing user-visible in the API from this fix.


Automated review by github-manager-bot

Descriptors.Descriptor endDesc = processEventDesc.findNestedTypeByName("EndEvent");
DynamicMessage.Builder endBuilder = DynamicMessage.newBuilder(endDesc);
Descriptors.FieldDescriptor exitCodeField = endDesc.findFieldByName("exit_code");
JsonNode exitCodeNode = endNode.path("exitCode");

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] The new "retain end only when a part is present" guard turns the camelCase-only key lookup into a hard failure for a snake_case peer.

endNode.path("exitCode") matches lowerCamelCase only. proto3 JSON accepts both exitCode and the proto name exit_code on the wire (Go's protojson emits the latter under UseProtoNames: true), and every other key read here — event, data, end, error, stdout, stderr — is spelled identically in both forms, so exitCode is the only one that can drift.

Before this commit a snake_case response silently produced exit = 0 (wrong, but a success); with the guard at :505 the same response now raises IOException("envd process stream ended before receiving a process exit code"), so a real exit 42 is reported as a protocol failure rather than as a wrong exit code. That is the better of the two wrong answers, but it is still a user-visible sandbox error, and it is cheap to close:

JsonNode exitCodeNode = endNode.path("exitCode");
if (exitCodeNode.isMissingNode()) {
    exitCodeNode = endNode.path("exit_code");
}

plus a jsonStartResponseAcceptsProtoFieldNameExitCode test next to exitCodeNonZero, so the accepted spellings are pinned rather than assumed.

appendDataStream(de, "stdout", stdout);
appendDataStream(de, "stderr", stderr);
sr = parseStartResponseFrame(data);
} catch (IOException ignored) {

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] Corrupt data frames are skipped with no trace, so "the process produced no output" and "we dropped its output" are now indistinguishable.

Narrowing the try to parseStartResponseFrame is the right call — the end-stream envelope now propagates instead of being swallowed. But the skipped frame is not recorded at all: ignored discards whatever InvalidProtocolBufferException said (bad wire type, length mismatch, invalid UTF-8 in a string field) and the loop continues.

The consequence is directional: when the stream later ends cleanly with an exit code, the caller receives truncated stdout/stderr plus a success exit code and zero signal that bytes were lost. That is the shape of bug that cost a week in the exit_code thread, and it is one line to make observable — it stays off the hot path because it only fires on a frame that already failed to decode:

} catch (IOException e) {
    log.warn(
            "drainStartStream: skipping undecodable connect frame ({} bytes, flags={})",
            len,
            flags,
            e);
    continue;
}

If WARN is too loud for a peer-side corruption, a framesSkipped counter reported once after the drain works too — that is also the natural hook for the OUTPUT_TRUNCATE_BYTES partial-output signal you already raise at :103, so a caller can treat the capture as partial instead of complete.

- Check compressed flag before end-stream so combined envelopes
  (0x03/0x07) are rejected as compressed instead of feeding bytes
  to the EndStreamMessage JSON parser; log reserved-bit skips.
- Accept both exitCode (jsonName) and exit_code (proto field name)
  in JSON end events per protojson wire acceptance.
- Log skipped undecodable frames (flags/len); drop the misleading
  exit=null from the end-stream success log.

@chcodex chcodex left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Follow-up on the fourth round (a68b373) — both warnings fixed, plus an independent Explore review pass (clean):

CamelCase-only lookup (487). Fixed as suggested: exitCode with fallback to exit_code (jsonName preferred; single-word fields need no fallback — noted in comments). Locked by exitCodeSnakeCaseFieldName ({"end":{"exit_code":42}} \u2192 exit 42).

Silent frame skips (213). log.debug with flags+len on undecodable frames; reserved-bit skips also logged. Dropped the misleading exit=null from the end-stream success log.

Flags precedence (prior thread). Took the reorder option: compressed bit is now checked before end-stream, so 0x03/0x07 are rejected as compressed (IOException, uniform with plain compressed frames) instead of reaching the JSON parser. 0x06 still enters the end-stream branch — reserved bits are ignored per the Connect spec, same as the Python SDK's if end_stream in flags precedence. Locked by compressedEndStreamFrameThrowsIOException / compressedReservedEndStreamFrameThrowsIOException.

Unit tests 36/36 + Spotless pass.

@chcodex

chcodex commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

@oss-maintainer please re-review at your convenience. Head is now a68b373: both fourth-round warnings fixed (exitCode/exit_code dual lookup with test; debug logs on skipped frames; misleading exit=null dropped) and flags precedence resolved via reorder (0x03/0x07 rejected as compressed, 0x06 stays end-stream per spec) with new tests. Details in my review reply above. Unit tests 36/36 + Spotless pass.

@oss-maintainer oss-maintainer left a comment

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.

Summary

Fifth round on a68b3730 — this push closes everything I had left open, and closes it with tests rather than with prose:

  • camelCase-only exitCode lookup (:500) now falls back to the proto field name exit_code, which is exactly what protojson accepts on the wire. Because exitCodeNode is reassigned before the presence guard at :521, the guard and the field write stay consistent — the failure mode I flagged last round (a command that really exited 42 surfacing as IOException("... ended before receiving a process exit code")) is gone, pinned by exitCodeSnakeCaseFieldName.
  • Silently dropped corrupt frames (:224) now log flags and len at debug, and the reserved-flag continue at :210 logs too. "The process produced no output" and "we dropped its output" are distinguishable in a debug-enabled log, which is what I asked for.
  • Flag precedence (:183-189): the compressed check moved ahead of end-stream handling, so 0x03/0x07 envelopes reject as compressed rather than being handed to the JSON parser. Two new tests pin both cases, and dropping exit={} from the endStream ok debug line at :204 is correct — that value belongs to the last EndEvent, not to the trailer.

Verified on the current head: build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync and codecov patch all passing; license/cla success; mergeable CLEAN. CI green and CLA signed.

I left two Info notes, neither of which I want to hold this on: one records the remaining 0x06 (end-stream + reserved bit) precedence trade-off so the intent is on file, one confirms the stdout/stderr siblings deliberately need no field-name fallback. The parser is now consistent between the protobuf and JSON paths and the proto3 presence asymmetry is documented where a reader will hit it.

Verdict: APPROVED. Merging stays with the maintainers — per the PR description the stack order is #3341 → #3343 → #3344, and #3343/#3344 diffs shrink once this lands.


Automated review by github-manager-bot

// Connect protocol: flags bit 1 = end_stream — final envelope carries EndStreamMessage
// JSON
// https://connectrpc.com/docs/protocol/#streaming-rpcs
if ((flags & 0x02) != 0) {

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 — non-blocking] Hoisting the compressed check above this branch is the right call: a combined envelope such as 0x07 now fails closed with IOException("Compressed connect frames not supported") instead of feeding compressed bytes to the EndStreamMessage parser, and both new tests pin it.

One asymmetry left, and it is genuinely theoretical: 0x06 (end-stream + reserved bit 0x04) still reaches parseEndStreamResponse here, before the reserved-bit check at :209. If that payload happened to parse as JSON with a falsy error, the loop breaks on :205 treating an envelope whose semantics we cannot verify as a clean end-of-stream. Real envd never sets reserved bits on the trailer, and the 0x02-before-0xFC ordering is what keeps compressed rejection working, so I am not asking for a change — recording the trade-off so a future reader of :183-186 knows the precedence was deliberate. If you want it airtight in one line, move the (flags & 0xFC) rejection ahead of the 0x02 test and keep (flags & 0x01) first; the compressedEndStreamFrame* tests stay green either way.

// original proto field name ("exit_code") on the wire: prefer jsonName,
// fall back to the original. (Single-word fields like error/event/end
// are identical in both forms and need no fallback.)
JsonNode exitCodeNode = endNode.path("exitCode");

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] Confirmed fix for the camelCase-only lookup — exitCode → exit_code matches both forms protojson accepts on the wire, and because exitCodeNode is reassigned before the guard at :521, the "retain end only when a part is present" check and the field write can no longer disagree. exitCodeSnakeCaseFieldName covers it.

Nothing to change here. FYI for the next person in this file: the sibling stdout/stderr lookups at :478-479 do not need the same treatment — those are single-word names, so jsonName and the proto field name are identical — which is why the fallback is only needed on exit_code.

@jujn
jujn merged commit 897c486 into agentscope-ai:main Oct 11, 2026
6 checks passed
jujn added a commit that referenced this pull request Oct 11, 2026
Closes #3339. Split from #2196.

Stacked on #3341 (A: envd process streaming parsing fix). Own change is
the top commit only; diff shrinks to 2 files once #3341 merges.

Scope: add E2bEnvdProcessClient.uploadFile (multipart POST) and
downloadFile (GET) against /files, routed via envdHost(); keep
E2b-Sandbox-Id/Port/X-Access-Token/Authorization headers. Plus unit
tests.

---------

Co-authored-by: jujn <[email protected]>
chickenlj pushed a commit that referenced this pull request Nov 13, 2026
Backport the verified frame, trailer and process-exit handling fix while retaining the 2.0.x transport and sandbox contracts.

(cherry picked from commit 897c486)
Constraint: No AgentScope Service or SDK migration
Confidence: high
Scope-risk: narrow
Not-tested: Live provider integration and Java 17 runtime
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(e2b): envd process streaming response parsing misreports exit code 0

3 participants