[GH-ISSUE #2472] [Issue]: Streaming responses corrupt multi-byte UTF-8 that straddles a network chunk boundary (mojibake) #1216

Closed
opened 2026-10-21 05:29:11 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @Romuromylus on GitHub (Jun 6, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2472

Originally assigned to: @SpicyMarinara on GitHub.

Summary

Severity: Medium — correctness regression. Every streaming provider path decodes each network chunk independently with String::from_utf8_lossy, so a multi-byte UTF-8 codepoint (emoji, CJK, accented letter, em dash, smart quote) whose bytes straddle a chunk boundary is corrupted into U+FFFD replacement characters and streamed to the chat as mojibake.

Expected behavior

Decode the byte stream statefully across chunks (carry trailing incomplete bytes to the next chunk), like main's TextDecoder(...).decode(value, { stream: true }), so split codepoints survive.

Actual behavior

All five SSE streaming loops push each chunk through from_utf8_lossy before SSE block assembly:

// src-tauri/crates/llm/src/lib.rs (Cohere 1998, OpenAI chat 2122, OpenAI Responses 2551, Anthropic 4286, Google 4999)
while let Some(chunk) = stream.next().await {
    let chunk = chunk.map_err(...)?;
    buffer.push_str(&String::from_utf8_lossy(&chunk));   // per-chunk lossy decode
    while let Some(block) = take_sse_block(&mut buffer) { ... }
}

A codepoint split across two chunks becomes invalid bytes on both sides → U+FFFD, before take_sse_block ever assembles the event, so SSE buffering cannot rescue it. The corrupted token is then emitted via emit(json!({"type":"token", ...})). The non-streaming path is correctly immune because it buffers the full body first, then calls from_utf8_lossy once on the complete byte vector. There is no encoding_rs/incremental decoder / valid_up_to carry-over anywhere in the streaming path.

Steps to reproduce

  1. Stream any LLM response (default mode) whose output contains non-ASCII glyphs — em dashes, accented character names, emoji, CJK (common in roleplay).
  2. Observe occasional �/garbled characters where a glyph landed on a chunk boundary; the more non-ASCII content and chunks, the more frequent.

Impact area

  • Runtime systems: generation, world-state, visuals, tracker, or haptics
  • Tauri/Rust storage, assets, LLM, integrations, security, imports, or HTTP runtime

Environment

  • Branch or commit: refactor @ 1fae2c42
  • Run mode: Tauri desktop
  • OS + version: found via static source audit (not runtime-reproduced)
  • Node + pnpm versions: n/a (static audit)
  • Rust version, if relevant: n/a (static audit)
  • Remote Runtime URL configured? not relevant
  • Provider, model, or integration, if relevant: all streaming providers (Cohere, OpenAI chat + Responses, Anthropic, Google)

Logs, screenshots, or video

Static trace: crates/llm/src/lib.rs:1998, 2122, 2551, 4286, 4999 (per-chunk from_utf8_lossy in the streaming loops); contrast the full-body decode in read_limited_provider_text.

Regression notes

Regression vs main, which decodes statefully: anthropic.provider.ts / google.provider.ts / openai.provider.ts use new TextDecoder().decode(value, { stream: true }), which holds back trailing incomplete bytes across chunks. The refactor's per-chunk lossy decode reintroduced the corruption. (The recent provider commits — 7e393a78, 70e76291, 80931cfc, 22fe2d73 — only touched the SSE block parsers and request shaping, not the byte-decode layer.)

Additional context

Fix: replace the per-chunk String::from_utf8_lossy with an incremental decoder that carries trailing 1-3 incomplete bytes into the next iteration — e.g. encoding_rs::UTF_8.new_decoder() with last = false, or a manual str::from_utf8(...).valid_up_to() split.

Template check

Please uncheck the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @Romuromylus on GitHub (Jun 6, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2472 Originally assigned to: @SpicyMarinara on GitHub. ## Summary **Severity: Medium — correctness regression.** Every streaming provider path decodes each network chunk independently with `String::from_utf8_lossy`, so a multi-byte UTF-8 codepoint (emoji, CJK, accented letter, em dash, smart quote) whose bytes straddle a chunk boundary is corrupted into U+FFFD replacement characters and streamed to the chat as mojibake. ## Expected behavior Decode the byte stream statefully across chunks (carry trailing incomplete bytes to the next chunk), like main's `TextDecoder(...).decode(value, { stream: true })`, so split codepoints survive. ## Actual behavior All five SSE streaming loops push each chunk through `from_utf8_lossy` before SSE block assembly: ```rust // src-tauri/crates/llm/src/lib.rs (Cohere 1998, OpenAI chat 2122, OpenAI Responses 2551, Anthropic 4286, Google 4999) while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(...)?; buffer.push_str(&String::from_utf8_lossy(&chunk)); // per-chunk lossy decode while let Some(block) = take_sse_block(&mut buffer) { ... } } ``` A codepoint split across two chunks becomes invalid bytes on both sides → U+FFFD, *before* `take_sse_block` ever assembles the event, so SSE buffering cannot rescue it. The corrupted token is then emitted via `emit(json!({"type":"token", ...}))`. The non-streaming path is correctly immune because it buffers the full body first, then calls `from_utf8_lossy` once on the complete byte vector. There is no `encoding_rs`/incremental decoder / `valid_up_to` carry-over anywhere in the streaming path. ## Steps to reproduce 1. Stream any LLM response (default mode) whose output contains non-ASCII glyphs — em dashes, accented character names, emoji, CJK (common in roleplay). 2. Observe occasional `�`/garbled characters where a glyph landed on a chunk boundary; the more non-ASCII content and chunks, the more frequent. ## Impact area - [x] Runtime systems: generation, world-state, visuals, tracker, or haptics - [x] Tauri/Rust storage, assets, LLM, integrations, security, imports, or HTTP runtime ## Environment - Branch or commit: refactor @ 1fae2c42 - Run mode: Tauri desktop - OS + version: found via static source audit (not runtime-reproduced) - Node + pnpm versions: n/a (static audit) - Rust version, if relevant: n/a (static audit) - Remote Runtime URL configured? not relevant - Provider, model, or integration, if relevant: all streaming providers (Cohere, OpenAI chat + Responses, Anthropic, Google) ## Logs, screenshots, or video Static trace: `crates/llm/src/lib.rs:1998, 2122, 2551, 4286, 4999` (per-chunk `from_utf8_lossy` in the streaming loops); contrast the full-body decode in `read_limited_provider_text`. ## Regression notes Regression vs main, which decodes statefully: `anthropic.provider.ts` / `google.provider.ts` / `openai.provider.ts` use `new TextDecoder().decode(value, { stream: true })`, which holds back trailing incomplete bytes across chunks. The refactor's per-chunk lossy decode reintroduced the corruption. (The recent provider commits — `7e393a78`, `70e76291`, `80931cfc`, `22fe2d73` — only touched the SSE block *parsers* and request shaping, not the byte-decode layer.) ## Additional context Fix: replace the per-chunk `String::from_utf8_lossy` with an incremental decoder that carries trailing 1-3 incomplete bytes into the next iteration — e.g. `encoding_rs::UTF_8.new_decoder()` with `last = false`, or a manual `str::from_utf8(...).valid_up_to()` split. ## Template check Please uncheck the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-21 05:29:11 +07:00
Author
Owner

@SpicyMarinara commented on GitHub (Jun 6, 2026):

Fixed on refactor in 038b7220.

Provider streaming now carries partial UTF-8 bytes across network chunks before decoding, preventing mojibake when multi-byte characters straddle chunk boundaries.

Verification: pnpm typecheck; pnpm build; pnpm check:architecture; cargo check --manifest-path src-tauri/Cargo.toml --workspace; focused Rust backup/profile tests; git diff --check; no .test.ts/.test.tsx files present.

<!-- gh-comment-id:4638720333 --> @SpicyMarinara commented on GitHub (Jun 6, 2026): Fixed on refactor in 038b7220. Provider streaming now carries partial UTF-8 bytes across network chunks before decoding, preventing mojibake when multi-byte characters straddle chunk boundaries. Verification: pnpm typecheck; pnpm build; pnpm check:architecture; cargo check --manifest-path src-tauri/Cargo.toml --workspace; focused Rust backup/profile tests; git diff --check; no .test.ts/.test.tsx files present.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1216
No description provided.