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:
@@ -27,6 +27,7 @@ type knowledgeBaseService struct {
|
||||
kbShareService interfaces.KBShareService
|
||||
modelService interfaces.ModelService
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
ownership retriever.TenantStoreOwnership
|
||||
tenantRepo interfaces.TenantRepository
|
||||
fileSvc interfaces.FileService
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
@@ -41,6 +42,7 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
kbShareService interfaces.KBShareService,
|
||||
modelService interfaces.ModelService,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
ownership retriever.TenantStoreOwnership,
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
fileSvc interfaces.FileService,
|
||||
graphEngine interfaces.RetrieveGraphRepository,
|
||||
@@ -54,6 +56,7 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
kbShareService: kbShareService,
|
||||
modelService: modelService,
|
||||
retrieveEngine: retrieveEngine,
|
||||
ownership: ownership,
|
||||
tenantRepo: tenantRepo,
|
||||
fileSvc: fileSvc,
|
||||
graphEngine: graphEngine,
|
||||
@@ -364,9 +367,24 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
tenantInfo, _ := types.TenantInfoFromContext(ctx)
|
||||
|
||||
// Load the KB before soft-delete so we can snapshot its VectorStoreID
|
||||
// into the async cleanup payload. GORM's soft-delete filter hides the
|
||||
// row from subsequent reads, so this read must happen first.
|
||||
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
})
|
||||
return err
|
||||
}
|
||||
var vectorStoreIDSnapshot *string
|
||||
if kb != nil {
|
||||
vectorStoreIDSnapshot = kb.VectorStoreID
|
||||
}
|
||||
|
||||
// Step 1: Delete the knowledge base record first (mark as deleted)
|
||||
logger.Infof(ctx, "Deleting knowledge base from database")
|
||||
err := s.repo.DeleteKnowledgeBase(ctx, id)
|
||||
err = s.repo.DeleteKnowledgeBase(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
@@ -384,6 +402,7 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: id,
|
||||
EffectiveEngines: tenantInfo.GetEffectiveEngines(),
|
||||
VectorStoreID: vectorStoreIDSnapshot, // snapshot taken before soft-delete
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
|
||||
@@ -444,12 +463,27 @@ func (s *knowledgeBaseService) ProcessKBDelete(ctx context.Context, t *asynq.Tas
|
||||
|
||||
logger.Infof(ctx, "Deleting all knowledge entries and their resources")
|
||||
|
||||
// Delete embeddings from vector store
|
||||
// Delete embeddings from vector store.
|
||||
// Resolve the engine via the factory, using the VectorStoreID captured
|
||||
// at enqueue time (may be nil → falls back to payload.EffectiveEngines).
|
||||
// If the payload references a store no longer owned/registered
|
||||
// (e.g. tampered queue entry or a store that was deleted while the
|
||||
// task sat in the queue), the factory returns a sentinel and we
|
||||
// SkipRetry to avoid burning retries on an unrecoverable situation.
|
||||
logger.Infof(ctx, "Deleting embeddings from vector store")
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
|
||||
retrieveEngine, err := retriever.CreateRetrieveEngineFromPayload(
|
||||
ctx,
|
||||
s.retrieveEngine,
|
||||
s.ownership,
|
||||
payload.TenantID,
|
||||
payload.EffectiveEngines,
|
||||
payload.VectorStoreID,
|
||||
)
|
||||
if errors.Is(err, retriever.ErrVectorStoreForbidden) ||
|
||||
errors.Is(err, retriever.ErrVectorStoreNotFound) {
|
||||
logger.Errorf(ctx, "KB delete task aborted: %v (tenant=%d, kb=%s)", err, payload.TenantID, payload.KnowledgeBaseID)
|
||||
return asynq.SkipRetry
|
||||
}
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to create retrieve engine: %v", err)
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user