Skip to content

fix: refine think stream parsing - #15745

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b066
Jun 8, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b066

Conversation

@buua436

@buua436 buua436 commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Refine the stream parsing for <think> / </think> so MiniMax and DeepSeek-style chunking both flush in the right order without mixing think and answer buffers.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Refactors the <think>...</think> streaming parser in dialog_service: adds separate think_buffer and answer_buffer, close_pending/pending_after_close for cross-chunk tag boundaries, and rewrites _stream_with_think_delta to emit marker events and token-sized text chunks while correctly flushing buffered segments.

Changes

Think-stream parser refactoring

Layer / File(s) Summary
State, helpers, and core parse loop
api/db/services/dialog_service.py
_ThinkStreamState refactored to separate think_buffer and answer_buffer; added close_pending and pending_after_close. _stream_with_think_delta rewritten with helper emit/flush routines, a pending buffer driven parse loop that detects <think>/</think>, emits marker events, strips tags, defers post-close answer content, and flushes buffered text at transitions and end-of-stream.
Unit tests for think-stream parser
test/testcases/unit/test_think_stream_parser.py
Adds async unit tests enumerating many chunk/tag edge cases, runs _stream_with_think_delta over provided chunk sequences, collects markers and reconstructed think/answer text, and asserts expected outputs and marker sequences.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15651: Fixes cursor/duplicate handling immediately after </think>, related to post-close emission handling in the parser.
  • infiniflow/ragflow#15582: Also addresses leftover text after </think> across chunk boundaries in the same parser.

Suggested labels

size:S

Suggested reviewers

  • Haruko386

Poem

A rabbit parses streams by moonlight's gleam, 🐇
Hopping through tags, gathering each dream,
Thoughts buffered gently, answers set free,
Chunks stitch together — neat harmony,
The parser hops on, content as can be. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: refining think stream parsing for proper tag handling and buffer management.
Description check ✅ Passed The description includes both required sections (problem statement and type of change) with appropriate detail about the bug being fixed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

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

@buua436
buua436 marked this pull request as ready for review June 8, 2026 02:32
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 8, 2026
@buua436 buua436 added the ci Continue Integration label Jun 8, 2026
@buua436
buua436 marked this pull request as draft June 8, 2026 02:33
@buua436
buua436 marked this pull request as ready for review June 8, 2026 02:33

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/db/services/dialog_service.py`:
- Around line 1474-1478: The branch that checks num_tokens_from_string against
min_tokens has mis-indented lines inside the function using state.answer_buffer;
fix the IndentationError by aligning the inner block (the assignment
state.answer_buffer = "" and the return out) to the same indentation level as
the if body and ensure the final return None aligns with the if (so the if, its
body, and the subsequent return all use consistent indentation) in the function
that contains state.answer_buffer and num_tokens_from_string.
- Around line 1543-1548: When switching from answer mode to think mode (the
branch that checks state.in_think and yields ("marker", "<think>", state)), the
code incorrectly calls _flush_think_buffer() even though buffered content is in
the answer buffer; change the flush to the answer buffer flush (call the
function that empties answer_buffer, e.g., _flush_answer_buffer()) so any
pending answer text is emitted before setting state.in_think = True and yielding
the "<think>" marker, and keep the rest of the logic (yielding flushed text if
not None, setting state.in_think, yielding marker) unchanged.
- Around line 1565-1576: At stream end, when state.close_pending is True the
code clears buffers and sets state.in_think = False but never emits the closing
marker; update the end-of-stream block in dialog_service.py to, if
state.close_pending is True, first yield ("marker", "</think>", state), clear
state.close_pending, then proceed to flush any
state.pending_after_close/state.answer_buffer/state.think_buffer and set
state.in_think = False so downstream consumers receive the end-to-think marker;
reference the existing variables state.close_pending, state.pending_after_close,
state.think_buffer, state.answer_buffer and state.in_think to locate and modify
the logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1380bc03-da5f-4560-80a6-055106d1b4f3

📥 Commits

Reviewing files that changed from the base of the PR and between b0a4580 and 5aae28e.

📒 Files selected for processing (1)
  • api/db/services/dialog_service.py

Comment thread api/db/services/dialog_service.py Resolved
Comment thread api/db/services/dialog_service.py Resolved
Comment thread api/db/services/dialog_service.py Resolved
@codecov

codecov Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (b0a4580) to head (6ca4cad).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15745   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review: fix: refine think stream parsing (#15745)

This PR rewrites the <think>/</think> streaming parser in _stream_with_think_delta, replacing the old delta-based approach with a new loop that maintains separate think_buffer and answer_buffer buffers and explicitly marks tag boundaries. The approach is cleaner, but there are 3 bugs that need fixing before merge.


Bug 1 — Missing </think> marker at end-of-stream (lines 1574-1575)

    if state.close_pending:
        state.in_think = False

When the stream ends while close_pending is True, the code only flips in_think but never yields ("marker", "</think>", state). Downstream consumers (lines 325-328, 889-892, 1683-1686) rely on this marker to set end_to_think: True on the response — without it, the client never gets the end-of-think signal and may misrender the answer.

Compare with the old code which did emit it:

    if state.endswith_think:
        yield ("marker", "</think>", state)

Fix: yield the </think> marker before clearing in_think:

    if state.close_pending:
        yield ("marker", "</think>", state)
        state.in_think = False

Bug 2 — Answer buffer not flushed when switching to think mode (lines 1543-1548)

                if not state.in_think:
                    think_piece = _flush_think_buffer()
                    if think_piece is not None:
                        yield ("text", think_piece, state)
                    state.in_think = True
                    yield ("marker", "<think>", state)

When entering think mode from answer mode, the code flushes _flush_think_buffer() but that buffer is empty (we were in answer mode). Meanwhile, state.answer_buffer may contain text from before the <think> tag that hasn't reached the min_tokens threshold yet. This text becomes stuck — never emitted, and will eventually be flushed as answer text at end-of-stream, out of order with the think content.

Fix: Add a _flush_answer_buffer helper and call it here:

    def _flush_answer_buffer():
        if not state.answer_buffer:
            return None
        out = state.answer_buffer
        state.answer_buffer = ""
        return out

    # then in the <think> handler:
    if not state.in_think:
        answer_piece = _flush_answer_buffer()
        if answer_piece is not None:
            yield ("text", answer_piece, state)
        state.in_think = True
        yield ("marker", "<think>", state)

Issue 3 — Indentation inconsistency in _emit_text (lines 1474-1477)

        if num_tokens_from_string(state.answer_buffer) >= min_tokens:
                out = state.answer_buffer
                state.answer_buffer = ""
                return out

The if body is indented by 8 spaces (to column 16) while the rest of the function uses 4-space increments per level (the think branch equivalent is at column 12→16). Python accepts this, but it's inconsistent and will confuse readers. Align to 4-space-per-level.


Minor: Dead field last_idx

_ThinkStreamState.last_idx (line 1438) was used by the removed _next_think_delta function. It is never read in the new code and should be removed from __init__.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
test/testcases/unit/test_think_stream_parser.py (2)

343-347: ⚡ Quick win

Remove unnecessary stdout redirection.

The stdout is redirected to a buffer that is never used or inspected. This adds unnecessary complexity without providing value.

♻️ Proposed fix
         for case_name, case in CASES:
             with self.subTest(case=case_name):
-                buf = io.StringIO()
-                with redirect_stdout(buf):
-                    think_text, answer_text, markers = asyncio.run(
-                        _collect_case(case["chunks"], case["min_tokens"])
-                    )
+                think_text, answer_text, markers = asyncio.run(
+                    _collect_case(case["chunks"], case["min_tokens"])
+                )

If this redirection was intended to suppress debug output, consider removing any debug print statements from the implementation instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/unit/test_think_stream_parser.py` around lines 343 - 347, The
test is redirecting stdout to an unused StringIO buffer around the call to
asyncio.run(_collect_case(...)); remove the temporary buf and the with
redirect_stdout(buf): block so the test simply calls
asyncio.run(_collect_case(case["chunks"], case["min_tokens"])) and assigns
think_text, answer_text, markers directly; if stdout suppression was required,
remove or silence debug prints inside _collect_case instead of swallowing output
here.

352-353: 💤 Low value

Consider validating markers for all test cases.

Currently, only some test cases validate the markers sequence. For consistency and completeness, consider adding expected markers to all cases to ensure the marker emission behavior is fully validated across all scenarios.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/unit/test_think_stream_parser.py` around lines 352 - 353, The
test only asserts markers when an individual test case includes an "markers"
key; update the test data so every case includes an expected "markers" sequence
and keep the existing assertion (self.assertEqual(markers, expected["markers"],
case_name)) to validate marker emission across all scenarios; look for the test
cases collection (e.g., the list/dict of cases used by test_think_stream_parser)
and add a "markers" entry for each case to reflect the expected marker sequence
for that scenario.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/testcases/unit/test_think_stream_parser.py`:
- Around line 339-340: The test method in TestThinkStreamParser
(test_think_stream_parser_cases) needs a pytest priority marker; add an import
for pytest if missing and annotate the method with the appropriate marker (e.g.,
add `@pytest.mark.p1` directly above def test_think_stream_parser_cases(self):) so
the test carries the required p1/p2/p3 priority marker.

---

Nitpick comments:
In `@test/testcases/unit/test_think_stream_parser.py`:
- Around line 343-347: The test is redirecting stdout to an unused StringIO
buffer around the call to asyncio.run(_collect_case(...)); remove the temporary
buf and the with redirect_stdout(buf): block so the test simply calls
asyncio.run(_collect_case(case["chunks"], case["min_tokens"])) and assigns
think_text, answer_text, markers directly; if stdout suppression was required,
remove or silence debug prints inside _collect_case instead of swallowing output
here.
- Around line 352-353: The test only asserts markers when an individual test
case includes an "markers" key; update the test data so every case includes an
expected "markers" sequence and keep the existing assertion
(self.assertEqual(markers, expected["markers"], case_name)) to validate marker
emission across all scenarios; look for the test cases collection (e.g., the
list/dict of cases used by test_think_stream_parser) and add a "markers" entry
for each case to reflect the expected marker sequence for that scenario.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c487f239-fced-45eb-b2f8-96616eda3265

📥 Commits

Reviewing files that changed from the base of the PR and between 20bfd4b and 6ca4cad.

📒 Files selected for processing (2)
  • api/db/services/dialog_service.py
  • test/testcases/unit/test_think_stream_parser.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/db/services/dialog_service.py

Comment on lines +339 to +340
class TestThinkStreamParser(unittest.TestCase):
def test_think_stream_parser_cases(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add pytest priority marker to the test method.

The test method is missing a pytest priority marker (p1/p2/p3). As per coding guidelines, Python tests should use pytest with priority markers.

📝 Proposed fix
+import pytest
+
 class TestThinkStreamParser(unittest.TestCase):
+    `@pytest.mark.p1`
     def test_think_stream_parser_cases(self):
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/testcases/unit/test_think_stream_parser.py` around lines 339 - 340, The
test method in TestThinkStreamParser (test_think_stream_parser_cases) needs a
pytest priority marker; add an import for pytest if missing and annotate the
method with the appropriate marker (e.g., add `@pytest.mark.p1` directly above def
test_think_stream_parser_cases(self):) so the test carries the required p1/p2/p3
priority marker.

Source: Coding guidelines

@wangq8
wangq8 merged commit c8c890b into infiniflow:main Jun 8, 2026
1 check passed
SailedApple1991 added a commit to SailedApple1991/greenlaw-ragflow that referenced this pull request Jun 14, 2026
chat-internals port (route-independent; fork keeps /chats contract + parallel
gather + cache + infiniflow#12689). Replaced fork's think-stream helper block
(_ThinkStreamState / _next_think_delta / _stream_with_think_delta) with
upstream v0.26's final version, which folds in:
- infiniflow#15745 refine think stream parsing (big refactor; min_tokens 1->16)
- infiniflow#15891 remove think text buffering (real-time reasoning)
- infiniflow#15651 prevent duplicated post-think text
- infiniflow#15582 think stream tail handling
- infiniflow#14271 normalize think tags in final answer (adds _extract_visible_answer;
  removes _next_think_delta)
Plus applied infiniflow#14271's 2 consumer wraps: async_chat + async_ask now call
decorate_answer(_extract_visible_answer(...)).

SKIPPED infiniflow#13917 (remove final["answer"]=""): conflicts with fork's deliberate
answer-clearing — async_chat explicitly caches the full answer then blanks it
for the streaming client ('preserve full answer for caching before clearing').
Touching it risks fork's cache/stream contract.

Verified: call convention unchanged (3 consumers); _next_think_delta fully
removed (0 refs); _extract_visible_answer logic correct (5 cases); fork customs
intact (parallel gather x8, cache x5); py_compile. Live SSE smoke -> batch F.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants