Skip to content

fix(llm_gateway): split streamed SSE lines only at CR, LF and CRLF - #364

Open
chinesepowered wants to merge 1 commit into
AssemblyAI:masterfrom
chinesepowered:fix/llm-stream-sse-line-splitting-341
Open

chinesepowered wants to merge 1 commit into
AssemblyAI:masterfrom
chinesepowered:fix/llm-stream-sse-line-splitting-341

Conversation

@chinesepowered

@chinesepowered chinesepowered commented Nov 30, 2026 •

Copy link
Copy Markdown

What changes

stream_completion (sync and async) now splits the SSE body only at CRLF, LF and CR, as the SSE spec requires, instead of with httpx iter_lines(), which follows str.splitlines() and also splits at U+2028, U+2029, U+0085 and other characters that JSON allows unescaped inside strings. Partial lines, including a CR split from its LF across reads, are buffered. The data: prefix handling is unchanged, so this doesn't overlap #272.

Fixes #341

Before and after

A streamed delta whose content is "Line one", then U+2028, then "line two" (script from the issue).

Before, sync and async:

RAISED json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 136 (char 135)

After: both deltas arrive intact, with the separator kept inside the first one. The same holds for U+2029 and U+0085.

Tests

  • test_chat_completions_stream_keeps_unicode_line_separators, parametrized over the three characters, sync and async: fails on master, passes with the fix.
  • test_chat_completions_stream_joins_lines_split_across_reads: CRLF, LF and CR line endings plus a multi-byte character, fed one byte per read, sync and async. It guards the new splitter (it passes on master too).

Also checked on httpx 0.22 / Python 3.9 / pydantic 1. Full unit suite (Python 3.12) passes apart from two existing Windows-only failures that also fail on master; ruff 0.3.5 and mypy 1.5.1 on Python 3.9 are clean on the changed source files.

Note: #365 and #366 change neighboring lines of the same stream_completion loop, so whichever of the three merges later needs a small rebase.

stream_completion read the event stream with httpx's iter_lines()/aiter_lines(), which follow str.splitlines() and also break at U+2028, U+2029, U+0085 and other characters that JSON allows unescaped inside strings. A delta containing one of them cut its data: line in two and the stream ended with a JSONDecodeError. The body is now read with iter_text()/aiter_text() and split only at CRLF, LF and CR, buffering a partial line (including a CR that may be half of a CRLF) across reads. The data: prefix handling is unchanged.

Fixes AssemblyAI#341
"""The asyncio counterpart of `api._iter_sse_lines`."""
rest = ""
async for text in texts:
lines, rest = _split_sse_lines(rest + text)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concatenating and rescanning the growing rest on every read makes long SSE lines split across many chunks quadratic to process.

Details

✨ AI Reasoning
​An async streamed JSON payload can span many reads. While a line is incomplete, rest grows and is repeatedly copied and processed by _split_sse_lines, so work increases quadratically with the number of chunks.

🔧 How do I fix it?
Move constant work outside loops. Use StringBuilder instead of string concatenation in loops. Cache compiled regex patterns. Use hash-based lookups instead of nested loops. Batch database operations instead of N+1 queries.

Reply on this comment to give feedback or ignore the issue.
More info

"""Yields the lines of an event stream read as pieces of decoded text."""
rest = ""
for text in texts:
lines, rest = _split_sse_lines(rest + text)

@aikido-pr-checks aikido-pr-checks Bot Nov 30, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concatenating and rescanning the growing rest on every read makes long SSE lines split across many chunks quadratic to process.

Show fix
Suggested change
lines, rest = _split_sse_lines(rest + text)
lines, rest = _split_sse_lines(text)
if rest and lines:
lines[0] = rest + lines[0]
elif rest:
rest = rest + text
Details

✨ AI Reasoning
​A streamed JSON payload can span many reads. When no line terminator has arrived, rest grows on every iteration, and _split_sse_lines processes the entire accumulated text again. This creates avoidable repeated copying and scanning for long lines.

Reply on this comment to give feedback or ignore the issue.
More info

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LLM Gateway stream=True crashes with JSONDecodeError when a chunk contains U+2028, U+2029 or U+0085 (SSE lines split with iter_lines())

1 participant