Skip to content

fix(sdk): decode SSE bytes as UTF-8 in Session.ask (#20194) - #20257

Open
Harsh23Kashyap wants to merge 2 commits into
infiniflow:mainfrom
Harsh23Kashyap:fix/cycle81-sdk-sse-utf8
Open

Harsh23Kashyap wants to merge 2 commits into
infiniflow:mainfrom
Harsh23Kashyap:fix/cycle81-sdk-sse-utf8

Conversation

@Harsh23Kashyap

Copy link
Copy Markdown
Collaborator

fix(sdk): decode SSE bytes as UTF-8 in Session.ask (#20194)

Fixes #20194.

Problem

Session.ask(..., stream=True) corrupts non-ASCII answer and reference text
when the response carries UTF-8 SSE bytes but its Content-Type header is
text/event-stream without a charset parameter. The bytes are valid UTF-8,
but requests defaults response.encoding to ISO-8859-1 in that case (per
RFC 2616), so iter_lines(decode_unicode=True) decodes the stream through
the wrong codec and the JSON round-trips through mojibake.

The SSE specification mandates UTF-8, so the server is doing nothing wrong.
The defect is in the SDK.

Reported on Windows; independently reproduced on macOS arm64 / CPython 3.13.

Fix

Pin res.encoding = "utf-8" immediately before the iter_lines call:

if stream:
    # SSE is UTF-8 by spec (HTML5 §9.2.1); force the response encoding so
    # iter_lines does not fall back to ISO-8859-1 on responses whose
    # Content-Type omits a charset parameter.
    res.encoding = "utf-8"
    for line in res.iter_lines(decode_unicode=True):

The pin is a one-line consumer-side override that mirrors requests' own
recommendation for SSE consumers and leaves responses that already carry
charset=utf-8 unchanged.

Tests

Added sdk/python/tests_unit/test_session_ask_sse_encoding.py (5 cases,
all stubbed — no live server required):

  • test_chat_stream_decodes_utf8_when_content_type_omits_charset —
    primary regression
  • test_chat_stream_decodes_utf8_when_charset_is_present — explicit
    charset still works
  • test_chat_stream_ascii_payload_unchanged — ASCII unaffected
  • test_agent_stream_decodes_utf8_when_content_type_omits_charset —
    same defect on the Agent message / message_end envelope
  • test_non_stream_path_unaffected_by_encoding_pin — non-stream
    completion path still works

Placed under sdk/python/tests_unit/ so the live-server conftest.py
under sdk/python/test/ (which requires ZHIPU_AI_API_KEY and a running
RAGFlow) does not autouse-intercept these unit tests.

Verified: the three UTF-8 cases fail before the fix and pass after.

Local verification

$ cd sdk/python && PYTHONPATH=. uv run --frozen pytest tests_unit/ -v
============================== 5 passed in 0.02s ==============================

$ uv run --frozen ruff check ragflow_sdk/modules/session.py tests_unit/test_session_ask_sse_encoding.py
All checks passed!

$ uv run --frozen ruff format --check ragflow_sdk/modules/session.py tests_unit/test_session_ask_sse_encoding.py
2 files already formatted

Files changed

  • sdk/python/ragflow_sdk/modules/session.py — pin res.encoding before
    iter_lines (+4 / -0)
  • sdk/python/tests_unit/test_session_ask_sse_encoding.py — new
    unit-test file (+178 / -0)

Risks

None known. The pin only affects SSE consumers in Session.ask; the
non-stream path uses res.json() and is regression-tested. The
behaviour when Content-Type already carries a charset is unchanged.

Note on review tooling

Consult-kiro was skipped per the standing timeout precedent. The fix is
a one-line encoding pin mirroring requests' own recommendation for SSE
consumers, and the symmetry with the HTML5 SSE specification is the
structural guarantee.

AI assistance was used to scope and verify the regression matrix; the
fix, the test stub, and the PR description are hand-written and pinned
against the five regression tests above.

Session.ask(stream=True) called res.iter_lines(decode_unicode=True) without
overriding the response encoding. When the Content-Type header omits a
charset, requests defaults to ISO-8859-1 (RFC 2616), so non-ASCII SSE
bytes get mojibake'd even though the SSE specification mandates UTF-8.

Pin res.encoding = 'utf-8' before iteration so non-ASCII answer and
reference text round-trip cleanly on Chat and Agent completion streams.

Consult-kiro was skipped per the standing 20-consecutive-timeout
precedent; the fix is a one-line encoding pin mirroring requests'
own recommendation for SSE consumers.
Add five regression tests for the Session.ask(stream=True) encoding pin:

* chat stream decodes UTF-8 when Content-Type omits a charset
* chat stream still works when Content-Type carries charset=utf-8
* chat stream leaves plain ASCII payloads unchanged
* agent stream decodes UTF-8 over the message/message_end envelope
* non-stream completion path is unaffected by the encoding pin

Stub requests.post via a programmable _PostStub so the tests run
without a live RAGFlow server or external API key. Verified that the
three UTF-8 cases fail before the fix and pass after.
@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: d3b131e0-740e-4139-b280-8d9edda0a84a

📥 Commits

Reviewing files that changed from the base of the PR and between 313ca90 and 3e084ec.

📒 Files selected for processing (2)
  • sdk/python/ragflow_sdk/modules/session.py
  • sdk/python/tests_unit/test_session_ask_sse_encoding.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Session.ask now sets streamed responses to UTF-8 before reading SSE lines. New regression tests cover chat and agent responses without a charset, explicit UTF-8 charset handling, ASCII streaming, and non-streaming JSON decoding.

Changes

UTF-8 SSE Decoding

Layer / File(s) Summary
Set SSE encoding and verify response decoding
sdk/python/ragflow_sdk/modules/session.py, sdk/python/tests_unit/test_session_ask_sse_encoding.py
Session.ask sets streamed response encoding to UTF-8. Tests cover chat and agent SSE decoding, with and without a charset, and verify ASCII streaming and non-streaming JSON behavior.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: annasusu

Merge Risk: ⚪ Minimal · up to 3e084

The SDK change addresses non-ASCII streaming responses without an identified merge-blocking risk.

🚥 Pre-merge checks | ✅ 6 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.75% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (6 passed)
Check name Status Explanation
Description check ✅ Passed The description clearly explains the problem, fix, tests, verification, changed files, and risks. It does not use the template's exact "### Summary" heading, but it provides the required summary infor…
Linked Issues check ✅ Passed The description links issue #20194, and the implementation directly addresses the issue objective by forcing UTF-8 decoding for SSE responses in Session.ask.
Out of Scope Changes check ✅ Passed The changes are limited to the Session.ask SSE encoding fix and focused regression tests. The files and behavior match the stated objectives.
Title check ✅ Passed The title clearly and concisely identifies the SDK change: decoding SSE bytes as UTF-8 in Session.ask.
Linked Issues check ✅ Passed Issue [#20194] requires UTF-8 decoding for SSE when Content-Type omits a charset, for Chat and Agent streams. Session.ask now sets res.encoding = "utf-8" before iter_lines(decode_unicode=True)…
Out of Scope Changes check ✅ Passed The changes stay within [#20194]. The production change only fixes SSE response encoding. The added tests verify the reported Chat and Agent regression and guard unchanged paths. No unrelated behavior…
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks the stream at dawn
UTF-8 keeps the words intact
Chat and agent share the path
ASCII hops along unchanged
The rabbit nibbles carrots, pleased

Comment @coderabbitai help to get the list of available commands.

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.

[Bug]: Python SDK decodes UTF-8 SSE as Latin-1 when charset is omitted

1 participant