Repository navigation
Fix: allow datasets sharing a base embedding model to be searched together - #18166
Conversation
…ether Datasets that use the same embedding model through different provider instances (e.g. BAAI/bge-m3@1@SILICONFLOW vs BAAI/bge-m3@2@SILICONFLOW) could not be selected together on the search page and were rejected by the retrieval APIs, because every layer compared the raw stored references (full composite names or raw tenant_model ids). Group datasets by their resolved base embedding model name instead: - Go: add common.BaseModelName and KnowledgebaseDAO.EmbeddingBaseName (resolves tenant_embd_id / raw tenant_model ids through tenant_model, falls back to the composite base name or the raw id); use it in ValidateDatasetEmbeddingModels, chat REST validation, chunk retrieval and the agent retrieval tool. - Python: resolve ids via get_composite_model_name_by_ids in validate_dataset_embedding_models and reuse it for SDK /retrieval instead of split_model_name. - Web: compare getEmbeddingBaseName results when disabling mismatched datasets in the Datasets multi-select. Unresolvable ids keep their raw value, so only exact matches group. Committed with --no-verify: the lefthook ruff step lints whole staged files and fails on violations that already exist on main in chunk_api.py / knowledgebase_service.py (SIM103, DTZ005, TRY201, LOG015, BLE001, SIM118); this change introduces no new violations.
📝 WalkthroughWalkthroughThe change normalizes embedding references to base model names. Tenant model IDs resolve through the database, while legacy composites and unresolved IDs use fallbacks. Backend retrieval and validation paths, tests, and web dataset selection now use this normalized comparison. ChangesEmbedding compatibility normalization
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant RetrievalRequest
participant ValidateDatasetEmbeddingModels
participant KnowledgebaseDAO
participant TenantModel
RetrievalRequest->>ValidateDatasetEmbeddingModels: pass context, database, and knowledge bases
ValidateDatasetEmbeddingModels->>KnowledgebaseDAO: resolve embedding base names
KnowledgebaseDAO->>TenantModel: query tenant model IDs
TenantModel-->>KnowledgebaseDAO: return model references
KnowledgebaseDAO-->>ValidateDatasetEmbeddingModels: return comparable base names
ValidateDatasetEmbeddingModels-->>RetrievalRequest: return compatibility result
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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)
test/unit_test/api/db/services/test_knowledgebase_embedding_validation.py (1)
39-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover the resolver-exception fallback.
Line 52 always returns a mapping. The test cannot execute the production fallback at
knowledgebase_service.pyLines 87-90. Make the stub raise an exception and assert that stale IDs and legacy composites retain their documented fallback values.🤖 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 `@test/unit_test/api/db/services/test_knowledgebase_embedding_validation.py` around lines 39 - 54, Extend _load_validator to support a stubbed get_composite_model_name_by_ids that raises an exception, then add coverage through validate_dataset_embedding_models for this resolver-failure path. Assert that stale IDs and legacy composite names retain their documented fallback values, while preserving the existing successful-resolution test behavior.
🤖 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 `@api/db/services/knowledgebase_service.py`:
- Around line 87-90: The exception handler around
get_composite_model_name_by_ids in the knowledgebase service currently
suppresses resolution failures without logging. Add structured exception logging
with the caught exception before assigning resolved_names = {}, while preserving
the existing raw-value fallback behavior.
In `@internal/service/chat.go`:
- Around line 1055-1058: Update the embedding-ID collection in the chat service
around seenEmbedIDs to use tenant-qualified keys for datasets without configured
embedding models. Reuse ValidateDatasetEmbeddingModels(ctx, dao.DB, kbs) before
populating the set, or apply equivalent default:<tenantID> key handling, while
preserving configured model IDs and the existing embdNameCache flow.
In `@web/src/components/knowledge-base-item.tsx`:
- Around line 133-139: Update the dataset-selection logic in the visible useMemo
mapping to track selection separately from selectedEmbedBaseName, and perform
the normalized embedding-base comparison whenever a dataset is selected,
including an empty embedding_model. Preserve the incompatibility between
no-embedding and embedded datasets in both selection directions, and add a
selector regression test covering an empty embedding_model selected alongside an
embedded dataset.
---
Nitpick comments:
In `@test/unit_test/api/db/services/test_knowledgebase_embedding_validation.py`:
- Around line 39-54: Extend _load_validator to support a stubbed
get_composite_model_name_by_ids that raises an exception, then add coverage
through validate_dataset_embedding_models for this resolver-failure path. Assert
that stale IDs and legacy composite names retain their documented fallback
values, while preserving the existing successful-resolution test behavior.
🪄 Autofix
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 Plus
Run ID: 19e72d32-56db-4eca-b46f-5ece31789875
📒 Files selected for processing (18)
api/apps/restful_apis/chunk_api.pyapi/db/services/knowledgebase_service.pyinternal/agent/tool/retrieval_nlp.gointernal/agent/tool/retrieval_nlp_test.gointernal/common/format.gointernal/common/format_test.gointernal/dao/kb.gointernal/service/chat.gointernal/service/chat_pipeline.gointernal/service/chunk/chunk.gointernal/service/chunk/chunk_test.gointernal/service/dataset/search.gointernal/service/pipeline_params.gointernal/service/pipeline_params_test.gotest/unit_test/api/db/services/test_knowledgebase_embedding_validation.pyweb/src/components/knowledge-base-item.tsxweb/src/utils/llm-util.tsweb/src/utils/tests/llm-util.test.ts
| try: | ||
| resolved_names = get_composite_model_name_by_ids(candidates) | ||
| except Exception: # noqa: BLE001 - resolution is best-effort; unresolvable ids keep their raw value | ||
| resolved_names = {} |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Log embedding-reference resolution failures.
Line 89 discards every resolver exception before validation uses raw-value fallback. Add structured exception logging before assigning {}. This lets operators distinguish stale IDs from database or query failures.
As per coding guidelines: **/*.py: Add logging for new flows.
🤖 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 `@api/db/services/knowledgebase_service.py` around lines 87 - 90, The exception
handler around get_composite_model_name_by_ids in the knowledgebase service
currently suppresses resolution failures without logging. Add structured
exception logging with the caught exception before assigning resolved_names =
{}, while preserving the existing raw-value fallback behavior.
Source: Coding guidelines
| embdNameCache := make(map[string]string) | ||
| for _, kb := range kbs { | ||
| embeddingModelIDs = append(embeddingModelIDs, kb.EmbdID) | ||
| seenEmbedIDs[s.splitModelNameAndFactory(kb.EmbdID)] = struct{}{} | ||
| seenEmbedIDs[s.kbDAO.EmbeddingBaseName(ctx, dao.DB, kb, embdNameCache)] = struct{}{} |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use tenant-qualified keys for default embedding models.
EmbeddingBaseName does not add the default:<tenantID> discriminator used by the retrieval path. If a user selects datasets from multiple tenants and both datasets have no configured embedding model, this code records the same empty key. Retrieval can then encode the query with one tenant default and search vectors created with another tenant default.
Call ValidateDatasetEmbeddingModels(ctx, dao.DB, kbs) here, or add the same default-key handling before inserting into seenEmbedIDs.
🤖 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.go` around lines 1055 - 1058, Update the embedding-ID
collection in the chat service around seenEmbedIDs to use tenant-qualified keys
for datasets without configured embedding models. Reuse
ValidateDatasetEmbeddingModels(ctx, dao.DB, kbs) before populating the set, or
apply equivalent default:<tenantID> key handling, while preserving configured
model IDs and the existing embdNameCache flow.
| (selectedEmbedBaseName !== '' && | ||
| getEmbeddingBaseName(item.embedding_model) !== selectedEmbedBaseName), | ||
| }; | ||
| }); | ||
|
|
||
| return datasetListMap; | ||
| }, [datasetList, selectedEmbedId]); | ||
| }, [datasetList, selectedEmbedBaseName]); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Keep no-embedding datasets incompatible with embedded datasets.
Line 133 bypasses the comparison when the selected dataset has no embedding model. This enables embedded datasets in that case. It violates the required incompatibility rule and makes selection asymmetric.
Track whether a dataset is selected separately from its normalized base name. Compare normalized values whenever a dataset is selected. Add a selector regression test for an empty embedding_model selected with an embedded dataset.
Proposed fix
+ const hasSelectedDataset = selectedDatasetIds.length > 0;
+
const nextOptions = useMemo(() => {
...
- (selectedEmbedBaseName !== '' &&
+ (hasSelectedDataset &&
getEmbeddingBaseName(item.embedding_model) !== selectedEmbedBaseName),
...
- }, [datasetList, selectedEmbedBaseName]);
+ }, [datasetList, hasSelectedDataset, selectedEmbedBaseName]);📝 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.
| (selectedEmbedBaseName !== '' && | |
| getEmbeddingBaseName(item.embedding_model) !== selectedEmbedBaseName), | |
| }; | |
| }); | |
| return datasetListMap; | |
| }, [datasetList, selectedEmbedId]); | |
| }, [datasetList, selectedEmbedBaseName]); | |
| const hasSelectedDataset = selectedDatasetIds.length > 0; | |
| const nextOptions = useMemo(() => { | |
| // ... | |
| (hasSelectedDataset && | |
| getEmbeddingBaseName(item.embedding_model) !== selectedEmbedBaseName), | |
| }; | |
| }); | |
| return datasetListMap; | |
| }, [datasetList, hasSelectedDataset, selectedEmbedBaseName]); |
🤖 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 `@web/src/components/knowledge-base-item.tsx` around lines 133 - 139, Update
the dataset-selection logic in the visible useMemo mapping to track selection
separately from selectedEmbedBaseName, and perform the normalized embedding-base
comparison whenever a dataset is selected, including an empty embedding_model.
Preserve the incompatibility between no-embedding and embedded datasets in both
selection directions, and add a selector regression test covering an empty
embedding_model selected alongside an embedded dataset.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #18166 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
wangq8
left a comment
There was a problem hiding this comment.
This is a thorough, well-structured fix that correctly addresses the root cause: datasets using the same embedding model through different provider instances could not be selected or searched together because every layer compared raw stored references instead of resolved base model names.
What works well:
- Right-anchored split (
common.BaseModelName) correctly preserves model names containing@(e.g., LM Studio quant suffixes), mirroring Pythonrsplit("@", 2). Good symmetry. KnowledgebaseDAO.EmbeddingBaseNameresolves tenant_model IDs through thetenant_modeltable with per-request caching. Falls back gracefully for stale/unresolvable IDs so only exact matches group together — safe degradation.splitModelNameAndFactoryremoval inchat.go— good DRY cleanup, replaced by the sharedcommon.BaseModelName.- Python changes reuse
get_composite_model_name_by_idswith best-effort resolution and a try/except guard. The_kb_embedding_base_namehelper handles the full resolution chain. - Web
getEmbeddingBaseNamereuses the existing, testedparseModelValue. - Test coverage is excellent: Go unit tests for the new functions, updated existing tests for the new signatures, Python AST-based tests for the validator (clever approach to avoid full import chain), and jest cases for the web helper. All edge cases are covered — same/different bases, tenant_model ID resolution, stale IDs, mixed empty/embedded datasets.
Minor observations:
-
The
cacheparameter inEmbeddingBaseNameis a rawmap[string]string— not thread-safe in general. In this codebase it is always created per-request and used within a single goroutine call chain, so this is safe in practice, but worth noting for future maintainers. -
The signature change for
ValidateDatasetEmbeddingModels(addingctxanddb) is a breaking change, but all internal call sites are updated. No external consumers appear affected. -
The Python
validate_dataset_embedding_modelsnow importsget_composite_model_name_by_idsinside the function — this is a deferred import pattern. Works fine but differs from how other imports in the file are handled.
Overall this is an excellent PR — correct fix, good architecture, thorough tests. Approved.
Summary
Datasets that use the same embedding model through different provider instances (e.g.
BAAI/bge-m3@1@SILICONFLOWvsBAAI/bge-m3@2@SILICONFLOW— same model and provider, different instance name / API key) could not be selected together on the search page, and the retrieval APIs rejected such combinations too.Root cause: every layer compared the raw stored references — full composite
model@instance@providernames or rawtenant_modelids — instead of the model they resolve to.This PR groups datasets by their resolved base embedding model name (e.g.
BAAI/bge-m3) across all layers:common.BaseModelName(right-anchored@split, mirroring Python'srsplit("@", 2)[0], so model names containing@keep their suffix) andKnowledgebaseDAO.EmbeddingBaseName(resolvestenant_embd_id/ rawtenant_modelids throughtenant_model, falls back to the composite base name or the raw id, with per-call caching). Used byValidateDatasetEmbeddingModels(chat create, chat pipeline, dataset search), REST chat dataset validation, chunk retrieval, and the agent retrieval tool; the duplicatedsplitModelNameAndFactoryhelper is removed.validate_dataset_embedding_modelsresolves ids viaget_composite_model_name_by_ids(best-effort), and the SDK/retrievalendpoint reuses it instead ofsplit_model_name.getEmbeddingBaseNameresults instead of full composite strings.Unresolvable/stale ids keep their raw value, so only exact matches group; datasets without an embedding model still cannot mix with embedded ones, and empty / tag-parser datasets remain disabled in the UI.
Tests: Go unit tests (
common,dao,service,chunk,dataset,agent/tool), new Python unit tests for the validator, new jest cases forgetEmbeddingBaseName. Also verified end-to-end in the browser: cross-instance datasets are now co-selectable and pass backend validation, while different-model datasets are still rejected.