Skip to content

Commit 0dca835

Browse files
committed
fix(streaming): decode SSE lines strictly per WHATWG CR/LF/CRLF rules
Decode SSE streams incrementally over iter_bytes()/aiter_bytes() and split strictly on CR, LF, or CRLF instead of relying on httpx iter_lines() (which splits on Unicode line separators such as U+2028, U+2029, and U+0085 inside JSON payloads). Fixes #45
1 parent 519d982 commit 0dca835

3 files changed

Lines changed: 129 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ existing `0.1.0` release; earlier development prereleases are not listed.
1515

1616
### Fixed
1717

18+
- Decode SSE streams over raw byte chunks using WHATWG CR/LF/CRLF line splitting instead of `httpx`'s `iter_lines()`, preventing Unicode line separators (`\u2028`, `\u2029`, `\x85`) inside JSON payloads from splitting frames and failing with `APIResponseValidationError`.
1819
- Preserve historical string `configs[].permission_policy` values when leniently parsing Managed Agent, Session and Thread tool snapshots. Tools and configs retain model attribute access instead of becoming Browser models or raw dictionaries; known Browser/media variants keep their concrete types and strict validation still rejects invalid payloads.
1920
- Expose Managed MCP toolsets' top-level `permission_policy` in requests and Agent/Session/Thread responses, including `always_deny` without `configs`. Set server-wide defaults here: nested `default_config.permission_policy` is retained unchanged for compatibility but does not set the MCP default; omitting the top-level policy defaults to allow.
2021
- Accept `"latest"` and positive integer strings for child Agent `version` in Managed Agent multiagent rosters through the new `MultiagentAgentParams` type, and parse saved `"latest"` versions in Agent responses, including with `_strict_response_validation=True`. `MultiagentAgentUnion.version` is now typed `int | str`; Session and Deployment Agent references keep numeric versions.

‎src/qca/common/_streaming.py‎

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from __future__ import annotations
22

3+
import codecs
34
import json
5+
import re
46
import socket
57
import threading
68
from collections.abc import AsyncIterator, Iterator
@@ -13,6 +15,8 @@
1315

1416
T = TypeVar("T")
1517

18+
_SSE_NEWLINE_RE = re.compile(r"\r\n|\r|\n")
19+
1620

1721
class SSEDecoder:
1822
def __init__(self) -> None:
@@ -47,6 +51,50 @@ def __init__(self, response: httpx.Response, cast_to: Any, *, strict: bool = Fal
4751
self._strict = strict
4852
self._decoder = SSEDecoder()
4953
self._last_event_id: str | None = None
54+
self._byte_decoder = codecs.getincrementaldecoder(response.encoding or "utf-8")(errors="replace")
55+
self._line_buffer = ""
56+
self._trailing_cr = False
57+
self._seen_text = False
58+
59+
def _decode_chunk(self, chunk: bytes) -> list[str]:
60+
if not chunk:
61+
return []
62+
text = self._byte_decoder.decode(chunk, final=False)
63+
return self._feed_text(text) if text else []
64+
65+
def _flush_lines(self) -> list[str]:
66+
text = self._byte_decoder.decode(b"", final=True)
67+
lines = self._feed_text(text) if text else []
68+
if self._line_buffer:
69+
lines.append(self._line_buffer)
70+
self._line_buffer = ""
71+
self._trailing_cr = False
72+
return lines
73+
74+
def _feed_text(self, text: str) -> list[str]:
75+
if not self._seen_text:
76+
self._seen_text = True
77+
if text.startswith("\ufeff"):
78+
text = text[1:]
79+
if not text:
80+
return []
81+
if self._trailing_cr:
82+
self._trailing_cr = False
83+
if text.startswith("\n"):
84+
text = text[1:]
85+
if not text:
86+
return []
87+
data = self._line_buffer + text
88+
lines: list[str] = []
89+
start = 0
90+
length = len(data)
91+
for match in _SSE_NEWLINE_RE.finditer(data):
92+
lines.append(data[start : match.start()])
93+
start = match.end()
94+
if match.group(0) == "\r" and start == length:
95+
self._trailing_cr = True
96+
self._line_buffer = data[start:]
97+
return lines
5098

5199
@property
52100
def last_event_id(self) -> str | None:
@@ -127,7 +175,17 @@ def __next__(self) -> T:
127175

128176
def _iter_events(self) -> Iterator[T]:
129177
try:
130-
for line in self.response.iter_lines():
178+
for chunk in self.response.iter_bytes():
179+
for line in self._decode_chunk(chunk):
180+
frame = self._decoder.decode(line)
181+
if frame is None:
182+
continue
183+
if frame[0] == "ping":
184+
continue
185+
if frame[1] == "[DONE]":
186+
return
187+
yield self._parse(frame)
188+
for line in self._flush_lines():
131189
frame = self._decoder.decode(line)
132190
if frame is None:
133191
continue
@@ -163,7 +221,17 @@ async def __anext__(self) -> T:
163221

164222
async def _iter_events(self) -> AsyncIterator[T]:
165223
try:
166-
async for line in self.response.aiter_lines():
224+
async for chunk in self.response.aiter_bytes():
225+
for line in self._decode_chunk(chunk):
226+
frame = self._decoder.decode(line)
227+
if frame is None:
228+
continue
229+
if frame[0] == "ping":
230+
continue
231+
if frame[1] == "[DONE]":
232+
return
233+
yield self._parse(frame)
234+
for line in self._flush_lines():
167235
frame = self._decoder.decode(line)
168236
if frame is None:
169237
continue

‎tests/test_streaming.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,64 @@ def handle(request):
6767
assert chunks.closed
6868

6969

70+
@pytest.mark.parametrize("separator", ["\u2028", "\u2029", "\x85"])
71+
def test_sse_preserves_unicode_line_separators_inside_json_payloads(separator):
72+
body = (
73+
"\ufeff"
74+
": comment\x0bwith\x0ccontrols\r\n"
75+
f'id: sep-1\r\nevent: agent.message\r\ndata: {{"content":[{{"type":"text","text":"before{separator}after"}}]}}\r\n\r\n'
76+
'id: sep-2\revent: agent.message\rdata: {"content":[{"type":"text","text":"cr-only"}]}\r\r'
77+
).encode("utf-8")
78+
chunks = Chunks(body)
79+
80+
with Forward(
81+
pat="test",
82+
http_client=httpx.Client(
83+
transport=httpx.MockTransport(
84+
lambda _: httpx.Response(200, stream=chunks, headers={"content-type": "text/event-stream"})
85+
)
86+
),
87+
) as client:
88+
with client.sessions.events.stream("session") as stream:
89+
events = list(stream)
90+
assert [event.id for event in events] == ["sep-1", "sep-2"]
91+
assert events[0].content[0]["text"] == f"before{separator}after"
92+
assert events[1].content[0]["text"] == "cr-only"
93+
assert chunks.closed
94+
95+
96+
async def test_async_sse_preserves_unicode_line_separators_and_split_crlf():
97+
class SplitChunks(httpx.AsyncByteStream):
98+
closed = False
99+
100+
async def __aiter__(self):
101+
payload = 'id: a1\r\nevent: agent.message\r\ndata: {"content":[{"type":"text","text":"line\u2028break"}]}\r\n\r\n'.encode(
102+
"utf-8"
103+
)
104+
# Deliver one byte at a time so CRLF and multi-byte UTF-8 cross chunk boundaries.
105+
for index in range(len(payload)):
106+
yield payload[index : index + 1]
107+
108+
async def aclose(self):
109+
self.closed = True
110+
111+
chunks = SplitChunks()
112+
async with AsyncManaged(
113+
pat="test",
114+
http_client=httpx.AsyncClient(
115+
transport=httpx.MockTransport(
116+
lambda _: httpx.Response(200, stream=chunks, headers={"content-type": "text/event-stream"})
117+
)
118+
),
119+
) as client:
120+
async with await client.sessions.events.stream("session") as stream:
121+
events = [event async for event in stream]
122+
assert len(events) == 1
123+
assert events[0].id == "a1"
124+
assert events[0].content[0].text == "line\u2028break"
125+
assert chunks.closed
126+
127+
70128
@pytest.mark.parametrize(
71129
"body,error",
72130
[

0 commit comments

Comments
 (0)