ai newsFr., 4. Dez.
EilmeldungAlibaba Releases Qwen4-35B-A3B: Open-Weight MoE Model With 1M Context

TextDecoder Without stream: true Broke 212 of 3,000 LLM Streams

A user sent me a screenshot of a Japanese answer from my chat app. Halfway through a sentence sat three black diamonds with question marks in them. ��� . The model had not written them. My frontend had. The bug was one missing option: I called TextDecoder.decode() on every chunk of the LLM st

dev.toDonnerstag 22:29 · 03.12.7 Min. Lesezeit
Bild: dev.to

A user sent me a screenshot of a Japanese answer from my chat app. Halfway through a sentence sat three black diamonds with question marks in them. ���. The model had not written them. My frontend had.

The bug was one missing option: I called TextDecoder.decode() on every chunk of the LLM stream without { stream: true }. When I replayed 3,000 recorded completions through my staging proxy, 212 of them came out corrupted. On localhost the same code corrupted zero. That gap is why I shipped it.

TextDecoder produces U+FFFD when the bytes it receives end in the middle of a multi-byte UTF-8 character and you have not told it more bytes are coming. Without stream: true, every decode() call is treated as the complete input. An incomplete sequence at the end is invalid, so it gets replaced.

Here is the code I had. It looks like every streaming tutorial you've skimmed:

const reader = res. body. getReader ( ); while ( true ) { const { done, value } = await reader. read ( ); if ( done ) break; const text = new TextDecoder ( ). decode ( value ); // bug #1 for ( const line of text. split ( "\n" ) ) { // bug #2 if (! line. startsWith ( "data: " ) ) continue; try { const evt = JSON. parse ( line. slice ( 6 ) ); onDelta ( evt. delta?. text?? "" ); } catch { } // bug #2's accomplice } } Enter fullscreen mode Exit fullscreen mode reader.read() hands you a Uint8Array of whatever bytes arrived. Not tokens, not events, not characters. Bytes. The server writes nice SSE events, but TCP, TLS records, proxies and the browser's own buffering are all free to cut that byte stream wherever they like.

ASCII never notices, because every ASCII character is one byte. You cannot cut a one-byte character in half. That's why my English test set came back clean and I felt great about it.

One split character creates 2 to 4 U+FFFD characters, depending on where the cut lands. The tail of chunk A becomes one � for the incomplete prefix. The head of chunk B is a run of continuation bytes with no lead byte, and each one becomes its own �.

That matches the screenshot exactly: one kanji, cut after its first byte, became three diamonds. The character is gone for good. You can't reassemble it from the replacement characters because the original bytes were thrown away.

I didn't want to measure against live model output, because two runs never produce the same text and I'd have nothing to diff against. So I recorded 3,000 completions once, as raw SSE byte streams, and built a tiny replay server that sends them back byte-for-byte.

Each replay went through two paths: straight to localhost, and through my staging reverse proxy over TLS, which is the same path production traffic takes. The client ran in headless Chromium with the old code and the fixed code. A stream counted as broken if its final text did not exactly equal the recorded reference.

const broken = output!== reference; const diamonds = ( output. match ( / � / g ) || [ ] ). length; Enter fullscreen mode Exit fullscreen mode Results: which streams broke? Set Streams Localhost, naive Proxy, naive Proxy, fixed English 1,000 0 0 0 Japanese 1,000 0 141 0 Emoji-heavy 1,000 0 71 0 Total 3,000 0 212 0 Across the 212 broken streams there were 307 destroyed characters and 781 U+FFFD characters. Most broken streams had exactly one bad spot, which is the worst possible failure mode for getting noticed. One glitch in a long answer looks like a font problem, so nobody files a ticket. One user did, and I owe them a coffee.

Japanese broke twice as often as emoji. That makes sense once you look at the bytes: nearly every byte of Japanese text sits inside a 3-byte character, so almost any arbitrary cut lands mid-character. In the emoji set, most bytes are still ASCII, and a cut only hurts if it lands inside one of the emoji.

It worked on localhost because nothing re-cut the bytes. I logged chunk boundaries on both paths. On localhost, each reader.read() returned exactly one SSE event, because the server flushed per event and nothing in between merged or split the writes. Every chunk ended on \n\n, which is always a character boundary.

Through the proxy, reads came back at arbitrary byte offsets. Sometimes two events glued together, sometimes an event sliced in the middle of a JSON string, sometimes in the middle of 日.

This is the part I'd tattoo on a junior dev: chunk boundaries are a property of the transport, not of your server. Your dev setup is the one environment where they happen to look tidy.

Create one TextDecoder for the whole stream and pass { stream: true } on every call. In streaming mode the decoder holds an incomplete trailing sequence in an internal buffer and prepends it to the next chunk. A final call without stream: true flushes whatever is left.

const decoder = new TextDecoder ( "utf-8" ); const reader = res. body. getReader ( ); let buf = ""; while ( true ) { const { done, value } = await reader. read ( ); buf += decoder. decode ( value, { stream:! done } ); // value is undefined when done: that call flushes const lines = buf. split ( "\n" ); buf = done? "": lines. pop ( ); // keep the partial last line for the next round for ( const line of lines ) { if (! line. startsWith ( "data: " ) ) continue; const payload = line. slice ( 6 ); if ( payload === "[DONE]" ) continue; const evt = JSON. parse ( payload ); // no silent catch: let it throw onDelta ( evt. delta?. text?? "" ); } if ( done ) break; } Enter fullscreen mode Exit fullscreen mode Three things changed.

The decoder moved out of the loop. stream: true went in. The partial last line now waits for the next chunk instead of being parsed half-finished.

If you don't need manual control, let the platform do it:

const textStream = res. body. pipeThrough ( new TextDecoderStream ( ) ); Enter fullscreen mode Exit fullscreen mode TextDecoderStream keeps the decoder state across chunks for you. You still need the line buffer, though, because a decoded string can still end in the middle of an SSE line.

The second bug was naive line splitting plus an empty catch {}. When a chunk ended in the middle of a data: {...} line, JSON.parse threw on the first half, the catch swallowed it, and the second half didn't start with data:, so it was skipped too. The whole delta vanished.

This one hits English just as hard, because it doesn't care about encoding. In the proxy run, 23 of 3,000 streams silently lost at least one delta: words missing from the middle of an answer, no error, no diamond, nothing. That's worse than the U+FFFD bug. Diamonds at least look broken.

The empty catch was there because "sometimes the stream has a weird line". It did. Every one of those weird lines was half of a real event.

Yes, if you decode bytes chunk by chunk yourself. chunk.decode("utf-8") on a split character raises UnicodeDecodeError, or quietly inserts � if you passed errors="replace" to make the exception go away. The fix is the same idea, an incremental decoder:

import codecs decoder = codecs. getincrementaldecoder ( "utf-8" ) ( ) for chunk in response. iter_bytes ( ): text = decoder. decode ( chunk ) # holds partial sequences... text_tail = decoder. decode ( b "", final = True ) Enter fullscreen mode Exit fullscreen mode Higher-level helpers that hand you text (like iter_text() in httpx) already use an incremental decoder internally. The bug shows up when you drop to raw bytes "for performance" and decode them yourself.

Total cost of this bug: one day of me blaming the font stack, one day building the replay harness, and a fix that added three lines.

TextDecoder without stream: true breaks LLM streams because network chunks split multi-byte UTF-8 characters, and a non-streaming decode replaces each half-character with U+FFFD. In my replay of 3,000 recorded completions through a real proxy, that corrupted 212 streams (141 Japanese, 71 emoji-heavy, 0 English), while localhost showed 0 failures. Use a single TextDecoder per stream with decode(value, { stream: true }) and a final flush, or TextDecoderStream, and buffer partial SSE lines so JSON.parse never sees half an event.

Written by the developer behind Preterview, an interview prep platform.

Quelle: dev.to (dev.to). Original öffnen