Skip to content

fix[go]: stop leaking [DONE] sentinel into streamed chat answers - #17084

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
euvre:fix/go-chat-stream-done-sentinel
Jul 20, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
euvre:fix/go-chat-stream-done-sentinel

Conversation

@euvre

@euvre euvre commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Summary

In Go mode, model drivers emit the OpenAI-style [DONE] marker as their final sender call (mirroring the Python convention, where consumers break on it). The channel adapter chatStreamWithContext (internal/service/model_chat.go) forwarded every delta verbatim into the channel, including this terminal sentinel.

As a result, channel consumers accumulated [DONE] as answer text:

  • AskService (search AI summary) appended it to the final answer, so the rendered AI summary ended with a stray [DONE].
  • The mindmap handler (internal/handler/mindmap.go) had the same exposure.

Fix: treat [DONE] as end-of-stream in the adapter — abort the driver loop via a sentinel error and never forward the marker into the channel. Drivers populate ToolCallsResult/UsageResult before sending [DONE], so nothing is lost.

Adds internal/service/model_chat_test.go covering that the sentinel is stripped while content deltas pass through intact. bash build.sh --test ./internal/service/... passes.

Model drivers emit the OpenAI-style [DONE] marker as their final sender
call. The channel adapter chatStreamWithContext forwarded it verbatim,
so AskService (search AI summary) and the mindmap handler accumulated
it as answer text, leaving a trailing [DONE] in the rendered summary.

Treat the sentinel as end-of-stream in the adapter: abort the driver
loop, never forward it into the channel.
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 20, 2026
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The chat streaming service now treats [DONE] as a terminal sentinel, stops processing without warning, and includes a test confirming that the sentinel is excluded from streamed message output.

Changes

Chat stream completion

Layer / File(s) Summary
Sentinel detection and stream validation
internal/service/model_chat.go, internal/service/model_chat_test.go
The stream callback detects [DONE], terminates cleanly through a dedicated error, and tests that emitted message deltas concatenate without the sentinel.

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

Possibly related PRs

Poem

A bunny watched the stream go by,
With “Hello world” beneath the sky.
“[DONE]” came hopping to the end,
Then vanished like a whiskered friend.
Clean streams bring carrots—what a trend!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: preventing the [DONE] sentinel from leaking into streamed chat answers.
Description check ✅ Passed The Summary section covers the problem, the fix, affected consumers, and the added test, matching the template well.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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.

@euvre euvre added the ci Continue Integration label Jul 20, 2026

@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.

🧹 Nitpick comments (1)
internal/service/model_chat_test.go (1)

35-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simulate driver trailing logic to catch early exits.

If you adjust the main implementation to return nil instead of errStreamDone, consider enhancing this mock driver to verify that trailing logic runs successfully. You can add a boolean flag (e.g., UsagePopulated bool) that is set to true after the loop finishes, and assert it in the test to guarantee that the driver wasn't prematurely aborted.

♻️ Proposed refactor for the mock driver
 type doneEmittingDriver struct {
 	*modelModule.DummyModel
 	deltas []string
+	usagePopulated bool
 }
 
 func (d *doneEmittingDriver) ChatStreamlyWithSender(modelName string, messages []modelModule.Message, apiConfig *modelModule.APIConfig, modelConfig *modelModule.ChatConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
 	for _, delta := range d.deltas {
 		if err := sender(&delta, nil); err != nil {
 			return err
 		}
 	}
 	done := streamDoneSentinel
-	return sender(&done, nil)
+	if err := sender(&done, nil); err != nil {
+		return err
+	}
+	d.usagePopulated = true
+	return nil
 }
🤖 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 `@internal/service/model_chat_test.go` around lines 35 - 43, Enhance the mock
driver method doneEmittingDriver.ChatStreamlyWithSender by adding a
usage-population flag and setting it only after all deltas have been sent
successfully, before emitting the completion sentinel. Update the related test
to assert this flag, ensuring trailing driver logic executes and is not
prematurely terminated.
🤖 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.

Nitpick comments:
In `@internal/service/model_chat_test.go`:
- Around line 35-43: Enhance the mock driver method
doneEmittingDriver.ChatStreamlyWithSender by adding a usage-population flag and
setting it only after all deltas have been sent successfully, before emitting
the completion sentinel. Update the related test to assert this flag, ensuring
trailing driver logic executes and is not prematurely terminated.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d5f000d6-f50d-4a39-80ff-da51d1c409e5

📥 Commits

Reviewing files that changed from the base of the PR and between c396ae9 and 7e82bb7.

📒 Files selected for processing (2)
  • internal/service/model_chat.go
  • internal/service/model_chat_test.go

@wangq8
wangq8 self-requested a review July 20, 2026 05:05

@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: PR #17084

Change: Introduces an errStreamDone sentinel error in chatStreamWithContext to abort the driver loop when the [DONE] marker is encountered, preventing it from leaking into channel consumers (AskService, mindmap handler). Adds model_chat_test.go.

Assessment:

  • Correctness: The approach is sound — [DONE] is a transport-level signal, not answer text. Using a sentinel error to cleanly abort the loop is idiomatic Go.

  • Edge cases: The sentinel check with errors.Is(err, errStreamDone) is correct since errStreamDone is a package-level errors.New value. The existing context.Canceled / DeadlineExceeded path is preserved alongside it.

  • Data loss: The comment correctly notes that drivers populate ToolCallsResult/UsageResult before emitting [DONE], so no data is lost.

  • Tests: The test file uses a doneEmittingDriver mock that faithfully replicates the real driver behavior. It asserts "Hello world" output without the sentinel. Good coverage of the core scenario. It would be nice to also test an empty-delta stream (only [DONE]), but not a blocker.

  • Nitpick (non-blocking): In doneEmittingDriver.ChatStreamlyWithSender, if sender returns an error mid-stream (including errStreamDone from our new check), the remaining deltas are skipped. That's fine — just noting the behavior in case any driver relies on all deltas being delivered before [DONE]. Given the comment that usage is populated before [DONE], this seems safe.

Verdict: LGTM — well-structured fix with good test coverage.

@wangq8
wangq8 merged commit 2e06c1d into infiniflow:main Jul 20, 2026
9 checks passed
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants