refactor(retriever): introduce factory for KB-scoped retrieve engine resolution
Extracts the 25 repeated NewCompositeRetrieveEngine call sites across seven services into two factory functions with tenant-ownership verification: CreateRetrieveEngineForKB (synchronous) and CreateRetrieveEngineFromPayload (async task handlers). Promotes GetByStoreID from concrete-only to interfaces.RetrieveEngineRegistry. Extends KBDeletePayload / IndexDeletePayload with an omitempty VectorStoreID snapshot. Design highlights - Factory verifies tenant ownership of the resolved store (defense-in-depth) so a gap in PR3 validation or a tampered Asynq payload cannot cross tenants. Cross-tenant attempts return ErrVectorStoreForbidden with a structured log entry. - Sentinel errors (ErrTenantInfoMissing, ErrVectorStoreNotFound, ErrVectorStoreForbidden) let async handlers classify non-retryable failures as asynq.SkipRetry. - nil and empty-string pointers for vectorStoreID normalize to "unbound" so callers never send an empty UUID to GetByStoreID. - resolveBoundEngine constructs engineInfos directly (with slices.Clone of Support()) instead of going through NewCompositeRetrieveEngine. The latter only reads from the byEngineType map and cannot reach DB stores in byStoreID -- multiple stores can share the same engine type. Unbound fallbacks still reuse NewCompositeRetrieveEngine so the tenant effective-engines path is byte-for-byte unchanged. - DeleteKnowledgeBase now reads the KB before soft-delete so the enqueued KBDeletePayload carries a VectorStoreID snapshot; once the row is soft-deleted GORM's default scope hides it. Cost: +1 SELECT per KB-delete request (a rare admin operation). - enqueueIndexDeleteTask gains a vectorStoreID *string parameter that the single caller (tag.go) populates from the owning KB. The worker (ProcessIndexDelete) validates ownership via the factory. - cleanupKnowledgeResources loads the KB so bound-store cleanup routes correctly. If the load fails it warns and falls back to tenant effective engines; orphan vectors become observable in logs instead of disappearing silently. - DeleteKnowledges (batch) stays on the tenant effective-engines path -- batches can span stores and multi-store fan-out is PR4 scope. Noted inline. Merge safety All knowledge bases have VectorStoreID = NULL at merge time (introduced nullable in PR1, Tencent/WeKnora#994). Every factory call falls back to NewCompositeRetrieveEngine(registry, tenantInfo.GetEffectiveEngines()), which is the existing code path for these KBs. Async payloads from before this change decode to VectorStoreID = nil (omitempty) and take the same fallback. Testing - go build ./... - go vet ./... - go test -race -count=1 ./internal/application/service/retriever/... covers unbound (nil/empty), bound, cross-tenant, unregistered store, ownership infra error, legacy payload shapes (missing field/null/ empty string/nil), tampered payload, and parallel invocation. - grep -r NewCompositeRetrieveEngine internal/application/service returns zero results outside factory.go/composite.go. Refs: Part of Tencent/WeKnora#993. Depends on Tencent/WeKnora#994.
This commit is contained in:
@@ -194,8 +194,18 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
}
|
||||
}
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
// Route CopyIndices via the source KB's bound store. This function does
|
||||
// not handle cross-store copies — embeddings written by different
|
||||
// VectorStore backends are not bit-compatible, so callers that allow
|
||||
// source/target KBs to bind to different stores must perform their own
|
||||
// cross-store migration before invoking this.
|
||||
var sourceStoreID *string
|
||||
if srcKB, loadErr := s.kbService.GetKnowledgeBaseByID(ctx, src.KnowledgeBaseID); loadErr == nil && srcKB != nil {
|
||||
sourceStoreID = srcKB.VectorStoreID
|
||||
}
|
||||
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
|
||||
ctx, s.retrieveEngine, s.ownership, tenantID, sourceStoreID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -441,9 +451,15 @@ func (s *knowledgeService) cloneFAQKnowledgeBase(
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get tenant info and initialize retrieve engine
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||
// Route the FAQ clone through the source KB's bound store. Same
|
||||
// constraint as CloneChunk: callers must ensure source and target share
|
||||
// the same VectorStore (cross-store FAQ clone is not handled here).
|
||||
var sourceStoreID *string
|
||||
if srcKB != nil {
|
||||
sourceStoreID = srcKB.VectorStoreID
|
||||
}
|
||||
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
|
||||
ctx, s.retrieveEngine, s.ownership, types.MustTenantIDFromContext(ctx), sourceStoreID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
|
||||
handleError(progress, err, "Failed to initialize retrieve engine")
|
||||
@@ -856,7 +872,6 @@ func (s *knowledgeService) moveKnowledgeReuseVectors(
|
||||
sourceKB, targetKB *types.KnowledgeBase,
|
||||
) error {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
|
||||
// 1. Get old chunk IDs for vector index copy mapping
|
||||
oldChunks, err := s.chunkRepo.ListChunksByKnowledgeID(ctx, tenantID, knowledge.ID)
|
||||
@@ -872,7 +887,16 @@ func (s *knowledgeService) moveKnowledgeReuseVectors(
|
||||
|
||||
// 2. Copy vector indices from source KB to target KB
|
||||
if len(chunkIDMapping) > 0 && knowledge.EmbeddingModelID != "" {
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||
// reuse_vectors mode copies index entries directly between KBs, which
|
||||
// only works inside the same VectorStore backend. Route through the
|
||||
// source KB's binding; callers must reject cross-store moves before
|
||||
// landing here.
|
||||
var sourceStoreID *string
|
||||
if sourceKB != nil {
|
||||
sourceStoreID = sourceKB.VectorStoreID
|
||||
}
|
||||
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
|
||||
ctx, s.retrieveEngine, s.ownership, tenantID, sourceStoreID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to init retrieve engine: %w", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user