Decoding text that arrives in pieces
UTF-8 spends one byte on ASCII characters and two to four bytes on everything else. The network does not know where one character ends and the next begins, so a read can stop after the first byte of a two-byte "é", or after the second byte of a three-byte Chinese character. Decoding each read separately breaks exactly those characters.
What goes wrong
Decoding the first read of the example above on its own sees a lead byte with no continuation. A strict decoder raises an error and the stream handler dies; a lenient one emits U+FFFD, the replacement character, and the following read starts with an orphaned continuation byte that becomes a second U+FFFD. Either way the text that reaches the user is damaged, and only for some languages, which is why the bug survives testing in English.
The same applies to emoji, which take four bytes in UTF-8, and to any text the model writes in a non-Latin script.
Incremental decoders
Both major runtimes ship a decoder that remembers an incomplete sequence and finishes it with the next input.
In Python, the codecs module provides one:
import codecs
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
text = decoder.decode(chunk) # call once per read
tail = decoder.decode(b"", final=True) # at the end of the body
In JavaScript, TextDecoder does the same when told more input is coming:
const decoder = new TextDecoder("utf-8");
let text = decoder.decode(chunk, { stream: true }); // for every read
text += decoder.decode(); // flush at the end
Python's str and JavaScript's strings then hold complete characters only. The final call with no input flushes any
bytes still held back; at the end of a well-formed stream it returns an empty string.
Decode first, then split
Line splitting has to happen on decoded text, not on bytes, or on bytes with care. In UTF-8 the bytes for carriage return and line feed never appear inside a multi-byte sequence, so splitting raw bytes at those values is safe, but then every line still needs an incremental decoder of its own. Decoding the whole stream through one incremental decoder and splitting the text, as the parser in the previous chapter does, is simpler and has no corner cases.
A test that catches it
Take a sample stream that contains at least one accented letter, one character from a CJK script and one emoji. Feed it to the parser in reads of one byte, then two, then three, and compare the assembled text with the original. A decoder that handles single-byte reads correctly handles everything.
What not to do
- Do not use
errors="ignore". It hides the bug by deleting characters. - Do not retry decoding the concatenation of all reads so far on every read. It works, but it makes the cost of a stream grow with the square of its length.
- Do not trust the
charsetin the response headers for event streams. The format is always UTF-8.