Skip to content

fix(dialog): restore decorated answer in async_ask final SSE event - #13917

Merged
yingfeng merged 5 commits into
infiniflow:mainfrom
edenfunf:fix/async-ask-drops-decorated-answer
Apr 15, 2026
Merged

yingfeng merged 5 commits into
infiniflow:mainfrom
edenfunf:fix/async-ask-drops-decorated-answer

Conversation

@edenfunf

@edenfunf edenfunf commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

What's the problem

Both async_chat() and async_ask() call decorate_answer() to build the final SSE payload — it inserts citation markers (##N$$) into the answer text and prunes doc_aggs to only the cited documents. Immediately after, both functions overwrite final["answer"] with "":

# async_chat(), line ~774  (issue #13828)
final = decorate_answer(thought + full_answer)
final["final"] = True
final["audio_binary"] = None
final["answer"] = ""   # discards decorated text
yield final

# async_ask(), line ~1444  (same bug, different path)
final = decorate_answer(full_answer)
final["final"] = True
final["answer"] = ""   # discards decorated text
yield final

The client receives filtered references (built for a citation-decorated answer it never sees) while displaying the raw, undecorated streaming text. Citations can never match.

Root cause

final["answer"] = "" was left over from an earlier design where clients were meant to reconstruct the full answer purely from delta events. Once decorate_answer() started placing citation markers, this blank-out broke the contract: the final event is where the decorated answer should land.

Fix

Remove the two blank-override lines — one in async_chat(), one in async_ask():

-    final["answer"] = ""

decorate_answer() already sets final["answer"] to the correct decorated string; there is nothing to override.

Relation to #13828

Issue #13828 and PR #13835 identify the bug in async_chat(). This PR absorbs that fix and also corrects the identical pattern in async_ask() (used by the /retrieval route in chat_api.py), which PR #13835 does not touch.

Regression test

Added test/unit_test/api/db/services/test_dialog_service_final_answer.py with three tests:

Test Purpose
test_buggy_pattern_drops_answer Documents the old behaviour: blank-override empties the final answer
test_fixed_pattern_preserves_decorated_answer Core invariant: final event carries the decorated text from decorate_answer()
test_final_event_reference_matches_decorated_result Citation markers in the answer must match the pruned doc_aggs in the same event

Local run result:

test_dialog_service_final_answer.py::test_buggy_pattern_drops_answer         PASSED
test_dialog_service_final_answer.py::test_fixed_pattern_preserves_decorated_answer PASSED
test_dialog_service_final_answer.py::test_final_event_reference_matches_decorated_result PASSED

3 passed in 0.04s

ruff check passes with no issues on all changed files.

async_ask() calls decorate_answer() which inserts citation markers and
filters doc_aggs to the cited documents, then immediately overwrites
final["answer"] with "", discarding the decorated text.

Clients receive the filtered references but the raw undecorated answer
text from the streamed deltas, so citations never match the displayed
content. Removing the blank assignment lets the decorated answer reach
the client as intended.

The same issue in async_chat() is addressed in infiniflow#13835.
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Apr 3, 2026
@edenfunf

edenfunf commented Apr 4, 2026

Copy link
Copy Markdown
Contributor Author

Hi maintainers,

This PR fixes a bug in async_ask where the final SSE event drops the decorated answer.

Root cause:

  • final["answer"] is overwritten after decoration, causing loss of citation markers

Fix:

  • Preserve the decorated answer in the final event

This is a small, scoped fix with no side effects.

Would really appreciate a review or any feedback. Thanks!

@yingfeng
yingfeng requested a review from xugangqiang April 9, 2026 02:57
@xugangqiang xugangqiang self-assigned this Apr 9, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

Appreciate your help on this.
Could you please re-produce this issue on your local environment (if possible) and then test with your fix to see if it really works?
If such testing evidence could be uploaded, I am more than happy to merge this change.

@edenfunf

edenfunf commented Apr 9, 2026

Copy link
Copy Markdown
Contributor Author

Appreciate your help on this. Could you please re-produce this issue on your local environment (if possible) and then test with your fix to see if it really works? If such testing evidence could be uploaded, I am more than happy to merge this change.

Reproduced and verified locally without a full RAGFlow stack.

Test script: test_pr13917.py — it isolates the final-event assembly logic
from async_ask() using minimal stubs that mirror the real decorate_answer() behaviour.

=== BUGGY (before fix) ===
answer : ''
doc_aggs : [{'doc_id': 'doc-A', 'title': 'Doc Alpha'}]
RESULT: answer is empty — citations lost on client side [BUG CONFIRMED]

=== FIXED (after fix) ===
answer : 'RAGFlow supports PDF and DOCX documents. ##0$$'
doc_aggs : [{'doc_id': 'doc-A', 'title': 'Doc Alpha'}]
RESULT: answer contains citation marker and doc_aggs is filtered [FIX VERIFIED]

All 3 assertions pass. The one-line removal is the correct fix.

@xugangqiang

Copy link
Copy Markdown
Contributor

Seems similar issue with #13835 . I am checking with the author of that PR and prefer to merge the two at the same time.

Thank you for your help on this.

@edenfunf

Copy link
Copy Markdown
Contributor Author

Seems similar issue with #13835 . I am checking with the author of that PR and prefer to merge the two at the same time.

Thank you for your help on this.

ok,Thank!

@xugangqiang

Copy link
Copy Markdown
Contributor

@edenfunf
May I ask for your help on this issue (#13835) as well?
Means add fix for that issue in your PR and do regression test to prove the fix works well and no regression issues.
Then please upload the testing evidence .
Thank you.

…path

Applies the same one-line fix to async_chat() that was already done for
async_ask() in the previous commit. Both functions call decorate_answer()
to build the final SSE payload (with citation markers and filtered refs),
then immediately overwrite final["answer"] with "", discarding that work.

Removing the blank assignment from async_chat() closes the same symptom
reported in infiniflow#13828.

Also adds a self-contained regression test that documents the old (buggy)
pattern and asserts the fixed invariant: the final event's answer field
must equal the decorated text produced by decorate_answer().
@coderabbitai

coderabbitai Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 875819ff-59d8-4c40-8ab1-55ced42606a9

📥 Commits

Reviewing files that changed from the base of the PR and between db32ca9 and 5f62c2b.

📒 Files selected for processing (1)
  • test/unit_test/api/db/services/test_dialog_service_final_answer.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/unit_test/api/db/services/test_dialog_service_final_answer.py

📝 Walkthrough

Walkthrough

Removed post-decoration clearing of answer in final streamed yields of async_chat, async_chat_solo, and async_ask, so final SSE events retain decorated answers; added regression tests that verify final-event payloads and reference handling for SSE streams.

Changes

Cohort / File(s) Summary
Dialog Service Fix
api/db/services/dialog_service.py
Removed final["answer"] = "" mutations from streamed final-yield paths in async_chat, async_chat_solo, and async_ask so the decorated answer is preserved in final SSE events.
Regression Tests
test/unit_test/api/db/services/test_dialog_service_final_answer.py
Added new test module with lightweight cv2 stub, async streaming/chat and retriever stubs, and _collect() helper; tests assert exactly one final=True SSE event, that final answer is non-empty and contains the model answer, and that reference fields follow expected population rules across delta vs final events.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I nibbled at streams through night and day,
Kept the final words from drifting away,
Decorated answers snug and bright,
One true final event — preserved just right,
A happy hop, the fix is in sight.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: restoring the decorated answer in the async_ask final SSE event, which directly corresponds to the primary code change of removing the final["answer"] = "" blank-override lines.
Description check ✅ Passed The description comprehensively addresses the template: it clearly explains the problem (answer overwrite after decoration), includes a Type of change (Bug Fix), provides code examples, root cause analysis, and regression test details.

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


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

@edenfunf

Copy link
Copy Markdown
Contributor Author

@xugangqiang Thanks for the suggestion! I've updated the PR to also cover the async_chat() path from #13828.

What's in the latest push:

  • Removed final["answer"] = "" in async_chat() (line ~774) — same one-liner as the async_ask() fix already in this PR, so both streaming paths are now consistent.
  • Added test/unit_test/api/db/services/test_dialog_service_final_answer.py with three regression tests covering the fixed invariant. All pass locally:
test_buggy_pattern_drops_answer                       PASSED
test_fixed_pattern_preserves_decorated_answer         PASSED
test_final_event_reference_matches_decorated_result   PASSED

3 passed in 0.04s

The tests document both the old behaviour (blank override discards decorated text) and the corrected behaviour (final event carries the decorate_answer() result with citation markers intact). ruff check is clean on all modified files.

Let me know if there's anything else you'd like adjusted.

@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: 2

🧹 Nitpick comments (1)
test/unit_test/api/db/services/test_dialog_service_final_answer.py (1)

37-67: Add lightweight logging hooks for the new async helper flow.

The newly added flow helpers/collector have no logging points, which makes event-order debugging harder when this test fails intermittently.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/unit_test/api/db/services/test_dialog_service_final_answer.py` around
lines 37 - 67, Add lightweight debug logging to the new async helper flow so
event-order can be traced: import and obtain a module logger, then add
logger.debug calls in _buggy_streaming_generator and _fixed_streaming_generator
before yielding each delta and before yielding the final event (reference the
functions _buggy_streaming_generator and _fixed_streaming_generator and include
the event dict or a brief description), and add logger.debug in _collect (and
its inner _run) to log when collection starts, each received event, and when
collection completes; keep logs non-blocking and low-verbosity (debug) so they
are safe for tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/unit_test/api/db/services/test_dialog_service_final_answer.py`:
- Around line 37-60: The test currently asserts behavior of local mock
generators (_buggy_streaming_generator/_fixed_streaming_generator) instead of
exercising the real service code; update the test to call the production entry
points (dialog_service.async_ask or dialog_service.async_chat) with network/IO
dependencies stubbed/mocked so the stream returned includes the actual final
event built by production logic (or alternatively import and test the shared
helper that assembles the final event used by decorate_answer). Ensure the test
replaces usage of the local generators with calls to async_ask/async_chat (or
the shared final-event assembly helper) and asserts the final event preserves
decorated_answer["answer"] rather than being blanked.
- Around line 101-104: The test currently only checks that final_events is
truthy but the intent is to assert there is exactly one final event; change the
assertion to explicitly assert len(final_events) == 1 (with a clear failure
message) before using final = final_events[0], referencing the variable
final_events in the test (and the subsequent assignment to final) so duplicates
will fail the test.

---

Nitpick comments:
In `@test/unit_test/api/db/services/test_dialog_service_final_answer.py`:
- Around line 37-67: Add lightweight debug logging to the new async helper flow
so event-order can be traced: import and obtain a module logger, then add
logger.debug calls in _buggy_streaming_generator and _fixed_streaming_generator
before yielding each delta and before yielding the final event (reference the
functions _buggy_streaming_generator and _fixed_streaming_generator and include
the event dict or a brief description), and add logger.debug in _collect (and
its inner _run) to log when collection starts, each received event, and when
collection completes; keep logs non-blocking and low-verbosity (debug) so they
are safe for tests.
🪄 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: 4b92aac2-4016-4abf-a9e8-76bba5a75515

📥 Commits

Reviewing files that changed from the base of the PR and between 87a87a7 and 93dd9c3.

📒 Files selected for processing (2)
  • api/db/services/dialog_service.py
  • test/unit_test/api/db/services/test_dialog_service_final_answer.py
💤 Files with no reviewable changes (1)
  • api/db/services/dialog_service.py

…egression

Replace the previous mock-generator tests with tests that call the actual
production functions (async_ask, async_chat) with their heavy dependencies
stubbed out. This means the suite will fail if final["answer"] = "" is
re-introduced in either function — unlike the previous version which only
tested local helper generators.

Three tests:
- test_async_ask_final_event_carries_decorated_answer: drives async_ask(),
  asserts the final event answer equals the decorated output from
  decorate_answer() (non-empty).
- test_async_ask_delta_events_carry_incremental_text_only: verifies delta
  events have empty reference, final event has populated chunk data.
- test_async_chat_final_event_carries_decorated_answer: drives async_chat()
  streaming path with a minimal dialog stub and the same assertion.

Also tightens assert final_events to len(...) == 1 per code review.
@coderabbitai

coderabbitai Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

Let me pull up the updated test file to verify the changes.


🏁 Script executed:

#!/bin/bash
fd "test_dialog_service_final_answer.py" --exec cat {}

Length of output: 11850


@edenfunf Thanks for the thorough update — both concerns are properly addressed.

Major (mock generators → real production paths): Confirmed. All three tests now drive dialog_service.async_ask() / dialog_service.async_chat() directly with monkeypatch standing in for LLMBundle, KnowledgebaseService, settings.retriever, etc. If final["answer"] = "" were re-introduced in either function the suite would catch it immediately. The regression guard is real now.

Minor (len == 1 assertion): Confirmed. Every final_events check now reads assert len(final_events) == 1, f"... {final_events}", which gives clear diagnostic output on failure.

One small optional observation: async_chat currently has one test while async_ask has two (including a delta-events check). A matching delta-events test for async_chat (asserting intermediate events carry reference == {}) would give symmetric coverage, but it is not required for this fix and can be deferred. The primary regression invariant is already guarded.

The tests look solid. The PR is in good shape. 🐇✨

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

@yingfeng @JinHai-CN @yuzhichang Please have a second eye check.

@yingfeng yingfeng added the ci Continue Integration label Apr 15, 2026
@yingfeng
yingfeng marked this pull request as draft April 15, 2026 05:04
@yingfeng
yingfeng marked this pull request as ready for review April 15, 2026 05:04
@xugangqiang

Copy link
Copy Markdown
Contributor

@edenfunf

Please fix CI error.

Looks like you are trying to connect to mysql in unit test which is not good and need to refactor (or use mock).

FAILED test/unit_test/api/db/services/test_dialog_service_final_answer.py::test_async_ask_final_event_carries_decorated_answer - peewee.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
FAILED test/unit_test/api/db/services/test_dialog_service_final_answer.py::test_async_ask_delta_events_carry_incremental_text_only - peewee.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
FAILED test/unit_test/api/db/services/test_dialog_service_final_answer.py::test_async_chat_final_event_carries_decorated_answer - ValueError: not enough values to unpack (expected 5, got 4)

Two CI failures:

1. async_ask tests hit peewee.OperationalError because kb_prompt() lazily
   imports DocumentService and calls get_by_ids(), which opens a MySQL
   connection. Fixed by stubbing dialog_service.kb_prompt in both async_ask
   test cases.

2. async_chat test raised ValueError (not enough values to unpack) because
   the get_models mock returned 4 values but async_chat expects the real
   signature: (kbs, embd_mdl, rerank_mdl, chat_mdl, tts_mdl) — 5 values.
   Fixed by including kbs as the first element.
@edenfunf

Copy link
Copy Markdown
Contributor Author

@xugangqiang Fixed — two root causes:

  1. async_ask MySQL error: kb_prompt() lazily imports DocumentService and calls get_by_ids(), which opens a peewee connection at runtime. Added monkeypatch.setattr(dialog_service, "kb_prompt", ...) to both async_ask tests so the DB is never touched.

  2. async_chat unpack error: My get_models mock was returning 4 values but async_chat unpacks it as kbs, embd_mdl, rerank_mdl, chat_mdl, tts_mdl (5 values). Fixed — mock now returns ([_KB], chat_mdl, None, chat_mdl, None).

Pushed as commit 5f62c2b. No other changes.

@codecov

codecov Bot commented Apr 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.66%. Comparing base (f08d132) to head (5f62c2b).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13917   +/-   ##
=======================================
  Coverage   96.66%   96.66%           
=======================================
  Files          10       10           
  Lines         690      690           
  Branches      108      108           
=======================================
  Hits          667      667           
  Misses          8        8           
  Partials       15       15           

☔ View full report in Codecov by Sentry.
📢 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.

@yingfeng
yingfeng merged commit 1f33ca1 into infiniflow:main Apr 15, 2026
1 check passed
JasleenKaurSethi pushed a commit to stackhpc/ragflow that referenced this pull request Apr 28, 2026
…nfiniflow#13917)

## What's the problem

Both `async_chat()` and `async_ask()` call `decorate_answer()` to build
the final SSE payload — it inserts citation markers (`##N$$`) into the
answer text and prunes `doc_aggs` to only the cited documents.
Immediately after, both functions overwrite `final["answer"]` with `""`:

```python
# async_chat(), line ~774  (issue infiniflow#13828)
final = decorate_answer(thought + full_answer)
final["final"] = True
final["audio_binary"] = None
final["answer"] = ""   # discards decorated text
yield final

# async_ask(), line ~1444  (same bug, different path)
final = decorate_answer(full_answer)
final["final"] = True
final["answer"] = ""   # discards decorated text
yield final
```

The client receives filtered references (built for a citation-decorated
answer it never sees) while displaying the raw, undecorated streaming
text. Citations can never match.

## Root cause

`final["answer"] = ""` was left over from an earlier design where
clients were meant to reconstruct the full answer purely from delta
events. Once `decorate_answer()` started placing citation markers, this
blank-out broke the contract: the final event is where the decorated
answer should land.

## Fix

Remove the two blank-override lines — one in `async_chat()`, one in
`async_ask()`:

```diff
-    final["answer"] = ""
```

`decorate_answer()` already sets `final["answer"]` to the correct
decorated string; there is nothing to override.

## Relation to infiniflow#13828

Issue infiniflow#13828 and PR infiniflow#13835 identify the bug in `async_chat()`. This PR
absorbs that fix and also corrects the identical pattern in
`async_ask()` (used by the `/retrieval` route in `chat_api.py`), which
PR infiniflow#13835 does not touch.

## Regression test

Added
`test/unit_test/api/db/services/test_dialog_service_final_answer.py`
with three tests:

| Test | Purpose |
|------|---------|
| `test_buggy_pattern_drops_answer` | Documents the old behaviour:
blank-override empties the final answer |
| `test_fixed_pattern_preserves_decorated_answer` | Core invariant:
final event carries the decorated text from `decorate_answer()` |
| `test_final_event_reference_matches_decorated_result` | Citation
markers in the answer must match the pruned `doc_aggs` in the same event
|

Local run result:

```
test_dialog_service_final_answer.py::test_buggy_pattern_drops_answer         PASSED
test_dialog_service_final_answer.py::test_fixed_pattern_preserves_decorated_answer PASSED
test_dialog_service_final_answer.py::test_final_event_reference_matches_decorated_result PASSED

3 passed in 0.04s
```

`ruff check` passes with no issues on all changed files.

---------

Co-authored-by: edenfunf <[email protected]>
Co-authored-by: Yingfeng <[email protected]>
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:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants