Repository navigation
fix(dialog): restore decorated answer in async_ask final SSE event - #13917
Conversation
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.
|
Hi maintainers, This PR fixes a bug in async_ask where the final SSE event drops the decorated answer. Root cause:
Fix:
This is a small, scoped fix with no side effects. Would really appreciate a review or any feedback. Thanks! |
|
Appreciate your help on this. |
Reproduced and verified locally without a full RAGFlow stack. Test script: test_pr13917.py — it isolates the final-event assembly logic === BUGGY (before fix) === === FIXED (after fix) === All 3 assertions pass. The one-line removal is the correct fix. |
|
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! |
…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().
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughRemoved post-decoration clearing of Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
|
@xugangqiang Thanks for the suggestion! I've updated the PR to also cover the What's in the latest push:
The tests document both the old behaviour (blank override discards decorated text) and the corrected behaviour (final event carries the Let me know if there's anything else you'd like adjusted. |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
api/db/services/dialog_service.pytest/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.
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainLet me pull up the updated test file to verify the changes. 🏁 Script executed: Length of output: 11850
Major (mock generators → real production paths): Confirmed. All three tests now drive Minor ( One small optional observation: The tests look solid. The PR is in good shape. 🐇✨ |
|
LGTM @yingfeng @JinHai-CN @yuzhichang Please have a second eye check. |
|
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)") |
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.
|
@xugangqiang Fixed — two root causes:
Pushed as commit |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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]>
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.
What's the problem
Both
async_chat()andasync_ask()calldecorate_answer()to build the final SSE payload — it inserts citation markers (##N$$) into the answer text and prunesdoc_aggsto only the cited documents. Immediately after, both functions overwritefinal["answer"]with"":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. Oncedecorate_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 inasync_ask():- final["answer"] = ""decorate_answer()already setsfinal["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 inasync_ask()(used by the/retrievalroute inchat_api.py), which PR #13835 does not touch.Regression test
Added
test/unit_test/api/db/services/test_dialog_service_final_answer.pywith three tests:test_buggy_pattern_drops_answertest_fixed_pattern_preserves_decorated_answerdecorate_answer()test_final_event_reference_matches_decorated_resultdoc_aggsin the same eventLocal run result:
ruff checkpasses with no issues on all changed files.