Skip to content

Fix: shared chatbot completion ignores knowledge base and empty response - #17092

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
euvre:fix/chatbot-shared-empty-response
Jul 21, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
euvre:fix/chatbot-shared-empty-response

Conversation

@euvre

@euvre euvre commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Summary

The Go /api/v1/chatbots/<dialog_id>/completions endpoint (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.ChatbotCompletion through ChatPipelineService.AsyncChat — the same RAG pipeline that serves the regular chat endpoints — mirroring the Python async_iframe_completion -> async_chat flow:

  • Retrieval now runs for shared chats; when nothing matches, the dialog's configured empty_response is returned (same behavior as in-app chat).
  • Session creation (no session_id) returns the prologue without an LLM call, matching the Python contract.
  • Pipeline deltas are accumulated into full-text SSE frames with final/start_to_think/end_to_think markers, keeping wire parity with the Python iframe envelope.
  • Each completed turn pair and its retrieval reference is persisted to api_4_conversation, so multi-turn shared sessions retain context.
  • The request body now accepts quote (defaults to false, as in bot_api.py), reasoning, internet (bool or 0/1), and doc_ids.

Testing: internal/service package tests pass, including new unit tests for the message-building and flag-normalization helpers; all TestChatbotCompletion_* handler tests pass.

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
@dosubot dosubot Bot added size:L This PR changes 100-499 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

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: 48905ac0-c35e-46ce-8dfa-c78b4cf02960

📥 Commits

Reviewing files that changed from the base of the PR and between c40c687 and 208ee0b.

📒 Files selected for processing (1)
  • internal/service/bot.go

📝 Walkthrough

Walkthrough

BotService routes chatbot completions through ChatPipelineService, streams reasoning and final SSE markers, accepts additional pipeline controls, and persists successful turns with retrieval references.

Changes

Chatbot pipeline completion

Layer / File(s) Summary
Pipeline and SSE contracts
internal/service/bot.go, internal/service/bot_completion.go
BotService initializes a chat pipeline, requests accept quote/reasoning/internet/document options, and SSE frames expose final and reasoning markers.
Session completion and streaming
internal/service/bot_completion.go
New sessions persist and return the prologue immediately; resumed sessions authorize access, invoke the pipeline, stream deltas and references, and persist successful turns.
Message shaping and persistence validation
internal/service/bot_completion.go, internal/service/bot_completion_history_test.go
History projection, turn parsing and persistence, flag/reference normalization, malformed-input handling, and concurrent same-session updates are implemented and tested.

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
Loading

Possibly related PRs

Suggested reviewers: qinling0210

Poem

I’m a rabbit with pipelines bright,
Streaming thoughts in frames of light.
Prologues hop, references gleam,
Turns persist beside the stream.
“Done!” I twitch my cotton tail—
Chatbot journeys now prevail!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: shared chatbot completion now uses the knowledge base pipeline and fixes empty-response behavior.
Description check ✅ Passed The description includes the required Summary section, background context, implementation details, and testing notes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

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 go mod tidy may solve the problem"


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
@wangq8
wangq8 self-requested a review July 20, 2026 06:19

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

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

17-23: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Drop 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1fdf167 and d0c5d4f.

📒 Files selected for processing (3)
  • internal/service/bot.go
  • internal/service/bot_completion.go
  • internal/service/bot_completion_history_test.go

Comment thread internal/service/bot_completion.go Resolved
Comment thread internal/service/bot_completion.go Resolved
Comment on lines +551 to +569
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,
},
)

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.

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

Suggested change
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 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.

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

  1. Correct architectural choice — ChatPipelineService.AsyncChat is 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.

  2. Prologue-on-new-session without LLM call — Mirrors Python async_iframe_completion exactly: the share page obtains a session_id first, then sends real questions. Avoids an unnecessary LLM round-trip on session creation.

  3. SSE wire parity — final and start_to_think/end_to_think markers match the Python iframe envelope so the front-end handles both shapes identically.

  4. Defensive normalizeBotBoolFlag — The reasoning/internet flags can arrive as true/false bools or 0/1 numbers depending on widget; the normalize function handles both cleanly.

  5. Error handling — Pipeline-level errors (**ERROR** prefix answer) prevent persistence, matching Python exception path. SSE sanitization preserved.

  6. Old helper removal — historyToMessages and historyFromMessages are deleted in favor of buildChatbotPipelineMessages / parseChatbotTurns which produce map[string]interface{} for the pipeline instead of typed modelModule.Message structs. Less coupling.

  7. 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 through buildChatbotPipelineMessages
  • persistChatbotTurn — not tested at all
  • referenceOrEmpty — 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 ⚠️ Adequate for helpers, missing for handler
Concurrency ⚠️ Potential race on session persistence
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 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.

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

  1. Core fix is sound — routing through the RAG pipeline correctly enables KB retrieval, empty_response fallback, citations, and system prompt for shared chatbot completions.

  2. Message filtering matches Python — buildChatbotPipelineMessages correctly drops system turns and leading assistant prologue, matching conversation_service.py:341-356.

  3. SSE frame parity — Final, StartToThink, EndToThink markers added to WriteChatbotFrame, matching the Python iframe envelope.

  4. Turn persistence is correct — persistChatbotTurn appends user+assistant pair with matching messageID plus retrieval reference, matching Python's structure_answer + append_message pattern.

  5. Flag normalization — normalizeBotBoolFlag handles bool/int/float inputs. Good.

  6. Error path — **ERROR** prefix check prevents persisting failed turns. Solid.

  7. stringFromMap nil-safety — already handles nil PromptConfig. 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 change

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

@wangq8
wangq8 requested a review from qinling0210 July 21, 2026 01:50
- 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
@euvre

euvre commented Jul 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. All points addressed in c40c687:

  1. Concurrency race in persistChatbotTurn — Fixed. BotService now carries a fixed-size striped lock set (persistLocks [64]sync.Mutex); persistChatbotTurn takes the per-session lock and re-reads the row inside the lock before appending, so two concurrent requests on the same session_id can no longer drop each other's exchange. Covered by TestPersistChatbotTurn_ConcurrentSameSession, which fails without the fix.
  2. CodeRabbit artifact in test comment — Removed; the header now describes only the runtime behavior.
  3. Shared messageID on the turn pair — Intentional; added a comment explaining the design (a Q&A exchange is addressed as a unit, mirroring the in-app chat pairing convention where the answer id derives from the question id).
  4. Inconsistent nil guards — s.pipeline now fails fast with CodeServerError exactly like s.llmService; the silent NewChatPipelineService() fallback is gone and the comment documents that the checks only guard a hand-rolled zero-value BotService.
  5. Test coverage gaps — Added TestParseChatbotTurns, TestReferenceOrEmpty, TestPersistChatbotTurn_AppendsPairAndReference, TestPersistChatbotTurn_NilReferenceDefaultsToEmpty, and the concurrent same-session test. Handler-level request→pipeline→SSE coverage still requires a mockable pipeline seam, which is a larger refactor; prefer tracking that separately.
  6. Mid-stream reference — Documented the assumption: the pipeline only populates Reference on the final result, and intermediate frames intentionally send an empty reference object for wire parity with python.

bash build.sh --test ./internal/service/ passes.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 70ff5fa and c40c687.

📒 Files selected for processing (3)
  • internal/service/bot.go
  • internal/service/bot_completion.go
  • internal/service/bot_completion_history_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/bot_completion.go

Comment thread internal/service/bot.go Resolved

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

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

euvre commented Jul 21, 2026

Copy link
Copy Markdown
Contributor Author

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 bash build.sh --test ./internal/service/ (passes) and a GOARCH=386 vet sweep (the only 32-bit complaints come from third-party deps like sonic/thrift that don't support 32-bit at all, unrelated to this change).

@wangq8
wangq8 merged commit 1c828da into infiniflow:main Jul 21, 2026
3 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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants