Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(claude-code): decode the stdout stream across chunk boundaries

Nguyen Thanh Dat61edbb4556b2
diff --git a/src/openhuman/inference/provider/claude_code/stream_parser.rs b/src/openhuman/inference/provider/claude_code/stream_parser.rs
index 1a2a71f91e..69e6ffc96a 100644
--- a/src/openhuman/inference/provider/claude_code/stream_parser.rs
+++ b/src/openhuman/inference/provider/claude_code/stream_parser.rs
@@ -50,10 +50,59 @@ pub enum ClaudeCodeEvent {
#[derive(Debug, Default)]
pub struct StreamJsonParser {
buffer: String,
+ /// Bytes of an incomplete UTF-8 sequence carried over from the previous chunk.
+ ///
+ /// `feed_bytes` is handed arbitrary read boundaries, so a multi-byte character
+ /// can straddle two chunks. Decoding each chunk on its own replaced both halves
+ /// with U+FFFD, and the JSON still parsed -- the replacement character is legal
+ /// inside a string -- so the corruption reached the transcript silently.
+ pending: Vec<u8>,
/// First-seen `schema_version` from a `system` event, if any.
pub schema_version: Option<String>,
}
+/// Decode `bytes` as UTF-8, returning the text and any incomplete trailing
+/// sequence to carry into the next chunk.
+///
+/// Invalid bytes are replaced, as `from_utf8_lossy` would — the stream must not
+/// stall on input that will never become valid. The difference is that only the
+/// invalid *sequence* is consumed, and decoding then continues, so an incomplete
+/// character at the very end is still carried.
+///
+/// Handing the whole remainder to `from_utf8_lossy` after the first bad byte
+/// looks equivalent and is not: it replaces a trailing partial character before
+/// its other half has arrived, which is the corruption this parser carries
+/// `pending` to avoid. One stray byte earlier in the chunk was enough to bring
+/// it back.
+fn decode_carrying_tail(bytes: &[u8]) -> (String, Vec<u8>) {
+ let mut decoded = String::new();
+ let mut rest = bytes;
+
+ loop {
+ match std::str::from_utf8(rest) {
+ Ok(text) => {
+ decoded.push_str(text);
+ return (decoded, Vec::new());
+ }
+ Err(err) => {
+ let valid = err.valid_up_to();
+ // `valid_up_to` guarantees this prefix is valid UTF-8.
+ decoded.push_str(&String::from_utf8_lossy(&rest[..valid]));
+ match err.error_len() {
+ // An incomplete tail: hold it for the next chunk.
+ None => return (decoded, rest[valid..].to_vec()),
+ // One replacement per invalid sequence, matching lossy
+ // semantics, then carry on with what follows it.
+ Some(len) => {
+ decoded.push(char::REPLACEMENT_CHARACTER);
+ rest = &rest[valid + len..];
+ }
+ }
+ }
+ }
+ }
+}
+
impl StreamJsonParser {
pub fn new() -> Self {
Self::default()
@@ -61,8 +110,21 @@ impl StreamJsonParser {
/// Append a UTF-8 byte chunk and return any events whose terminating
/// newline arrived in this chunk.
+ ///
+ /// See [`decode_carrying_tail`] for the decode contract.
pub fn feed_bytes(&mut self, chunk: &[u8]) -> Vec<ClaudeCodeEvent> {
- self.buffer.push_str(&String::from_utf8_lossy(chunk));
+ // Decode only complete sequences and carry the trailing partial one into the
+ // next chunk. `valid_up_to()` is the boundary; anything after it is either an
+ // incomplete tail (keep it) or genuinely invalid input (replace it, as before).
+ let bytes: &[u8] = if self.pending.is_empty() {
+ chunk
+ } else {
+ self.pending.extend_from_slice(chunk);
+ &self.pending[..]
+ };
+ let (decoded, carry) = decode_carrying_tail(bytes);
+ self.pending = carry;
+ self.buffer.push_str(&decoded);
self.flush()
}
@@ -74,6 +136,15 @@ impl StreamJsonParser {
/// Drain any remaining buffered content. Call on EOF.
pub fn end(&mut self) -> Vec<ClaudeCodeEvent> {
+ // No further chunk is coming, so a held incomplete sequence can never be
+ // completed. Release it lossily rather than dropping it: that is what the
+ // per-chunk decode produced before the carry-over existed, and silently
+ // discarding trailing bytes would be a different kind of data loss than the
+ // one this parser is fixing.
+ if !self.pending.is_empty() {
+ let tail = std::mem::take(&mut self.pending);
+ self.buffer.push_str(&String::from_utf8_lossy(&tail));
+ }
if !self.buffer.is_empty() && !self.buffer.ends_with('\n') {
self.buffer.push('\n');
}
diff --git a/src/openhuman/inference/provider/claude_code/stream_parser_tests.rs b/src/openhuman/inference/provider/claude_code/stream_parser_tests.rs
index dd70f99cab..92012799e1 100644
--- a/src/openhuman/inference/provider/claude_code/stream_parser_tests.rs
+++ b/src/openhuman/inference/provider/claude_code/stream_parser_tests.rs
@@ -47,3 +47,171 @@ fn bad_json_becomes_parse_error() {
let events = p.feed("not json\n");
assert!(matches!(events[0], ClaudeCodeEvent::ParseError { .. }));
}
+
+/// A stream that ends mid-character must not swallow the partial bytes.
+/// Before the carry-over existed, `from_utf8_lossy` turned them into U+FFFD
+/// immediately; holding them means `end()` has to release them, or the last
+/// line of a truncated stream disappears entirely.
+#[test]
+fn end_flushes_an_incomplete_trailing_sequence() {
+ let line = serde_json::json!({
+ "type": "system",
+ "session_id": "x",
+ "schema_version": "2.0"
+ })
+ .to_string();
+ let mut bytes = line.into_bytes();
+ // A lone lead byte: a genuine incomplete tail, and no newline follows.
+ bytes.push(0xE4);
+
+ let mut p = StreamJsonParser::new();
+ assert!(
+ p.feed_bytes(&bytes).is_empty(),
+ "no newline yet, nothing emitted"
+ );
+ let events = p.end();
+ assert_eq!(
+ events.len(),
+ 1,
+ "the buffered line must still be emitted at EOF"
+ );
+ // The held byte is released as a replacement character rather than vanishing,
+ // which is what the per-chunk decode produced before the carry-over existed.
+ //
+ // Asserted on the field that carries it, not on the Debug rendering: a
+ // `contains` over `{:?}` passes if U+FFFD turns up anywhere in any field, so it
+ // would keep passing if the byte were released into the wrong place. The lone
+ // 0xE4 lands after the closing brace, which is why this is a `ParseError` and
+ // not a `System` event -- the released byte makes the line invalid JSON.
+ match &events[0] {
+ ClaudeCodeEvent::ParseError { line, .. } => assert!(
+ line.ends_with(char::REPLACEMENT_CHARACTER),
+ "the released byte should be the last character of the line, got {line:?}"
+ ),
+ other => panic!("expected the unparsable line to be reported, got {other:?}"),
+ }
+}
+
+/// An invalid byte earlier in the chunk must not cost the incomplete
+/// character at the end of it.
+///
+/// Handing everything after the first bad byte to `from_utf8_lossy` replaces
+/// a trailing partial sequence before its other half arrives — the exact
+/// corruption `pending` exists to prevent, reachable again through one stray
+/// byte anywhere earlier in the same read.
+#[test]
+fn an_invalid_byte_does_not_consume_a_split_character_after_it() {
+ let mut parser = StreamJsonParser::new();
+
+ // An ASCII marker holds the spot while the fixture is built as valid
+ // JSON, and is overwritten with a real invalid byte afterwards. (A NUL
+ // would not survive: serde escapes it to `\u0000`, six ASCII bytes.)
+ let line = serde_json::json!({
+ "type": "assistant",
+ "message": { "type": "text", "text": "bad@then 🌍 tail" }
+ })
+ .to_string()
+ + "\n";
+
+ let mut bytes: Vec<u8> = line.into_bytes();
+ let bad = bytes
+ .windows(8)
+ .position(|w| w == b"bad@then")
+ .expect("fixture contains the marker")
+ + 3;
+ // A lone lead byte of a 3-byte sequence: never valid on its own.
+ bytes[bad] = 0xE4;
+
+ let emoji_start = bytes
+ .windows(4)
+ .position(|w| w == "🌍".as_bytes())
+ .expect("fixture contains the emoji");
+ // Split inside the emoji, which sits after the invalid byte.
+ let split = emoji_start + 2;
+ assert!(
+ split > bad,
+ "precondition: the invalid byte has to come first for this to test anything"
+ );
+
+ let first = parser.feed_bytes(&bytes[..split]);
+ assert!(
+ first.is_empty(),
+ "no newline in the first chunk, so nothing should be emitted yet"
+ );
+
+ let events = parser.feed_bytes(&bytes[split..]);
+ assert_eq!(events.len(), 1, "the completed line must be emitted");
+
+ match &events[0] {
+ ClaudeCodeEvent::Assistant { message } => {
+ let text = message
+ .get("text")
+ .and_then(Value::as_str)
+ .expect("the fixture carries the text field");
+ assert!(
+ text.contains('🌍'),
+ "the split emoji must survive an invalid byte earlier in the chunk, got {text:?}"
+ );
+ assert!(
+ text.contains(char::REPLACEMENT_CHARACTER),
+ "the invalid byte should still surface as a replacement, got {text:?}"
+ );
+ }
+ other => panic!("expected the assistant line to parse, got {other:?}"),
+ }
+}
+
+/// `feed_bytes` is handed arbitrary read boundaries (the driver reads into an
+/// 8 KiB buffer), so a multi-byte character can straddle two chunks. Decoding
+/// each chunk independently replaced both halves with U+FFFD, and because that
+/// character is legal inside a JSON string the line still parsed -- the text was
+/// corrupted with no error raised anywhere.
+#[test]
+fn feed_bytes_preserves_a_character_split_across_chunks() {
+ let line = serde_json::json!({
+ "type": "assistant",
+ "message": { "type": "text", "text": "héllo 世界 🌍 tail" }
+ })
+ .to_string()
+ + "\n";
+
+ // Split inside the emoji: its four bytes land on both sides of the boundary.
+ let bytes = line.as_bytes();
+ let emoji_start = line.find('🌍').expect("fixture contains the emoji");
+ let split = emoji_start + 2;
+ assert!(
+ !line.is_char_boundary(split),
+ "the split must be mid-character"
+ );
+
+ let mut p = StreamJsonParser::new();
+ let mut events = p.feed_bytes(&bytes[..split]);
+ events.extend(p.feed_bytes(&bytes[split..]));
+
+ assert_eq!(events.len(), 1);
+ let rendered = format!("{:?}", events[0]);
+ assert!(
+ rendered.contains("héllo 世界 🌍 tail"),
+ "text was corrupted across the chunk boundary: {rendered}"
+ );
+ assert!(
+ !rendered.contains('\u{FFFD}'),
+ "replacement character present: {rendered}"
+ );
+}
+
+/// Bytes that can never become valid must not stall the stream: the old lossy
+/// behaviour is kept for those, so only an *incomplete tail* is carried over.
+#[test]
+fn feed_bytes_still_replaces_genuinely_invalid_bytes() {
+ let mut p = StreamJsonParser::new();
+ let mut chunk: Vec<u8> = b"{\"type\":\"system\",\"session_id\":\"".to_vec();
+ chunk.push(0xFF); // not a valid UTF-8 lead byte in any position
+ chunk.extend_from_slice(b"\",\"schema_version\":\"2.0\"}\n");
+ let events = p.feed_bytes(&chunk);
+ assert_eq!(
+ events.len(),
+ 1,
+ "the line must still be emitted, not withheld"
+ );
+}