Repository navigation
Fix: shared chatbot completion ignores knowledge base and empty response - #17092
Conversation
The Go /api/v1/chatbots/<dialog_id>/completions endpoint bypassed retrieval entirely: it sent raw history to the LLM, so the dialog's configured empty_response (and retrieval, citations, system prompt) never applied in the shared/embedded chat UI. Route ChatbotCompletion through ChatPipelineService.AsyncChat — the same RAG pipeline used by the regular chat endpoints — mirroring the Python async_iframe_completion -> async_chat flow: - retrieve from the dialog's knowledge bases and return the configured empty_response when nothing matches - session creation returns the prologue without an LLM call - stream full-text frames with final/think markers, persist each completed turn pair and its reference to api_4_conversation - accept quote/reasoning/internet/doc_ids request fields
|
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)
📝 WalkthroughWalkthroughBotService routes chatbot completions through ChatPipelineService, streams reasoning and final SSE markers, accepts additional pipeline controls, and persists successful turns with retrieval references. ChangesChatbot pipeline completion
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant BotService
participant ChatPipelineService
participant api_4_conversation
Client->>BotService: Submit chatbot completion
BotService->>api_4_conversation: Load and authorize session
BotService->>ChatPipelineService: Send history, question, and flags
ChatPipelineService-->>BotService: Stream answer and reasoning markers
BotService-->>Client: Emit SSE frames and final reference
BotService->>api_4_conversation: Persist completed turn
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 OpenGrep (1.25.0)OpenGrep binary not available 🔧 golangci-lint (2.12.2)level=error msg="Running error: context loading failed: no go files to analyze: running 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/service/bot_completion_history_test.go (1)
17-23: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDrop the internal review-artifact reference from the comment.
"Locks in review Finding 8" ties this comment to an internal review-tracking ID rather than describing current runtime behavior.
As per coding guidelines, "keep package and documentation comments aligned with the current runtime path rather than migration history" and "Remove dead tests, commented-out code, stale documentation, and 'move later' notes."
✏️ Proposed fix
-// Tests for the message-building / flag-normalisation helpers used -// by BotService.ChatbotCompletion. Locks in review Finding 8 — a -// resumed session_id must carry prior turns (assistant prologue + -// earlier user/assistant exchanges) into the next pipeline call so -// multi-turn chatbot clients retain context, and the filtering must -// match python async_iframe_completion (drop system turns and the -// leading assistant prologue). +// Tests for the message-building / flag-normalisation helpers used +// by BotService.ChatbotCompletion. A resumed session_id must carry +// prior turns (assistant prologue + earlier user/assistant +// exchanges) into the next pipeline call so multi-turn chatbot +// clients retain context, and the filtering must match python +// async_iframe_completion (drop system turns and the leading +// assistant prologue).🤖 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/bot_completion_history_test.go` around lines 17 - 23, Update the comment above the chatbot completion tests to remove the “review Finding 8” reference, while retaining only the description of resumed-session context propagation and message filtering behavior.Source: Coding guidelines
🤖 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 `@internal/service/bot_completion.go`:
- Line 370: Make the session read-modify-write flow in ChatbotCompletion and
persistChatbotTurn concurrency-safe for the same session_id. Do not save the
stale session fetched before the streaming pipeline; re-read the latest
conversation immediately before applying the turn, and use an atomic update or
optimistic-lock/version check so concurrent writes cannot silently overwrite
each other. Preserve both requests’ Message and Reference history, and ensure
the 551-594 persistence path uses the same protection.
- Around line 378-387: Update the guard in the completion path to validate the
dependency actually used by the pipeline: check s.pipeline rather than
s.llmService for an unwired service. Preserve the existing server-error response
and the separate dialog.LLMID validation.
- Around line 551-569: Update persistChatbotTurn so the user and assistant turn
records receive distinct message IDs. Preserve the existing messageID for the
user turn, and generate or use a separate assistant-turn identifier before
appending the assistant map; keep the rest of the persisted turn fields
unchanged.
---
Nitpick comments:
In `@internal/service/bot_completion_history_test.go`:
- Around line 17-23: Update the comment above the chatbot completion tests to
remove the “review Finding 8” reference, while retaining only the description of
resumed-session context propagation and message filtering behavior.
🪄 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: 9f3d0992-da90-4175-b3a8-91ee8214b0e8
📒 Files selected for processing (3)
internal/service/bot.gointernal/service/bot_completion.gointernal/service/bot_completion_history_test.go
| func (s *BotService) persistChatbotTurn( | ||
| session *entity.API4Conversation, question, answer, messageID string, reference map[string]any, | ||
| ) error { | ||
| now := time.Now().Unix() | ||
| turns := parseChatbotTurns(session.Message) | ||
| turns = append(turns, | ||
| map[string]any{ | ||
| "role": "user", | ||
| "content": question, | ||
| "id": messageID, | ||
| "created_at": now, | ||
| }, | ||
| map[string]any{ | ||
| "role": "assistant", | ||
| "content": answer, | ||
| "id": messageID, | ||
| "created_at": now, | ||
| }, | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
User and assistant turns share the same messageID.
buildChatbotPipelineMessages tags the new user turn with messageID (line 516), and persistChatbotTurn then persists BOTH the user turn (558-562) and the assistant turn (563-568) under that same id. Two different conversation turns ending up with identical ids can break any future per-message lookup (edit/regenerate/citation-by-message-id).
🔧 Proposed fix
+ answerID := utility.GenerateUUID()
turns = append(turns,
map[string]any{
"role": "user",
"content": question,
"id": messageID,
"created_at": now,
},
map[string]any{
"role": "assistant",
"content": answer,
- "id": messageID,
+ "id": answerID,
"created_at": now,
},
)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (s *BotService) persistChatbotTurn( | |
| session *entity.API4Conversation, question, answer, messageID string, reference map[string]any, | |
| ) error { | |
| now := time.Now().Unix() | |
| turns := parseChatbotTurns(session.Message) | |
| turns = append(turns, | |
| map[string]any{ | |
| "role": "user", | |
| "content": question, | |
| "id": messageID, | |
| "created_at": now, | |
| }, | |
| map[string]any{ | |
| "role": "assistant", | |
| "content": answer, | |
| "id": messageID, | |
| "created_at": now, | |
| }, | |
| ) | |
| func (s *BotService) persistChatbotTurn( | |
| session *entity.API4Conversation, question, answer, messageID string, reference map[string]any, | |
| ) error { | |
| now := time.Now().Unix() | |
| turns := parseChatbotTurns(session.Message) | |
| answerID := utility.GenerateUUID() | |
| turns = append(turns, | |
| map[string]any{ | |
| "role": "user", | |
| "content": question, | |
| "id": messageID, | |
| "created_at": now, | |
| }, | |
| map[string]any{ | |
| "role": "assistant", | |
| "content": answer, | |
| "id": answerID, | |
| "created_at": now, | |
| }, | |
| ) |
🤖 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/bot_completion.go` around lines 551 - 569, Update
persistChatbotTurn so the user and assistant turn records receive distinct
message IDs. Preserve the existing messageID for the user turn, and generate or
use a separate assistant-turn identifier before appending the assistant map;
keep the rest of the persisted turn fields unchanged.
wangq8
left a comment
There was a problem hiding this comment.
PR Review: #17092 — Fix shared chatbot completion ignoring KB and empty response
Author: @euvre
Files: internal/service/bot.go, internal/service/bot_completion.go, internal/service/bot_completion_history_test.go
Net: +343 / −232
Overall Assessment
This is a solid architectural fix. The core insight is correct: the Go /api/v1/chatbots/<dialog_id>/completions endpoint was short-circuiting to a direct LLM call, bypassing the RAG pipeline entirely. Routing through ChatPipelineService.AsyncChat brings shared/embedded chat into parity with the in-app chat experience and mirrors the Python async_iframe_completion → async_chat flow.
The implementation is clean — SSE frame parity (final, start_to_think, end_to_think markers), session lifecycle (prologue-only new sessions), request field expansion (quote, reasoning, internet, doc_ids), and persistence of turn pairs + references are all correctly handled.
👍 Whats Done Well
-
Correct architectural choice —
ChatPipelineService.AsyncChatis the shared RAG pipeline; routing through it ensures KB retrieval, citations, empty-response fallback, system prompt, and tool calls all behave identically to the in-app chat endpoints. -
Prologue-on-new-session without LLM call — Mirrors Python
async_iframe_completionexactly: the share page obtains asession_idfirst, then sends real questions. Avoids an unnecessary LLM round-trip on session creation. -
SSE wire parity —
finalandstart_to_think/end_to_thinkmarkers match the Python iframe envelope so the front-end handles both shapes identically. -
Defensive
normalizeBotBoolFlag— Thereasoning/internetflags can arrive astrue/falsebools or0/1numbers depending on widget; the normalize function handles both cleanly. -
Error handling — Pipeline-level errors (
**ERROR**prefix answer) prevent persistence, matching Python exception path. SSE sanitization preserved. -
Old helper removal —
historyToMessagesandhistoryFromMessagesare deleted in favor ofbuildChatbotPipelineMessages/parseChatbotTurnswhich producemap[string]interface{}for the pipeline instead of typedmodelModule.Messagestructs. Less coupling. -
Tests rewritten for new interface — Tests now cover message filtering (drops leading assistant + system turns), malformed input resilience, and flag normalization.
🔍 Issues Raised
1. Concurrency race in persistChatbotTurn (Medium)
File: internal/service/bot_completion.go ~line 551
func (s *BotService) persistChatbotTurn(session ..., question, answer, messageID string, reference map[string]any) error {
turns := parseChatbotTurns(session.Message)
turns = append(turns, ...)
rawMsg, _ := json.Marshal(turns)
session.Message = rawMsg
...
return s.api4ConversationDAO.Update(session)
}The read–modify–write on session.Message is not atomic. Two concurrent SSE requests for the same session_id can both read the same stale base, append their own turns, and the last Update call wins — silently dropping the other turn. For v1 this may be acceptable (the comment acknowledges "at most the latest exchange" may be lost), but it should be tracked.
Suggestion: Consider adding a version/row-lock column on api_4_conversation, or re-reading the session immediately before Update with an optimistic WHERE clause (WHERE message = <old> AND id = <id>). A simpler approach: set DeleteAfterRun on the goroutine or use a per-session mutex map.
2. CodeRabbit artifact in test comment (Low)
File: internal/service/bot_completion_history_test.go line ~17
// Locks in review Finding 8
This references an internal CodeRabbit review tracking ID. It is meaningless to future readers and should be removed from committed code.
Suggestion: Reword the comment to describe only the runtime behavior, e.g.:
// Tests for the message-building / flag-normalization helpers used by
// BotService.ChatbotCompletion. A resumed session_id must carry prior
// turns into the next pipeline call so multi-turn chatbot clients retain
// context, and the filtering must match Python async_iframe_completion
// (drop system turns and the leading assistant prologue).3. User and assistant turn share the same messageID (Low)
File: internal/service/bot_completion.go ~line 556
turns = append(turns,
map[string]any{
"role": "user", "content": question, "id": messageID, ...
},
map[string]any{
"role": "assistant", "content": answer, "id": messageID, ...
},
)Both turns in the pair get the same messageID. If this is intentional to pair them as a Q&A unit, a comment explaining the design would help future readers. If they need to be independently addressable (e.g., for message editing, deletion, or citation linking), they should get distinct IDs.
4. Inconsistent defensive guards on s.pipeline vs s.llmService (Low)
File: internal/service/bot_completion.go ~line 378
pipeline := s.pipeline
if pipeline == nil {
pipeline = NewChatPipelineService()
}NewBotService always creates a NewChatPipelineService(), so this nil check is only relevant in test bootstrap. Meanwhile, s.llmService has no such fallback and returns CodeServerError when nil.
Suggestion: Either remove the defensive fallback here (add a nil-LLM-style guard instead) or document that this is intentionally permissive for testing. Consistency matters.
5. Test coverage gaps (Medium)
The old tests covered historyToMessages, historyFromMessages, malformed input, empty-field skipping, and round-trip fidelity. The new tests cover buildChatbotPipelineMessages and normalizeBotBoolFlag but miss:
parseChatbotTurns— no direct test; only exercised throughbuildChatbotPipelineMessagespersistChatbotTurn— not tested at allreferenceOrEmpty— trivial but uncovered
The largest gap is the lack of integration-level handler tests for ChatbotCompletion itself (with a mocked pipeline or DAO). The handler is the entry point for all this logic and has no test coverage for the full request → pipeline → SSE → persistence flow.
6. ChatbotSSEFrame.Reference may be inconsistent in streaming frames (Minor)
File: internal/service/bot_completion.go ~line 492
During accumulation, intermediate frames carry reference: {} while only the final frame carries the actual retrieval reference. The Python wire format sends an empty reference for intermediate frames, so this matches. However, if res.Reference was non-nil on a non-final result (line 487–489), finalRef is updated but the SSE frame still sends map[string]any{}.
Suggestion: Consider whether mid-stream reference updates should be forwarded. Currently this is a no-op in practice (pipeline only populates reference on final results), but documenting this assumption helps.
✅ Summary
| Category | Verdict |
|---|---|
| Fix correctness | ✅ Fixes the described regression properly |
| Architecture | ✅ Correct; matches Python flow |
| Security | ✅ No new surface; existing sanitization preserved |
| Test coverage | |
| Concurrency | |
| Code quality | ✅ Clean, well-commented, readable |
Verdict: Change is sound and should be merged after addressing the CodeRabbit artifact comment and ideally adding handler-level test coverage. The persist race is a known trade-off for v1 and can be tracked separately.
…pty-response # Conflicts: # internal/service/bot_completion.go
wangq8
left a comment
There was a problem hiding this comment.
PR Review: #17092 — Fix: shared chatbot completion ignores KB and empty response
Summary
This PR fixes a significant bug where /api/v1/chatbots/<dialog_id>/completions bypassed knowledge-base retrieval entirely, routing raw conversation history straight to the LLM. The fix routes BotService.ChatbotCompletion through ChatPipelineService.AsyncChat, mirroring Python's async_iframe_completion → async_chat flow. Overall the architectural direction is correct and the code is well-commented.
✅ Positives
-
Core fix is sound — routing through the RAG pipeline correctly enables KB retrieval, empty_response fallback, citations, and system prompt for shared chatbot completions.
-
Message filtering matches Python —
buildChatbotPipelineMessagescorrectly drops system turns and leading assistant prologue, matchingconversation_service.py:341-356. -
SSE frame parity —
Final,StartToThink,EndToThinkmarkers added toWriteChatbotFrame, matching the Python iframe envelope. -
Turn persistence is correct —
persistChatbotTurnappends user+assistant pair with matchingmessageIDplus retrieval reference, matching Python'sstructure_answer+append_messagepattern. -
Flag normalization —
normalizeBotBoolFlaghandles bool/int/float inputs. Good. -
Error path —
**ERROR**prefix check prevents persisting failed turns. Solid. -
stringFromMapnil-safety — already handles nilPromptConfig. No new nil risk.
🔴 Must-Fix: Reasoning text is silently dropped
The Go pipeline (chat_pipeline.go:1098-1108) emits reasoning text in the Reasoning field (not Answer):
if inThink {
out <- AsyncChatResult{
Reasoning: text, // ← not Answer
Answer: "", // defaults to ""
}
}But the PR code only accumulates res.Answer:
fullAnswer += res.Answer // "" → no changeThe StartToThink/EndToThink markers are forwarded correctly, but the reasoning text between them is never sent to the front-end. The front-end receives bracketing markers with no reasoning content.
Fix: The delta loop should handle res.Reasoning and accumulate it alongside fullAnswer (perhaps in a separate accumulator), or forward reasoning frames as SSE frames with the reasoning content in the data payload.
🟡 Should-Fix: No pipeline integration tests
The PR description states "all TestChatbotCompletion_* handler tests pass", but no such tests exist in the repository. The only tests cover message-building helpers (buildChatbotPipelineMessages, normalizeBotBoolFlag). The full pipeline path — KB retrieval, empty_response fallback, citation display through WriteChatbotFrame — has zero test coverage.
Suggestion: At minimum, add a test that verifies the SSE frame sequence for the three key paths:
- Successful KB retrieval → decorated answer with
final:true - Empty retrieval → empty_response text returned
- Pipeline error →
**ERROR**prefix not persisted
🟡 Worth Noting
Test removal: TestHistoryFromMessages_PreservesOrder, TestHistoryRoundTrip_PreservesPriorTurns, and TestHistoryToMessages_SkipsEmptyFields are removed. The filtering is now in buildChatbotPipelineMessages (tested) and parseChatbotTurns passes ALL turns through. This is architecturally valid but reduces test surface. Consider adding a test for persistChatbotTurn since it manages the critical write-back.
Pipeline initialization in constructor: NewBotService now creates a ChatPipelineService. If that service has DB or external dependencies in its init path, this could slow test startup or fail in lightweight test environments (the nil-guard in ChatbotCompletion partially mitigates this).
Final frame with empty Answer: When res.Answer == "" on final, accumulated deltas stand. This is correct for the empty_response path, but relies on the pipeline contract that a non-empty-response final frame always carries a non-empty decorated Answer. An explicit assertion or comment documenting this invariant would help.
Verdict
The fix is correct and well-structured. The reasoning-text-dropping issue is a functional regression that should be fixed before merge. The test coverage gap is significant for a 257-line change in a production code path, but not a blocker if manually verified.
- Serialise persistChatbotTurn's read-modify-write per session with a striped lock and re-read the row inside the lock, so two concurrent requests on the same session_id no longer drop each other's exchange - Guard a nil chat pipeline the same way as the nil LLM service instead of silently constructing one - Document the shared messageID on the user/assistant pair, the empty-reference assumption on intermediate SSE frames - Drop the internal review-tracking reference from the test header - Add tests for parseChatbotTurns, referenceOrEmpty and persistChatbotTurn, including the concurrent same-session case
|
Thanks for the thorough review. All points addressed in c40c687:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@internal/service/bot.go`:
- Around line 219-225: Update persistLock to compute the modulo using the uint32
hash value before converting the result to int for indexing s.persistLocks.
Preserve the existing FNV hash and lock-selection behavior while ensuring the
index cannot become negative on 32-bit architectures.
🪄 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: 6e29647e-3f87-4709-bfb1-15610df5bf04
📒 Files selected for processing (3)
internal/service/bot.gointernal/service/bot_completion.gointernal/service/bot_completion_history_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/service/bot_completion.go
qinling0210
left a comment
There was a problem hiding this comment.
LGTM.
Please address the critical issue coderabbitai commented.
Converting the FNV-1a sum to int before the modulo can go negative on 32-bit architectures, and a negative array index panics at runtime. Apply the modulo on the unsigned hash instead.
|
Good catch — fixed in 208ee0b. The modulo now runs on the unsigned hash: return &s.persistLocks[h.Sum32()%uint32(len(s.persistLocks))]so the index is guaranteed non-negative on 32-bit architectures as well. Verified with |
Summary
The Go
/api/v1/chatbots/<dialog_id>/completionsendpoint (used by the shared/embedded chat UI) bypassed knowledge-base retrieval entirely: it sent the raw conversation history straight to the LLM. As a result, none of the retrieval-related dialog configuration took effect in shared chats — most visibly, the configured empty response was never returned when the knowledge base had no matching content, and the LLM answered freely instead. Retrieval, citations, and the system prompt were silently skipped as well.This PR routes
BotService.ChatbotCompletionthroughChatPipelineService.AsyncChat— the same RAG pipeline that serves the regular chat endpoints — mirroring the Pythonasync_iframe_completion -> async_chatflow:empty_responseis returned (same behavior as in-app chat).session_id) returns the prologue without an LLM call, matching the Python contract.final/start_to_think/end_to_thinkmarkers, keeping wire parity with the Python iframe envelope.api_4_conversation, so multi-turn shared sessions retain context.quote(defaults to false, as inbot_api.py),reasoning,internet(bool or 0/1), anddoc_ids.Testing:
internal/servicepackage tests pass, including new unit tests for the message-building and flag-normalization helpers; allTestChatbotCompletion_*handler tests pass.