Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(search): isolate multi-KB embedding dimensions (#4659)

Sun Shihao8c188986a510
diff --git a/internal/agent/tools/search_knowledge.go b/internal/agent/tools/search_knowledge.go
index 28fbbd938..43da62aa9 100644
--- a/internal/agent/tools/search_knowledge.go
+++ b/internal/agent/tools/search_knowledge.go
@@ -571,9 +571,9 @@ func (t *SearchKnowledgeTool) retrievalParams(limit int) (topK int, vectorThresh
}
// concurrentSearchByTargets executes retrieval using pre-computed search targets.
-// Targets sharing the same underlying embedding model (identified by model name + endpoint)
-// are grouped so the query embedding is computed once per model, and all
-// full-KB targets in a group are combined into a single retrieval call.
+// Targets sharing the same model name, endpoint and configured vector dimension
+// are grouped so each group computes one query embedding and combines all
+// full-KB targets into a single retrieval call.
func (t *SearchKnowledgeTool) concurrentSearchByTargets(
ctx context.Context,
query string,
@@ -620,7 +620,8 @@ func (t *SearchKnowledgeTool) concurrentSearchByTargets(
}
searchTargets = filteredTargets
- // Resolve actual model identities (name + endpoint) for cross-tenant grouping
+ // Resolve actual model identities (name + endpoint + configured dimension)
+ // for cross-tenant grouping
modelKeyMap := t.knowledgeBaseService.ResolveEmbeddingModelKeys(ctx, kbList)
groups := make(map[string][]*types.SearchTarget)
diff --git a/internal/application/service/chat_pipeline/search.go b/internal/application/service/chat_pipeline/search.go
index 59f179a59..b0f89c260 100644
--- a/internal/application/service/chat_pipeline/search.go
+++ b/internal/application/service/chat_pipeline/search.go
@@ -361,10 +361,10 @@ func targetReportsEmbedFailure(kb *types.KnowledgeBase) bool {
}
// searchByTargets performs KB searches using pre-computed SearchTargets.
-// Targets sharing the same underlying embedding model (identified by model
-// name + endpoint, not just model ID) are grouped so the query embedding is
-// computed once per model AND all full-KB targets in a group are combined into
-// a single retrieval call, reducing both embedding API calls and DB round-trips.
+// Targets sharing the same model name, endpoint and configured vector dimension
+// are grouped even across model IDs. Each group computes one query embedding
+// and combines all full-KB targets into a single retrieval call, reducing both
+// embedding API calls and DB round-trips.
func (p *PluginSearch) searchByTargets(
ctx context.Context,
chatManage *types.ChatManage,
@@ -397,8 +397,9 @@ func (p *PluginSearch) searchByTargets(
})
}
- // Resolve actual model identities (name + endpoint) so that cross-tenant
- // KBs backed by the same physical model share one embedding computation.
+ // Resolve actual model identities (name + endpoint + configured dimension)
+ // so that cross-tenant KBs backed by the same vector space share one
+ // embedding computation.
modelKeyMap := p.knowledgeBaseService.ResolveEmbeddingModelKeys(ctx, kbList)
groups := make(map[string][]*types.SearchTarget)
diff --git a/internal/application/service/knowledgebase_search.go b/internal/application/service/knowledgebase_search.go
index e615197e4..e4ef91181 100644
--- a/internal/application/service/knowledgebase_search.go
+++ b/internal/application/service/knowledgebase_search.go
@@ -21,8 +21,8 @@ const maxRetrievalPoolSize = 500
// GetQueryEmbedding computes the query embedding using the embedding model
// associated with the given knowledge base. Callers can pre-compute and reuse
-// the result across multiple KBs that share the same embedding model to avoid
-// redundant embedding API calls.
+// the result across multiple KBs that share the same embedding model and
+// configured vector dimension to avoid redundant embedding API calls.
func (s *knowledgeBaseService) GetQueryEmbedding(ctx context.Context, kbID string, queryText string) ([]float32, error) {
kb, err := s.repo.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
@@ -77,8 +77,10 @@ func validateQueryEmbeddingDimension(model embedding.Embedder, actual int) error
}
// ResolveEmbeddingModelKeys resolves embedding model IDs to their actual model
-// identity key (name + endpoint). KBs using the same underlying model across
-// different tenants will share the same key, enabling optimal grouping.
+// identity key (name + endpoint + configured vector dimension). KBs using the
+// same underlying model and vector space across different tenants will share
+// the same key, enabling optimal grouping without reusing a query embedding
+// across incompatible index dimensions.
func (s *knowledgeBaseService) ResolveEmbeddingModelKeys(ctx context.Context, kbs []*types.KnowledgeBase) map[string]string {
type modelRef struct {
ModelID string
@@ -94,7 +96,9 @@ func (s *knowledgeBaseService) ResolveEmbeddingModelKeys(ctx context.Context, kb
kbRefs[kb.ID] = ref
}
- // Resolve each unique (modelID, tenantID) to a model identity key
+ // Resolve each unique (modelID, tenantID) to a model identity key. The
+ // configured dimension is part of the key because providers such as OpenAI
+ // support multiple output widths for one model name and endpoint.
resolvedKeys := make(map[modelRef]string, len(uniqueRefs))
for ref := range uniqueRefs {
tenantCtx := types.WithExecutionTenant(ctx, ref.TenantID)
@@ -104,7 +108,8 @@ func (s *knowledgeBaseService) ResolveEmbeddingModelKeys(ctx context.Context, kb
resolvedKeys[ref] = ref.ModelID
continue
}
- resolvedKeys[ref] = model.Name + "|" + model.Parameters.BaseURL
+ resolvedKeys[ref] = fmt.Sprintf("%s|%s|%d", model.Name, model.Parameters.BaseURL,
+ model.Parameters.EmbeddingParameters.Dimension)
}
result := make(map[string]string, len(kbs))
diff --git a/internal/application/service/knowledgebase_search_embedding_dimension_test.go b/internal/application/service/knowledgebase_search_embedding_dimension_test.go
new file mode 100644
index 000000000..5157d70fb
--- /dev/null
+++ b/internal/application/service/knowledgebase_search_embedding_dimension_test.go
@@ -0,0 +1,155 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+
+ chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestResolveEmbeddingModelKeys_Dimensions(t *testing.T) {
+ t.Parallel()
+
+ models := make(map[string]*types.Model)
+ for id, dimension := range map[string]int{"full": 1536, "short": 512, "shared": 1536} {
+ model := buildModel(id, "text-embedding-3-small", "https://embedding.example/v1")
+ model.Parameters.EmbeddingParameters = types.EmbeddingParameters{
+ Dimension: dimension,
+ SupportsDimensionOverride: true,
+ }
+ models[id] = model
+ }
+ svc := newKBSvcForValidate(&fakeModelSvcForKeys{byID: models})
+ keys := svc.ResolveEmbeddingModelKeys(context.Background(), []*types.KnowledgeBase{
+ {ID: "kb-full", EmbeddingModelID: "full", TenantID: 1},
+ {ID: "kb-short", EmbeddingModelID: "short", TenantID: 1},
+ {ID: "kb-shared", EmbeddingModelID: "shared", TenantID: 2},
+ })
+
+ require.Len(t, keys, 3)
+ assert.NotEqual(t, keys["kb-full"], keys["kb-short"],
+ "different vector widths must not share a precomputed query embedding")
+ assert.Equal(t, keys["kb-full"], keys["kb-shared"],
+ "compatible cross-tenant knowledge bases should still reuse the query embedding")
+}
+
+func TestValidateSameEmbeddingModel_Dimensions(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ dimensions [2]int
+ wantError bool
+ }{
+ {name: "different widths", dimensions: [2]int{1536, 512}, wantError: true},
+ {name: "same width", dimensions: [2]int{1536, 1536}},
+ {name: "unknown and explicit width", dimensions: [2]int{0, 512}, wantError: true},
+ {name: "legacy unspecified widths", dimensions: [2]int{0, 0}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ models := make(map[string]*types.Model)
+ for i, id := range []string{"model-a", "model-b"} {
+ model := buildModel(id, "text-embedding-3-small", "https://embedding.example/v1")
+ model.Parameters.EmbeddingParameters = types.EmbeddingParameters{
+ Dimension: tc.dimensions[i],
+ SupportsDimensionOverride: true,
+ }
+ models[id] = model
+ }
+ svc := newKBSvcForValidate(&fakeModelSvcForKeys{byID: models})
+ err := svc.validateSameEmbeddingModel(context.Background(), []*types.KnowledgeBase{
+ {ID: "kb-a", EmbeddingModelID: "model-a", TenantID: 1},
+ {ID: "kb-b", EmbeddingModelID: "model-b", TenantID: 2},
+ })
+ if !tc.wantError {
+ require.NoError(t, err)
+ return
+ }
+ require.Error(t, err, "incompatible vector spaces must be rejected before retrieval")
+ app, ok := apperrors.IsAppError(err)
+ require.True(t, ok, "expected AppError, got %T", err)
+ assert.Equal(t, apperrors.ErrBadRequest, app.Code)
+ })
+ }
+}
+
+// Keep the real model-key resolution while recording the vector passed to
+// each KB. This exercises the chat pipeline's grouping and embedding reuse,
+// rather than assuming a different key is enough to prevent missing recall.
+type dimensionSearchService struct {
+ interfaces.KnowledgeBaseService
+ kbs []*types.KnowledgeBase
+ dimensions map[string]int
+ mu sync.Mutex
+ embedCalls int
+}
+
+func (s *dimensionSearchService) GetKnowledgeBasesByIDsOnly(
+ context.Context, []string,
+) ([]*types.KnowledgeBase, error) {
+ return s.kbs, nil
+}
+
+func (s *dimensionSearchService) GetQueryEmbedding(_ context.Context, kbID, _ string) ([]float32, error) {
+ s.mu.Lock()
+ s.embedCalls++
+ s.mu.Unlock()
+ return make([]float32, s.dimensions[kbID]), nil
+}
+
+func (s *dimensionSearchService) HybridSearch(
+ _ context.Context, _ string, params types.SearchParams,
+) ([]*types.SearchResult, error) {
+ var results []*types.SearchResult
+ for _, id := range params.KnowledgeBaseIDs {
+ if len(params.QueryEmbedding) != s.dimensions[id] {
+ return nil, fmt.Errorf("query has %d dimensions, knowledge base %s expects %d",
+ len(params.QueryEmbedding), id, s.dimensions[id])
+ }
+ results = append(results, &types.SearchResult{ID: "chunk-" + id, KnowledgeBaseID: id})
+ }
+ return results, nil
+}
+
+func TestSearchPipeline_GroupsByEmbeddingDimension(t *testing.T) {
+ t.Parallel()
+
+ models := make(map[string]*types.Model)
+ svc := &dimensionSearchService{dimensions: map[string]int{"kb-full": 1536, "kb-short": 512, "kb-shared": 1536}}
+ var targets types.SearchTargets
+ for _, id := range []string{"kb-full", "kb-short", "kb-shared"} {
+ model := buildModel(id, "text-embedding-3-small", "https://embedding.example/v1")
+ model.Parameters.EmbeddingParameters.Dimension = svc.dimensions[id]
+ model.Parameters.EmbeddingParameters.SupportsDimensionOverride = true
+ models[id] = model
+ tenantID := uint64(1)
+ if id == "kb-shared" {
+ tenantID = 2
+ }
+ svc.kbs = append(svc.kbs, &types.KnowledgeBase{ID: id, EmbeddingModelID: id, TenantID: tenantID})
+ targets = append(targets, &types.SearchTarget{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: id})
+ }
+ svc.KnowledgeBaseService = newKBSvcForValidate(&fakeModelSvcForKeys{byID: models})
+ plugin := chatpipeline.NewPluginSearch(chatpipeline.NewEventManager(), svc, nil, nil, nil, nil, nil, nil, nil, nil)
+ chat := &types.ChatManage{
+ PipelineRequest: types.PipelineRequest{SearchTargets: targets, EmbeddingTopK: 10},
+ PipelineState: types.PipelineState{RewriteQuery: "a shared question"},
+ }
+ err := plugin.OnEvent(context.Background(), types.CHUNK_SEARCH, chat, func() *chatpipeline.PluginError {
+ return nil
+ })
+ require.Nil(t, err)
+ require.Len(t, chat.SearchResult, 3, "every KB must be searched in its configured vector space")
+ assert.ElementsMatch(t, []string{"chunk-kb-full", "chunk-kb-short", "chunk-kb-shared"},
+ []string{chat.SearchResult[0].ID, chat.SearchResult[1].ID, chat.SearchResult[2].ID})
+ assert.Equal(t, 2, svc.embedCalls, "same-width KBs should share one embedding even across tenants")
+}
diff --git a/internal/types/interfaces/knowledgebase.go b/internal/types/interfaces/knowledgebase.go
index a386b7a86..f89061185 100644
--- a/internal/types/interfaces/knowledgebase.go
+++ b/internal/types/interfaces/knowledgebase.go
@@ -104,12 +104,14 @@ type KnowledgeBaseService interface {
// GetQueryEmbedding computes the query embedding using the embedding model
// associated with the given knowledge base. This allows callers to pre-compute
- // and reuse embeddings across multiple KBs that share the same model.
+ // and reuse embeddings across multiple KBs that share the same model and
+ // vector space.
GetQueryEmbedding(ctx context.Context, kbID string, queryText string) ([]float32, error)
// ResolveEmbeddingModelKeys resolves embedding model IDs to their actual
- // model identity key (name + endpoint). KBs using the same underlying model
- // across different tenants will share the same key, enabling optimal grouping.
+ // model identity key (name + endpoint + configured vector dimension). KBs
+ // using the same underlying model and vector space across different tenants
+ // will share the same key, enabling optimal grouping.
// Returns a map from KB ID to model identity key string.
ResolveEmbeddingModelKeys(ctx context.Context, kbs []*types.KnowledgeBase) map[string]string