What causes broken UTF-8 multibyte characters when slicing raw byte chunks in an SSE stream reader? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

What causes broken UTF-8 multibyte characters when slicing raw byte chunks in an SSE stream reader?

message-square
0

How Broken UTF-8 Multibyte Characters Happen in SSE Stream Readers

In UTF-8, characters are encoded using 1 to 4 bytes: ASCII characters take 1 byte (0xxxxxxx), while accented Latin characters, emojis, or non-Latin scripts (such as Urdu, Arabic, CJK) take 2 to 4 bytes where leading bytes start with 110xxxxx, 1110xxxx, or 11110xxx and continuation bytes start with 10xxxxxx. In a Server-Sent Events (SSE) stream, TCP packets and chunked HTTP reads split bytes at arbitrary network boundaries—so a 3- or 4-byte character can arrive with its first 1–2 bytes in chunk $N$ and its remaining bytes in chunk $N+1$.

  • Premature per-chunk decoding (Buffer.toString("utf8") or TextDecoder without { stream: true }): Calling chunk.toString("utf8") or new TextDecoder().decode(chunk) on each raw byte chunk independently decodes incomplete trailing bytes at the end of a chunk into Unicode replacement characters (U+FFFD, ``) instead of waiting for the remaining bytes in the next chunk.
  • String-level slicing after decoding: Even if decoding succeeds, slicing decoded JavaScript strings by UTF-16 code units rather than complete UTF-8 sequences or SSE event boundaries (\n\n) can split surrogate pairs (such as emojis outside the Basic Multilingual Plane) or truncate data: payloads mid-character.
  • SSE framing + byte boundaries interacting: SSE lines are delimited by \n (or \r\n), and events are separated by blank lines (\n\n). Splitting raw bytes directly into strings before handling incomplete trailing UTF-8 sequences corrupts both text content and SSE event lines if a multibyte character straddles a chunk split.

Steps to Prevent Broken UTF-8 Characters in an SSE Stream Reader

  1. Decode bytes incrementally with TextDecoder(..., { stream: true }) or StringDecoder: Use a stateful decoder (new TextDecoder("utf-8", { stream: true }) in Web Streams/fetch or StringDecoder("utf8") from node:string_decoder) that buffers incomplete trailing multibyte sequences internally until the next chunk supplies the missing bytes.
  2. Buffer SSE lines/events cleanly after stateful decoding: Append decoded text chunks to an event/line buffer and split on \n or \n\n boundaries, keeping any incomplete trailing event/line in the buffer for the next chunk.
  3. Flush the decoder on stream end (decoder.decode()): Call decoder.decode() with no arguments (or decoder.end()) once the stream closes so any final buffered bytes are flushed cleanly and any genuinely truncated trailing byte sequence at EOF is surfaced or handled explicitly.
  4. Test with split multibyte sequences and multi-chunk SSE frames: Unit-test your SSE parser by feeding byte arrays split at every single byte offset across 2-, 3-, and 4-byte UTF-8 characters (like é, 中, اردو, and 🚀).

TypeScript Example: Stateful UTF-8 Decoding in a Fetch SSE Reader

export interface SseEvent {
  event: string;
  data: string;
}

/**
 * Reads an SSE byte stream without splitting UTF-8 multibyte characters across chunks.
 * Uses `{ stream: true }` on TextDecoder so partial 2-4 byte sequences wait for
 * subsequent bytes before being decoded into strings.
 */
export async function* readSseStream(
  body: ReadableStream<Uint8Array>,
  signal?: AbortSignal
): AsyncGenerator<SseEvent, void, unknown> {
  const reader = body.getReader();
  const decoder = new TextDecoder("utf-8", { stream: true });
  let buffer = "";

  try {
    while (true) {
      if (signal?.aborted) {
        throw new DOMException("SSE stream aborted", "AbortError");
      }

      const { value, done } = await reader.read();
      if (done) {
        break;
      }

      if (value && value.byteLength > 0) {
        // `stream: true` holds back incomplete trailing UTF-8 bytes until the next chunk
        buffer += decoder.decode(value, { stream: true });
      }

      // Normalize CRLF to LF for consistent SSE frame parsing
      buffer = buffer.replace(/\r\n/g, "\n");

      let separatorIndex = buffer.indexOf("\n\n");
      while (separatorIndex !== -1) {
        const rawEvent = buffer.slice(0, separatorIndex);
        buffer = buffer.slice(separatorIndex + 2);

        const parsed = parseSseFrame(rawEvent);
        if (parsed) {
          yield parsed;
        }

        separatorIndex = buffer.indexOf("\n\n");
      }
    }

    // Flush any remaining buffered bytes at stream completion
    buffer += decoder.decode().replace(/\r\n/g, "\n");
    if (buffer.trim().length > 0) {
      const parsed = parseSseFrame(buffer);
      if (parsed) {
        yield parsed;
      }
    }
  } finally {
    reader.releaseLock();
  }
}

function parseSseFrame(rawFrame: string): SseEvent | null {
  let eventName = "message";
  const dataLines: string[] = [];

  for (const line of rawFrame.split("\n")) {
    if (!line || line.startsWith(":")) {
      continue;
    }
    const colonIdx = line.indexOf(":");
    const field = colonIdx === -1 ? line : line.slice(0, colonIdx);
    let value = colonIdx === -1 ? "" : line.slice(colonIdx + 1);
    if (value.startsWith(" ")) {
      value = value.slice(1);
    }

    if (field === "event") {
      eventName = value || "message";
    } else if (field === "data") {
      dataLines.push(value);
    }
  }

  if (dataLines.length === 0) {
    return null;
  }

  return {
    event: eventName,
    data: dataLines.join("\n"),
  };
}

Helpful Tips for Production SSE & Streaming Pipelines

  • Never slice raw Uint8Array or Buffer by character count: Byte length and character/code-point count differ dramatically in UTF-8; always frame SSE events on byte/decoded delimiters (\n\n) rather than slicing fixed byte lengths.
  • Watch out for JSON JSON.parse failures on split SSE data: lines: Even with intact UTF-8 characters, a single JSON payload can occasionally be split across multiple data: lines in an SSE event—join dataLines with \n before calling JSON.parse.
  • Ensure Content-Type: text/event-stream; charset=utf-8 on upstream emitters: Explicitly declaring UTF-8 on both server and client avoids ambiguous charset fallbacks and keeps non-Latin scripts and emojis intact end-to-end.