Skip to content

Fix: streaming response reference mismatch with answer - #13835

Closed
Lntanohuang wants to merge 1 commit into
infiniflow:mainfrom
Lntanohuang:fix/stream-reference-mismatch
Closed

Lntanohuang wants to merge 1 commit into
infiniflow:mainfrom
Lntanohuang:fix/stream-reference-mismatch

Conversation

@Lntanohuang

@Lntanohuang Lntanohuang commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #13828 — streaming response references are mismatched with the answer, while chat history references are correct.

Root Cause

In async_chat() (api/db/services/dialog_service.py), the streaming code path:

  1. Sends intermediate SSE events with reference: {} (empty) — expected, since references are computed after the full answer is available.
  2. After streaming completes, calls decorate_answer() which:
    • Inserts citation markers (##N$$) into the answer text
    • Filters doc_aggs based on which chunks were actually cited
    • Returns the decorated answer with matching references
  3. Bug: The final SSE event then blanks the answer (final["answer"] = ""), discarding the citation-processed text while keeping the citation-filtered references.

This means the client accumulates raw answer text (no citation markers) from delta events, but receives references filtered based on citation analysis it never sees — causing the mismatch reported in the issue.

Chat history is unaffected because structure_answer() correctly persists conv.reference[-1] from the final event's reference data.

Fix

Remove final["answer"] = "" so the final SSE event includes the full decorated answer (with citation markers) alongside its matching references. This is consistent with the non-streaming code path behavior.

Behavior Change

Previously, the final streaming SSE event had answer: "". After this fix, it contains the complete citation-processed answer. Clients that accumulate delta text should use the final event's answer as the authoritative text (replacing accumulated deltas), which is the same pattern used in the non-streaming response.

Test plan

  • Call POST /api/v1/chats/{chat_id}/completions with stream=true and citation enabled
  • Verify the final SSE event contains both the decorated answer and matching references
  • Verify the references in the streaming response match those in the chat history
  • Verify non-streaming (stream=false) behavior is unchanged

🤖 Generated with Claude Code


Update: Also fixes the same issue in async_ask(). The infinity_conn.py escaping fix has been moved to a separate PR (#14053) to keep this one focused on the streaming reference mismatch.

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. labels Mar 28, 2026
edenfunf pushed a commit to edenfunf/ragflow that referenced this pull request Apr 3, 2026
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.
@xugangqiang xugangqiang self-assigned this Apr 9, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

Appreciate your help on this.

Could you please test on your local environment and then verify your fix?

If testing evidence could be uploaded, that will be of great help to fix/close this bug.

@dosubot dosubot Bot mentioned this pull request Apr 10, 2026
4 tasks done
Remove `final["answer"] = ""` in both async_chat() and async_ask()
so the final streaming event includes the citation-decorated answer
alongside matching references, fixing the mismatch reported in infiniflow#13828.
@Lntanohuang
Lntanohuang force-pushed the fix/stream-reference-mismatch branch from ca84447 to 4cf7aa8 Compare April 10, 2026 20:49
@coderabbitai

coderabbitai Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

A bug fix that removes explicit empty string assignments (final["answer"] = "") from two streaming response paths in the dialog service, allowing properly decorated answers with references to be returned instead of being overridden.

Changes

Cohort / File(s) Summary
Streaming Response References Fix
api/db/services/dialog_service.py
Removed two lines that were overriding the answer field with an empty string after the decorate_answer() function had already populated it with the proper answer and reference information. Fixes incorrect references in streamed chat completions.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 A reference went missing, oh what a sight,
But a simple removal set everything right!
Two lines that were blanking what should've been shown,
Now citations shine bright as the seeds I have sown. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: fixing a streaming response reference mismatch issue.
Linked Issues check ✅ Passed The code changes directly address the requirements in issue #13828 by removing the problematic final["answer"] = "" assignments that caused the reference mismatch.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the streaming response reference mismatch; no extraneous modifications are present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed The pull request description is well-structured and complete, following the expected format with problem statement, root cause analysis, fix explanation, behavior changes, and test plan.

✏️ 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.

@Lntanohuang

Copy link
Copy Markdown
Contributor Author

Thanks for the review! I've updated this PR with the following changes:

  1. Extended the fix to async_ask() — it had the identical final["answer"] = "" issue, so now both async_chat() and async_ask() streaming paths are covered.

  2. Separated the infinity_conn.py fix into its own PR — the single-quote escaping fix was unrelated to the streaming reference mismatch, so I've split it out to keep this PR focused. See fix(infinity): escape single quotes in fulltext filter to prevent TokenError #14053 for that fix.

@edenfunf I noticed your PR #13917 addresses the same async_ask() issue. I've incorporated that fix here so both code paths are covered together. Feel free to close #13917 if you agree, or let me know if you'd prefer otherwise.

I'll follow up with local testing evidence shortly.

@Lntanohuang

Copy link
Copy Markdown
Contributor Author

I'll have the local testing evidence uploaded within the next day. Stay tuned!

@xugangqiang

Copy link
Copy Markdown
Contributor

@Lntanohuang May I know if the testing goes well?

yingfeng added a commit that referenced this pull request Apr 15, 2026
…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 #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 #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.

---------

Co-authored-by: edenfunf <[email protected]>
Co-authored-by: Yingfeng <[email protected]>
@xugangqiang

Copy link
Copy Markdown
Contributor

#13917 has been merged which contains the fix as well. Thus close this one.

@Lntanohuang

Copy link
Copy Markdown
Contributor Author

Sorry for the delay — I've been swamped with work and feeling under the weather these past few days, so I couldn't follow up in time.

Glad to see this got resolved through #13917. Thanks @edenfunf for picking it up and @xugangqiang for coordinating!

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: /api/v1/chats/{chat_id}/completions stream returns wrong references, but chat history is correct

2 participants