Skip to content

feat(go-api): add RAG retrieval to chat completions - #15739

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
oktofeesh1:codex/go-chat-rag-completion
Jun 10, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
oktofeesh1:codex/go-chat-rag-completion

Conversation

@oktofeesh1

@oktofeesh1 oktofeesh1 commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add knowledge-base retrieval support to Go chat completions.

What changed

  • Routes KB-backed chat sessions through the Go retrieval service instead of falling back to solo chat.
  • Resolves embedding and rerank models, validates accessible knowledge bases, and preserves tenant-aware retrieval.
  • Rejects mixed embedding models across selected knowledge bases before retrieval to avoid incompatible vector dimensions.
  • Threads the HTTP request context into streaming retrieval so cancelled requests can stop downstream retrieval work.
  • Applies metadata filters and message-level doc_ids before retrieval.
  • Expands parent/child chunks before building references and prompt context.
  • Injects retrieved knowledge through a copied dialog prompt config so the caller's original dialog is not mutated.
  • Honors configured empty responses when no chunks are found.
  • Names the metadata no-match sentinel and reuses it across retrieval/handler paths.
  • Adds a defensive content cast while appending streamed answers.
  • Adds focused unit coverage for retrieval, metadata filtering, authorization, multimodal messages, references, empty-response behavior, prompt immutability, and mixed embedding models.

Why

  • Go chat completions had a placeholder RAG path, so KB-backed chats did not actually retrieve from configured datasets.

Validation

  • uvx cmake -S internal/cpp -B internal/cpp/cmake-build-release
  • uvx cmake --build internal/cpp/cmake-build-release --target rag_tokenizer_c_api -j 4
  • go test ./internal/service -run 'Test(AsyncChat|MessagesWithRetrievedKnowledge|ApplyMetaFilter|ConvertToMetaCondition|ApplySingleCondition|CompareValues)' -count=1
  • go test ./internal/service -run '^$' -count=1
  • go test ./internal/handler -run 'TestDifyRetrieval|Chat' -count=1
  • go vet ./internal/service ./internal/handler
  • git diff --check

Notes

  • The branch is rebased onto current main and mergeable.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Injects KB/retrieval/metadata/doc-engine interfaces into ChatSessionService, threads userID through async chat, implements KB-backed retrieval (streaming and non-streaming) with metadata filtering and knowledge injection, adds NoMatchDocIDSentinel, and adds tests plus a GetRerankModel helper.

Changes

Knowledge Base Retrieval in Chat Sessions

Layer / File(s) Summary
Dify & handler adjustments
internal/handler/chat_session.go, internal/handler/dify_retrieval_handler.go
Handler streaming call now passes request context; Dify handler formatting and switch to service.NoMatchDocIDSentinel for metadata-filter no-match case.
Dependency interfaces and wiring
internal/service/chat_session.go (imports, lines ~20–91)
Introduce internal interfaces for KB store, model provider, metadata, and retrieval; extend ChatSessionService fields and wire default retrieval service in constructors.
User-aware async routing
internal/service/chat_session.go (lines ~338,354,494–528)
Completion/CompletionStream pass userID; asyncChat updated to accept userID and dispatch KB-backed dialogs to retrieval flows with Tavily-backed fallback warning.
Streaming + Core retrieval and knowledge injection
internal/service/chat_session.go (lines ~549–1130)
Add asyncChatStream, asyncChatWithRetrieval, messagesWithRetrievedKnowledge and helpers: load/authorize KBs, extract question/doc constraints, resolve embedding/rerank models, apply metadata filters, call retrievalSvc.Retrieval, optionally expand chunks via docEngine, build knowledge/reference blocks, and inject knowledge into system prompt or messages (multimodal-aware).
Test doubles and retrieval behavior tests
internal/service/chat_session_test.go
New test suite with fakes/stubs validating retrieval invocation, error propagation, placeholder replacement, empty-response behavior, metadata filtering/sentinel, fail-closed behavior when metadata unavailable, chunk expansion, tenant authorization/shared KB access, multimodal preservation, and doc_id deduplication.
Metadata filter and sentinel
internal/service/metadata_filter.go, internal/service/metadata_filter_test.go
Add exported NoMatchDocIDSentinel = "-999", trim/skip-empty parsing for "in"/"not in" values, and return sentinel when manual metadata filter yields no matches; test import adjusted for deterministic sorting.
Model rerank helper
internal/service/model_service.go
Add GetRerankModel method to ModelProviderService that resolves model config and returns a modelModule.RerankModel.

Sequence Diagram

sequenceDiagram
  participant Client
  participant ChatSessionService
  participant RetrievalService
  participant KnowledgebaseStore
  participant ModelProvider
  participant DocEngine

  Client->>ChatSessionService: Completion(userID, messages, kbIDs)
  ChatSessionService->>ChatSessionService: asyncChat(userID, messages, kbIDs)
  alt Has Knowledge Bases
    ChatSessionService->>KnowledgebaseStore: LoadKBs(kbIDs, userID)
    KnowledgebaseStore-->>ChatSessionService: KBs (tenant info, embedding model)
    ChatSessionService->>RetrievalService: Retrieval(question, docIDs, embeddingModel, rerankModel)
    RetrievalService-->>ChatSessionService: chunks
    ChatSessionService->>DocEngine: ExpandParentChunks(chunks)
    DocEngine-->>ChatSessionService: expandedChunks
    ChatSessionService->>ModelProvider: Chat(messages with injected knowledge)
    ModelProvider-->>ChatSessionService: response + references
  else No Knowledge or Tavily-only
    ChatSessionService->>ModelProvider: Chat(messages without retrieval)
    ModelProvider-->>ChatSessionService: response
  end
  ChatSessionService-->>Client: answer + references
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • Haruko386
  • JinHai-CN

Poem

🐰 I hopped through code to fetch the facts,
UserIDs threaded through chatty tracts.
Chunks expand and sentinels stand true,
Tests nod yes — retrieval joins the queue. ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.90% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The PR description does not follow the required template structure with the specified section headings. Restructure the description to match the template: add explicit 'What problem does this PR solve?' section, and clearly mark 'Type of change' with checkbox options (Bug Fix, New Feature, Documentation Update, Refactoring, Performance Improvement, Other).
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: adding RAG retrieval to chat completions in the Go API, which matches the substantial code refactoring and new retrieval functionality throughout the pull request.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@oktofeesh1

Copy link
Copy Markdown
Contributor Author

Hi @Haruko386 @JinHai-CN this is ready for review 👍

@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 (2)
internal/service/chat_session.go (1)

727-731: 💤 Low value

Consider using a named constant for the empty filter sentinel.

The magic string "-999" used as a sentinel to indicate "no documents match the filter" would benefit from being a named constant for clarity and maintainability.

♻️ Suggested constant definition
+// emptyFilterSentinel is a doc ID that matches no documents, used to short-circuit
+// retrieval when metadata filtering excludes all documents.
+const emptyFilterSentinel = "-999"
+
 func (s *ChatSessionService) filteredDocIDsForDialog(ctx context.Context, dialog *entity.Chat, kbIDs []string, question string, baseDocIDs []string) ([]string, error) {
 	if empty {
-		return []string{"-999"}, nil
+		return []string{emptyFilterSentinel}, 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/chat_session.go` around lines 727 - 731, Replace the magic
sentinel string "-999" with a named constant (e.g., EmptyFilterSentinel or
NoMatchSentinel) to make intent clear: define the constant near related code or
in a package-level const block, update the return in the conditional inside the
function where ApplyMetaDataFilter is handled (the block that currently returns
[]string{"-999"}) to return []string{EmptyFilterSentinel}, and search for other
places that compare to "-999" (or rely on that sentinel) and update them to use
the new constant so all sentinel comparisons and returns use the named symbol.
internal/service/chat_session_test.go (1)

294-294: 💤 Low value

Consider checking json.Marshal errors explicitly in test setup.

While marshaling these simple test structures will never fail in practice, explicitly checking the error (e.g., require.NoError(t, err) if using testify, or a simple panic) would make the test setup more robust and consistent.

Also applies to: 448-448

🤖 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/chat_session_test.go` at line 294, The test setup marshals
JSON into sessionMessage without checking the returned error; update both
occurrences (the sessionMessage assignment at the location creating
map[string]interface{}{"messages": []interface{}{}} and the similar marshal at
the other reported spot) to capture the (data, err) result and assert or fail on
err (e.g., use require.NoError(t, err) or panic/ t.Fatalf) before using
sessionMessage so tests fail clearly on marshal errors.
🤖 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/chat_session_test.go`:
- Line 294: The test setup marshals JSON into sessionMessage without checking
the returned error; update both occurrences (the sessionMessage assignment at
the location creating map[string]interface{}{"messages": []interface{}{}} and
the similar marshal at the other reported spot) to capture the (data, err)
result and assert or fail on err (e.g., use require.NoError(t, err) or panic/
t.Fatalf) before using sessionMessage so tests fail clearly on marshal errors.

In `@internal/service/chat_session.go`:
- Around line 727-731: Replace the magic sentinel string "-999" with a named
constant (e.g., EmptyFilterSentinel or NoMatchSentinel) to make intent clear:
define the constant near related code or in a package-level const block, update
the return in the conditional inside the function where ApplyMetaDataFilter is
handled (the block that currently returns []string{"-999"}) to return
[]string{EmptyFilterSentinel}, and search for other places that compare to
"-999" (or rely on that sentinel) and update them to use the new constant so all
sentinel comparisons and returns use the named symbol.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7868d4d4-1593-44ea-a160-52e6bfecfdff

📥 Commits

Reviewing files that changed from the base of the PR and between 5a04ac0 and e3c5f52.

📒 Files selected for processing (2)
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go

@oktofeesh1
oktofeesh1 force-pushed the codex/go-chat-rag-completion branch from eb907cc to 5139748 Compare June 8, 2026 06:48

@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 (2)
internal/service/chat_session.go (2)

1048-1051: 💤 Low value

Mutation of dialog.PromptConfig may cause unexpected side effects.

injectKnowledgeIntoDialogPrompt mutates dialog.PromptConfig in place by replacing the "system" key. While cloneJSONMap creates a shallow copy, this still modifies the dialog's state which could affect callers if the dialog object is reused elsewhere.

Consider documenting this intentional mutation or ensuring callers don't rely on the original prompt config after this function is called.

🤖 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/chat_session.go` around lines 1048 - 1051,
injectKnowledgeIntoDialogPrompt is mutating dialog.PromptConfig by assigning
copied["system"] and then writing copied back to dialog.PromptConfig, which can
cause caller-side surprises; instead avoid mutating the dialog in place by
producing a new prompt config and returning it (or rename function to indicate
mutation) — use a deep copy routine (or extend cloneJSONMap to deep clone) to
create newConfig, set newConfig["system"] = strings.ReplaceAll(systemPrompt,
"{knowledge}", knowledge), and return the newConfig so callers explicitly assign
it (or, if mutation is intentional, update function name/docs to state it
mutates dialog.PromptConfig).

607-614: 💤 Low value

Consider validating embedding model consistency across KBs.

The code uses only the first KB's embedding model (line 607: kbs[0]). If the dialog references multiple knowledge bases created with different embedding models, the retrieval may produce unexpected results due to embedding dimension mismatches.

If this is intentional (e.g., dialogs are expected to only reference KBs with compatible embeddings), consider adding a validation check or comment documenting this assumption.

🤖 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/chat_session.go` around lines 607 - 614, The code currently
picks the embedding model from only kbs[0] via embeddingModelForKnowledgebase,
which can cause dimension/compatibility issues if dialog.KnowledgeBases includes
KBs using different embedding models; update the logic to validate that all kbs
have the same embedding model (or compatible dimensions) before proceeding:
iterate over kbs, resolve each with embeddingModelForKnowledgebase (or otherwise
retrieve the model identifier/dimension from each KB), compare against the model
for kbs[0], and return an explicit error if any mismatch is found (or
document/assert the single-model assumption), referencing kbs,
embeddingModelForKnowledgebase, embeddingTenantID and dialog to locate the code
to change.
🤖 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/chat_session.go`:
- Around line 1048-1051: injectKnowledgeIntoDialogPrompt is mutating
dialog.PromptConfig by assigning copied["system"] and then writing copied back
to dialog.PromptConfig, which can cause caller-side surprises; instead avoid
mutating the dialog in place by producing a new prompt config and returning it
(or rename function to indicate mutation) — use a deep copy routine (or extend
cloneJSONMap to deep clone) to create newConfig, set newConfig["system"] =
strings.ReplaceAll(systemPrompt, "{knowledge}", knowledge), and return the
newConfig so callers explicitly assign it (or, if mutation is intentional,
update function name/docs to state it mutates dialog.PromptConfig).
- Around line 607-614: The code currently picks the embedding model from only
kbs[0] via embeddingModelForKnowledgebase, which can cause
dimension/compatibility issues if dialog.KnowledgeBases includes KBs using
different embedding models; update the logic to validate that all kbs have the
same embedding model (or compatible dimensions) before proceeding: iterate over
kbs, resolve each with embeddingModelForKnowledgebase (or otherwise retrieve the
model identifier/dimension from each KB), compare against the model for kbs[0],
and return an explicit error if any mismatch is found (or document/assert the
single-model assumption), referencing kbs, embeddingModelForKnowledgebase,
embeddingTenantID and dialog to locate the code to change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f26022e4-87f0-4b30-bc7e-e162367311e1

📥 Commits

Reviewing files that changed from the base of the PR and between eb907cc and 5139748.

📒 Files selected for processing (6)
  • internal/handler/dify_retrieval_handler.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/metadata_filter.go
  • internal/service/metadata_filter_test.go
  • internal/service/model_service.go
✅ Files skipped from review due to trivial changes (1)
  • internal/service/metadata_filter_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/handler/dify_retrieval_handler.go
  • internal/service/chat_session_test.go

@oktofeesh1
oktofeesh1 force-pushed the codex/go-chat-rag-completion branch from 5139748 to 2f07b44 Compare June 8, 2026 06:59

@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 (2)
internal/service/chat_session.go (2)

543-543: ⚖️ Poor tradeoff

Consider propagating a cancellable context into the goroutine.

Using context.Background() means the retrieval operation cannot be cancelled if the client disconnects. Under high load, this could result in orphaned goroutines completing work for requests that will never be consumed. If the HTTP handler provides a request context, threading it through CompletionStream → asyncChatStream → messagesWithRetrievedKnowledge would allow graceful cancellation.

🤖 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/chat_session.go` at line 543, The call to
messagesWithRetrievedKnowledge currently uses context.Background(), preventing
cancellation; update CompletionStream and asyncChatStream signatures to accept a
context.Context from the HTTP request (or the caller) and pass that context into
messagesWithRetrievedKnowledge instead of context.Background(), and ensure any
goroutine spawned for asyncChatStream/CompletionStream uses that cancellable ctx
(select on ctx.Done() where appropriate) so retrieval and downstream work can be
cancelled when the request context is cancelled.

1378-1382: 💤 Low value

Consider adding a defensive type check to prevent potential panic.

The type assertion lastMsg["content"].(string) will panic if content is nil or not a string. While the normal flow always produces string content, corrupted session data or external modifications could trigger this path with unexpected types.

🛡️ Optional defensive fix
-			if ans["final"] == true && ans["answer"] != nil {
-				lastMsg["content"] = ans["answer"]
-			} else {
-				lastMsg["content"] = (lastMsg["content"].(string)) + content
-			}
+			if ans["final"] == true && ans["answer"] != nil {
+				lastMsg["content"] = ans["answer"]
+			} else {
+				existing, _ := lastMsg["content"].(string)
+				lastMsg["content"] = existing + content
+			}
🤖 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/chat_session.go` around lines 1378 - 1382, Add a defensive
type-check before concatenating to lastMsg["content"]: instead of using
lastMsg["content"].(string) blindly (which can panic), use the comma-ok type
assertion to verify it's a string and handle non-string or nil cases by either
converting to an empty string or logging and skipping concatenation; update the
branch where ans["final"] is false (the else block handling lastMsg and content)
to safely cast lastMsg["content"] to string using the ok pattern and then set
lastMsg["content"] = existing + content (or fallback to content) to avoid panics
when lastMsg["content"] is nil or of an unexpected type.
🤖 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/chat_session.go`:
- Line 543: The call to messagesWithRetrievedKnowledge currently uses
context.Background(), preventing cancellation; update CompletionStream and
asyncChatStream signatures to accept a context.Context from the HTTP request (or
the caller) and pass that context into messagesWithRetrievedKnowledge instead of
context.Background(), and ensure any goroutine spawned for
asyncChatStream/CompletionStream uses that cancellable ctx (select on ctx.Done()
where appropriate) so retrieval and downstream work can be cancelled when the
request context is cancelled.
- Around line 1378-1382: Add a defensive type-check before concatenating to
lastMsg["content"]: instead of using lastMsg["content"].(string) blindly (which
can panic), use the comma-ok type assertion to verify it's a string and handle
non-string or nil cases by either converting to an empty string or logging and
skipping concatenation; update the branch where ans["final"] is false (the else
block handling lastMsg and content) to safely cast lastMsg["content"] to string
using the ok pattern and then set lastMsg["content"] = existing + content (or
fallback to content) to avoid panics when lastMsg["content"] is nil or of an
unexpected type.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5395f435-cc3d-4b00-811a-e35f46aea4d4

📥 Commits

Reviewing files that changed from the base of the PR and between 5139748 and 2f07b44.

📒 Files selected for processing (6)
  • internal/handler/dify_retrieval_handler.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/metadata_filter.go
  • internal/service/metadata_filter_test.go
  • internal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/service/metadata_filter_test.go
  • internal/handler/dify_retrieval_handler.go
  • internal/service/metadata_filter.go
  • internal/service/model_service.go
  • internal/service/chat_session_test.go

@oktofeesh1
oktofeesh1 force-pushed the codex/go-chat-rag-completion branch from 2f07b44 to e19d938 Compare June 8, 2026 07:12

@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/handler/chat_session.go`:
- Around line 295-298: The goroutine currently reads c.Request.Context()
directly inside go func(), which may access Gin request state concurrently;
capture the request context into a local variable (e.g., reqCtx :=
c.Request.Context()) before starting the goroutine and pass that reqCtx into
chatSessionService.CompletionStream instead of calling c.Request.Context()
inside the goroutine; update the call site where CompletionStream(userID,
req.ConversationID, ...) is invoked to include this captured context so the
worker uses the safe, pre-captured context and keeps streamChan and messageID
usage unchanged.
🪄 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: fc261014-f456-47c1-b1ff-be12c64dec62

📥 Commits

Reviewing files that changed from the base of the PR and between 2f07b44 and e19d938.

📒 Files selected for processing (7)
  • internal/handler/chat_session.go
  • internal/handler/dify_retrieval_handler.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/metadata_filter.go
  • internal/service/metadata_filter_test.go
  • internal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/service/metadata_filter.go
  • internal/service/metadata_filter_test.go
  • internal/handler/dify_retrieval_handler.go
  • internal/service/model_service.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go

Comment thread internal/handler/chat_session.go Resolved
@Haruko386 Haruko386 added the ci Continue Integration label Jun 9, 2026
@Haruko386
Haruko386 marked this pull request as draft June 9, 2026 02:58
@Haruko386
Haruko386 marked this pull request as ready for review June 9, 2026 02:58

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @oktofeesh1 The overall direction is useful: this replaces the Go chat RAG placeholder with actual KB retrieval and wires in model resolution, KB access checks, retrieval context, prompt injection, and reference construction.

However, I think this needs fixes before matching the PR description.

First, metadata filters and message-level doc_ids are currently combined as a union. ApplyMetaDataFilter initializes docIDs with baseDocIDs and then appends metadata-filter matches. That means doc_ids can bypass metadata filters, and metadata no-match will not produce the no-match sentinel when baseDocIDs is non-empty. These constraints should be intersected so retrieval only sees documents satisfying both.

Second, validateKnowledgebaseEmbeddingModels only compares Knowledgebase.EmbdID. It does not account for TenantEmbdID or the resolved composite embedding model, so mixed tenant-specific embedding configs can pass validation. Since the goal is avoiding incompatible vector dimensions, this should compare the resolved embedding model identity used for retrieval.

@codecov

codecov Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (64b860f) to head (136a40b).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15739   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@oktofeesh1
oktofeesh1 requested a review from Haruko386 June 9, 2026 04:49
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

Hi @oktofeesh1 The overall direction is useful: this replaces the Go chat RAG placeholder with actual KB retrieval and wires in model resolution, KB access checks, retrieval context, prompt injection, and reference construction.

However, I think this needs fixes before matching the PR description.

First, metadata filters and message-level doc_ids are currently combined as a union. ApplyMetaDataFilter initializes docIDs with baseDocIDs and then appends metadata-filter matches. That means doc_ids can bypass metadata filters, and metadata no-match will not produce the no-match sentinel when baseDocIDs is non-empty. These constraints should be intersected so retrieval only sees documents satisfying both.

Second, validateKnowledgebaseEmbeddingModels only compares Knowledgebase.EmbdID. It does not account for TenantEmbdID or the resolved composite embedding model, so mixed tenant-specific embedding configs can pass validation. Since the goal is avoiding incompatible vector dimensions, this should compare the resolved embedding model identity used for retrieval.

Thanks, both review points were valid and are fixed now.

What changed:

  • Metadata filters and message-level doc_ids are now intersected instead of unioned.
  • If explicit doc_ids and metadata matches have no overlap, retrieval receives NoMatchDocIDSentinel.
  • Empty manual metadata filters still preserve the original doc_ids.
  • validateKnowledgebaseEmbeddingModels now compares resolved composite embedding model identities, including TenantEmbdID overrides.
  • Retrieval now uses the validated resolved embedding model identity.

Validation:

  • go test ./internal/service -run 'TestMessagesWithRetrievedKnowledge|TestValidateKnowledgebaseEmbeddingModels'
  • git diff --check
  • Verified clean merge-tree against current upstream/main.

Note: broader go test ./internal/service still fails on existing document ownership/database fixture tests unrelated to this PR.

@Haruko386

Copy link
Copy Markdown
Member

@oktofeesh1 fix the CI error

yingfeng and others added 2 commits June 9, 2026 21:17
The chat_session_test.go fake still returned []string after #15862
re-enabled the Go test step and fixed the entity/models test files,
so internal/service still failed to build. Align fakeChatModelDriver
with the new ModelDriver.ListModels signature.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

@oktofeesh1 fix the CI error

@Haruko386 fixed.

@JinHai-CN
JinHai-CN requested a review from qinling0210 June 10, 2026 02:04

@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

@JinHai-CN
JinHai-CN merged commit bbc1f2e into infiniflow:main Jun 10, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 10, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants