feat(knowledge-base): validate vector store bindings on create, copy, and delete

Wires KnowledgeBase.VectorStoreID and the ownership-aware retrieve factory
into the user-facing knowledge-base lifecycle:

- POST /knowledge-bases validates the requested vector_store_id against
  the caller's tenant scope and the engine registry. New error codes
  ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201)
  distinguish the typed branches without echoing UUIDs to the client.
- GET / POST / PUT / PUT-pin responses embed the bound store's display
  metadata (name, source, engine_type, status) without exposing any
  connection credentials. Cross-tenant shared KBs receive a suppressed
  payload (vector_store_id stripped, source="shared") so operator-chosen
  store names cannot be enumerated across tenants.
- POST /knowledge-bases/copy synchronously rejects clones whose target
  has a different embedding model or vector store, before the async
  clone task is enqueued. The async clone worker re-applies the same
  checks for defense in depth.
- DELETE /vector-stores/:id refuses to remove a store with bound KBs,
  inside a transaction that row-locks the store on PostgreSQL and
  serializes via WAL on SQLite. unregister-from-registry is wrapped in
  defer/recover so a panic surfaces as a structured warning instead of
  silently leaking a stale engine.
- vector_store_id is immutable after creation. The GORM <-:create tag
  blocks every ORM update path; the service-layer DTO omits the field
  entirely; a reflection-based regression test catches any future
  maintainer who adds it back to either layer.
- Empty-string vector_store_id is normalized to nil at both the create
  path and inside SharesStoreWith, so rows persisted by callers that
  did not run Normalize first cannot trip false same-store comparisons.

Part of #993. Depends on #994 and #1310.
This commit is contained in:
ochan.kwon
2026-05-18 10:10:01 +09:00
committed by lyingbug
parent 7611d59d71
commit 0e8de6192c
23 changed files with 2420 additions and 164 deletions
@@ -121,3 +121,30 @@ func (r *knowledgeBaseRepository) UpdateKnowledgeBase(ctx context.Context, kb *t
func (r *knowledgeBaseRepository) DeleteKnowledgeBase(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.KnowledgeBase{}).Error
}
// CountByVectorStoreID counts active knowledge bases that are bound to the
// given vector store within a tenant scope.
//
// Soft-delete filter is applied automatically by GORM because KnowledgeBase
// has a gorm.DeletedAt column — we deliberately do not add an explicit
// `deleted_at IS NULL` predicate to keep the single source of truth on the
// auto-scope.
//
// Pass db == nil to use the repository's default db handle; pass a *gorm.DB
// bound to a transaction (e.g., from db.Transaction) to share the same
// write-lock context as the caller. Query column order matches the
// composite index idx_knowledge_bases_tenant_vector_store(tenant_id,
// vector_store_id).
func (r *knowledgeBaseRepository) CountByVectorStoreID(
ctx context.Context, db *gorm.DB, tenantID uint64, storeID string,
) (int64, error) {
if db == nil {
db = r.db
}
var count int64
err := db.WithContext(ctx).
Model(&types.KnowledgeBase{}).
Where("tenant_id = ? AND vector_store_id = ?", tenantID, storeID).
Count(&count).Error
return count, err
}
@@ -217,3 +217,92 @@ func TestKnowledgeBase_VectorStoreID_Roundtrip_Value(t *testing.T) {
require.NotNil(t, reloaded.VectorStoreID)
assert.Equal(t, "store-uuid-42", *reloaded.VectorStoreID)
}
// TestCountByVectorStoreID covers the binding-count helper used by the
// VectorStore delete guard. Verifies tenant scoping, the GORM auto soft-delete
// filter (no explicit `deleted_at IS NULL` literal in the query), and the
// edge case where a row stores an empty-string vector_store_id (SQLite
// treats "" and NULL differently — we want both excluded from a non-empty
// storeID lookup).
func TestCountByVectorStoreID(t *testing.T) {
db := setupKBTestDB(t)
repo := &knowledgeBaseRepository{db: db}
ctx := t.Context()
// Tenant 1: two active rows bound to store-A, one row bound to store-B.
kbA1 := makeKB(kbStrPtr("store-A"))
kbA2 := makeKB(kbStrPtr("store-A"))
kbB := makeKB(kbStrPtr("store-B"))
require.NoError(t, db.Create(kbA1).Error)
require.NoError(t, db.Create(kbA2).Error)
require.NoError(t, db.Create(kbB).Error)
// Tenant 2: one row bound to store-A (must not count for tenant 1).
kbCross := makeKB(kbStrPtr("store-A"))
kbCross.TenantID = 2
require.NoError(t, db.Create(kbCross).Error)
// Soft-deleted row bound to store-A (must not count under auto-scope).
kbDeleted := makeKB(kbStrPtr("store-A"))
require.NoError(t, db.Create(kbDeleted).Error)
require.NoError(t, db.Delete(kbDeleted).Error)
// Row with empty-string vector_store_id (regression — sqlite quirk).
kbEmpty := makeKB(kbStrPtr(""))
require.NoError(t, db.Create(kbEmpty).Error)
t.Run("nil db handle uses default", func(t *testing.T) {
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "store-A")
require.NoError(t, err)
assert.Equal(t, int64(2), count, "tenant 1 has 2 active KBs on store-A")
})
t.Run("explicit db handle works the same", func(t *testing.T) {
count, err := repo.CountByVectorStoreID(ctx, db, 1, "store-A")
require.NoError(t, err)
assert.Equal(t, int64(2), count)
})
t.Run("different store id", func(t *testing.T) {
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "store-B")
require.NoError(t, err)
assert.Equal(t, int64(1), count)
})
t.Run("unknown store id returns zero", func(t *testing.T) {
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "store-XYZ")
require.NoError(t, err)
assert.Equal(t, int64(0), count)
})
t.Run("different tenant", func(t *testing.T) {
count, err := repo.CountByVectorStoreID(ctx, nil, 2, "store-A")
require.NoError(t, err)
assert.Equal(t, int64(1), count)
})
t.Run("non-empty lookup does not match empty-string rows", func(t *testing.T) {
count, err := repo.CountByVectorStoreID(ctx, nil, 1, "")
require.NoError(t, err)
// Only the empty-string-vsid row matches "" exactly (SQLite quirk —
// "" is not NULL). The non-empty rows do not.
assert.Equal(t, int64(1), count, "empty-string lookup matches only the empty row")
})
t.Run("shared tx handle returns same result twice", func(t *testing.T) {
err := db.Transaction(func(tx *gorm.DB) error {
c1, err := repo.CountByVectorStoreID(ctx, tx, 1, "store-A")
if err != nil {
return err
}
c2, err := repo.CountByVectorStoreID(ctx, tx, 1, "store-A")
if err != nil {
return err
}
assert.Equal(t, c1, c2, "two reads within the same tx must agree")
assert.Equal(t, int64(2), c1)
return nil
})
require.NoError(t, err)
})
}
+132 -2
View File
@@ -7,10 +7,12 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
"github.com/hibiken/asynq"
)
@@ -74,7 +76,12 @@ func (s *knowledgeBaseService) GetRepository() interfaces.KnowledgeBaseRepositor
return s.repo
}
// CreateKnowledgeBase creates a new knowledge base
// CreateKnowledgeBase creates a new knowledge base.
//
// When VectorStoreID is set, the binding is validated against the caller's
// tenant scope and the engine registry before persisting. A nil or
// empty-string VectorStoreID is normalized to nil ("use the tenant's
// effective engines") to match the retrieve-engine factory's pre-condition.
func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
kb *types.KnowledgeBase,
) (*types.KnowledgeBase, error) {
@@ -87,6 +94,22 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
kb.UpdatedAt = time.Now()
kb.EnsureDefaults()
// Fold empty-string vector_store_id into nil so this path and the
// retrieve-engine factory's pre-condition share a single representation.
wasEmpty := kb.VectorStoreID != nil && *kb.VectorStoreID == ""
kb.Normalize()
if wasEmpty {
logger.Debugf(ctx,
"[kb.create] empty vector_store_id normalized to nil for tenant=%d",
kb.TenantID)
}
if kb.HasVectorStore() {
if err := s.validateVectorStoreBinding(ctx, kb.TenantID, *kb.VectorStoreID); err != nil {
return nil, err
}
}
logger.Infof(ctx, "Creating knowledge base, ID: %s, tenant ID: %d, name: %s", kb.ID, kb.TenantID, kb.Name)
if err := s.repo.CreateKnowledgeBase(ctx, kb); err != nil {
@@ -101,6 +124,62 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
return kb, nil
}
// validateVectorStoreBinding routes through retriever.VerifyBinding so the
// ownership + registry sentinel hierarchy stays the single source of truth.
// The service layer's responsibility is to:
//
// 1. fast-reject malformed UUIDs (cheap pre-flight that also avoids a DB
// round trip for type-confusion inputs like "' OR 1=1 --"),
// 2. translate retriever sentinels into user-facing AppErrors with
// generic messages and the typed error codes.
//
// UUID parse failures map to the same "vector store not found" message as
// cross-tenant attempts to avoid an enumeration oracle that distinguishes
// "malformed input" from "non-existent UUID".
func (s *knowledgeBaseService) validateVectorStoreBinding(
ctx context.Context, tenantID uint64, storeID string,
) error {
sanitized := secutils.SanitizeForLog(storeID)
if _, err := uuid.Parse(storeID); err != nil {
logger.WarnWithFields(ctx, logger.Fields{
"tenant_id": tenantID,
"store_id": sanitized,
"reason": "malformed vector_store_id",
}, "[kb.create] vector store id is not a valid UUID")
return apperrors.NewVectorStoreBindingInvalidError("vector store not found")
}
switch err := retriever.VerifyBinding(
ctx, s.retrieveEngine, s.ownership, tenantID, storeID,
); {
case err == nil:
return nil
case errors.Is(err, retriever.ErrVectorStoreForbidden):
logger.WarnWithFields(ctx, logger.Fields{
"tenant_id": tenantID,
"store_id": sanitized,
"reason": "cross-tenant or unknown store",
}, "[kb.create] vector store not owned by tenant")
return apperrors.NewVectorStoreBindingInvalidError("vector store not found")
case errors.Is(err, retriever.ErrVectorStoreNotFound):
logger.WarnWithFields(ctx, logger.Fields{
"tenant_id": tenantID,
"store_id": sanitized,
"reason": "store registered in DB but missing in registry",
}, "[kb.create] vector store currently unavailable")
return apperrors.NewVectorStoreUnavailableError(
"vector store is currently unavailable; check its connection configuration")
default:
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
"store_id": sanitized,
"reason": "binding verification failed",
})
return apperrors.NewInternalServerError("failed to verify vector store binding")
}
}
// GetKnowledgeBaseByID retrieves a knowledge base by its ID
func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
if id == "" {
@@ -266,7 +345,23 @@ func (s *knowledgeBaseService) FillKnowledgeBaseCounts(ctx context.Context, kb *
return nil
}
// UpdateKnowledgeBase updates a knowledge base's properties
// UpdateKnowledgeBase updates a knowledge base's mutable properties.
//
// IMPORTANT — vector_store_id immutability contract:
// The vector_store_id binding is deliberately not accepted by this method.
// Two layers enforce immutability:
//
// 1. ORM layer: the GORM tag `<-:create` on KnowledgeBase.VectorStoreID
// makes every UPDATE path (Save / Updates / Select-Updates) a no-op for
// that column. Verified by repository/knowledgebase_sqlite_test.go.
// 2. Service layer: this method intentionally omits VectorStoreID from its
// parameter list, and the matching handler DTO UpdateKnowledgeBaseRequest
// omits the field as well. A reflection-based regression test
// (handler/knowledgebase_request_test.go) fails if either DTO field
// is added back, alerting future maintainers.
//
// Any future cross-store rebind workflow must use raw SQL through a
// dedicated repository method — the only sanctioned write path post-creation.
func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
id string,
name string,
@@ -624,6 +719,21 @@ func (s *knowledgeBaseService) SetEmbeddingModel(ctx context.Context, id string,
// CopyKnowledgeBase copies a knowledge base to a new knowledge base (shallow copy).
// Source and target must belong to the tenant in context; cross-tenant access is rejected.
//
// Defensive checks:
//
// - When dstKB != "" (clone into an existing target), the source's
// EmbeddingModelID and VectorStoreID must match the target's. Mismatched
// embedding models would silently mix incompatible vector spaces;
// mismatched vector stores would require copying physical vector data
// between stores, which is not yet supported.
// - When dstKB == "" (create a new target), VectorStoreID is copied from
// the source so the new KB shares the same physical vector index. GORM
// `<-:create` allows INSERT, so the new row is well-formed.
//
// The handler's CopyKnowledgeBase endpoint runs the same checks synchronously
// before enqueueing the async clone task, so the 400 errors here are
// defense-in-depth for the worker entry point.
func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
srcKB string, dstKB string,
) (*types.KnowledgeBase, *types.KnowledgeBase, error) {
@@ -642,12 +752,31 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
if err != nil {
return nil, nil, err
}
// Defense 1: embedding model must match. Mixing incompatible
// vector spaces would produce semantically broken search results.
if sourceKB.EmbeddingModelID != targetKB.EmbeddingModelID {
return nil, nil, apperrors.NewBadRequestError(
"source and target knowledge bases use different embedding models; " +
"clone into a target with the same embedding model")
}
// Defense 2: vector store binding must match. Cross-store cloning
// would require copying physical vector data between stores.
// (both nil → equal; both same UUID → equal; otherwise → rejected)
if !sourceKB.SharesStoreWith(targetKB) {
return nil, nil, apperrors.NewBadRequestError(
"source and target knowledge bases are bound to different vector stores; " +
"cross-store cloning is not yet supported")
}
} else {
var faqConfig *types.FAQConfig
if sourceKB.FAQConfig != nil {
cfg := *sourceKB.FAQConfig
faqConfig = &cfg
}
// Preserve VectorStoreID so the cloned KB lands on the same
// physical index. GORM `<-:create` permits the value at INSERT.
targetKB = &types.KnowledgeBase{
ID: uuid.New().String(),
Name: sourceKB.Name,
@@ -662,6 +791,7 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
StorageProviderConfig: sourceKB.StorageProviderConfig,
StorageConfig: sourceKB.StorageConfig,
FAQConfig: faqConfig,
VectorStoreID: sourceKB.VectorStoreID,
}
targetKB.EnsureDefaults()
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
@@ -0,0 +1,330 @@
package service
import (
"context"
stderrors "errors"
"testing"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
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"
"gorm.io/gorm"
)
// ---------------------------------------------------------------------------
// Vector-store binding service-level tests
//
// Coverage:
// - CreateKnowledgeBase: vector_store_id validation matrix (Normalize,
// malformed UUID, sentinel wrap, error code distinction).
// - CopyKnowledgeBase: embedding-model + store defenses, new-KB
// VectorStoreID copy.
//
// These are pure logic tests that drive `validateVectorStoreBinding` and
// `CopyKnowledgeBase` through stubbed dependencies — no DB I/O.
// ---------------------------------------------------------------------------
// validKBStoreUUID is a well-formed UUID used to drive the validation
// branches that survive the uuid.Parse() pre-flight.
const validKBStoreUUID = "0193b8a0-1111-7000-8000-000000000001"
type fakeOwnership struct {
owned map[string]uint64 // storeID -> tenantID owner
err error
}
func (f *fakeOwnership) StoreOwnedBy(_ context.Context, storeID string, tenantID uint64) (bool, error) {
if f.err != nil {
return false, f.err
}
owner, ok := f.owned[storeID]
return ok && owner == tenantID, nil
}
type fakeRegistry struct {
registered map[string]struct{}
}
func (f *fakeRegistry) Register(_ interfaces.RetrieveEngineService) error { return nil }
func (f *fakeRegistry) GetRetrieveEngineService(_ types.RetrieverEngineType) (interfaces.RetrieveEngineService, error) {
return nil, nil
}
func (f *fakeRegistry) GetAllRetrieveEngineServices() []interfaces.RetrieveEngineService { return nil }
func (f *fakeRegistry) GetByStoreID(storeID string) (interfaces.RetrieveEngineService, error) {
if _, ok := f.registered[storeID]; ok {
return nil, nil
}
return nil, stderrors.New("not registered")
}
// fakeKBRepo is the smallest KnowledgeBaseRepository needed by
// CreateKnowledgeBase + CopyKnowledgeBase tests. It stores rows in a map
// keyed by ID. No tenant scoping is applied — the tested paths already
// enforce that explicitly.
type fakeKBRepo struct {
rows map[string]*types.KnowledgeBase
createErr error
}
func newFakeKBRepo() *fakeKBRepo { return &fakeKBRepo{rows: map[string]*types.KnowledgeBase{}} }
func (r *fakeKBRepo) CreateKnowledgeBase(_ context.Context, kb *types.KnowledgeBase) error {
if r.createErr != nil {
return r.createErr
}
r.rows[kb.ID] = kb
return nil
}
func (r *fakeKBRepo) GetKnowledgeBaseByID(_ context.Context, id string) (*types.KnowledgeBase, error) {
return r.rows[id], nil
}
func (r *fakeKBRepo) GetKnowledgeBaseByIDAndTenant(_ context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error) {
kb := r.rows[id]
if kb == nil || kb.TenantID != tenantID {
return nil, stderrors.New("not found")
}
return kb, nil
}
func (r *fakeKBRepo) GetKnowledgeBaseByIDs(_ context.Context, _ []string) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (r *fakeKBRepo) ListKnowledgeBases(_ context.Context) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (r *fakeKBRepo) ListKnowledgeBasesByTenantID(_ context.Context, _ uint64) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (r *fakeKBRepo) UpdateKnowledgeBase(_ context.Context, _ *types.KnowledgeBase) error {
return nil
}
func (r *fakeKBRepo) DeleteKnowledgeBase(_ context.Context, _ string) error { return nil }
func (r *fakeKBRepo) TogglePinKnowledgeBase(_ context.Context, _ string, _ uint64) (*types.KnowledgeBase, error) {
return nil, nil
}
func (r *fakeKBRepo) CountByVectorStoreID(_ context.Context, _ *gorm.DB, _ uint64, _ string) (int64, error) {
return 0, nil
}
// Force compile-time conformance check so any future interface change
// surfaces as a build error here rather than at usage site.
var _ interfaces.KnowledgeBaseRepository = (*fakeKBRepo)(nil)
func newPR3KBService(repo *fakeKBRepo, registry *fakeRegistry, ownership *fakeOwnership) *knowledgeBaseService {
return &knowledgeBaseService{
repo: repo,
retrieveEngine: registry,
ownership: ownership,
}
}
func ctxWithTenant(tenantID uint64) context.Context {
return context.WithValue(context.Background(), types.TenantIDContextKey, tenantID)
}
// ---------------------------------------------------------------------------
// CreateKnowledgeBase — vector_store_id binding validation matrix
// ---------------------------------------------------------------------------
func TestCreateKnowledgeBase_VectorStoreBinding(t *testing.T) {
registered := map[string]struct{}{validKBStoreUUID: {}}
t.Run("nil vector_store_id persists unchanged", func(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo,
&fakeRegistry{registered: registered},
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 1}},
)
kb, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb"})
require.NoError(t, err)
assert.Nil(t, kb.VectorStoreID)
assert.Len(t, repo.rows, 1)
})
t.Run("empty string vector_store_id normalizes to nil", func(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo,
&fakeRegistry{registered: registered},
&fakeOwnership{},
)
empty := ""
kb, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &empty})
require.NoError(t, err)
assert.Nil(t, kb.VectorStoreID)
})
t.Run("malformed UUID rejected with BindingInvalid code", func(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo,
&fakeRegistry{registered: registered},
&fakeOwnership{},
)
bad := "not-a-uuid"
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &bad})
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrVectorStoreBindingInvalid, appErr.Code)
assert.NotContains(t, appErr.Message, bad, "UUID must not echo back")
assert.Empty(t, repo.rows, "must not persist on validation failure")
})
t.Run("valid UUID + owned + registered → persist OK", func(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo,
&fakeRegistry{registered: registered},
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 1}},
)
id := validKBStoreUUID
kb, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
require.NoError(t, err)
require.NotNil(t, kb.VectorStoreID)
assert.Equal(t, validKBStoreUUID, *kb.VectorStoreID)
})
t.Run("valid UUID + cross-tenant → BindingInvalid", func(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo,
&fakeRegistry{registered: registered},
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 2}}, // owned by tenant 2
)
id := validKBStoreUUID
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrVectorStoreBindingInvalid, appErr.Code)
})
t.Run("valid UUID + owned but unregistered → Unavailable", func(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo,
&fakeRegistry{registered: map[string]struct{}{}}, // not registered
&fakeOwnership{owned: map[string]uint64{validKBStoreUUID: 1}},
)
id := validKBStoreUUID
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrVectorStoreUnavailable, appErr.Code)
})
t.Run("ownership infra error → 500", func(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo,
&fakeRegistry{registered: registered},
&fakeOwnership{err: stderrors.New("db down")},
)
id := validKBStoreUUID
_, err := svc.CreateKnowledgeBase(ctxWithTenant(1), &types.KnowledgeBase{Name: "kb", VectorStoreID: &id})
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, 500, appErr.HTTPCode)
})
// Compile-time check: the retriever sentinels still match what we expect
// in the wrapper logic. If they are ever renamed or removed, this fails
// at build time rather than silently degrading the wrap.
_ = retriever.ErrVectorStoreForbidden
_ = retriever.ErrVectorStoreNotFound
}
// ---------------------------------------------------------------------------
// CopyKnowledgeBase — embedding model + vector store defenses
// ---------------------------------------------------------------------------
func TestCopyKnowledgeBase_Defenses(t *testing.T) {
mkKB := func(id string, tenant uint64, embed string, vsid *string) *types.KnowledgeBase {
return &types.KnowledgeBase{
ID: id, Name: id, TenantID: tenant, EmbeddingModelID: embed, VectorStoreID: vsid,
}
}
storeA := "store-A"
storeB := "store-B"
t.Run("dstKB empty -> new KB inherits VectorStoreID", func(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
src, tgt, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "")
require.NoError(t, err)
require.NotNil(t, src.VectorStoreID)
require.NotNil(t, tgt.VectorStoreID)
assert.Equal(t, *src.VectorStoreID, *tgt.VectorStoreID, "M17: VectorStoreID preserved")
// Reload from fake repo and re-verify
stored := repo.rows[tgt.ID]
require.NotNil(t, stored)
require.NotNil(t, stored.VectorStoreID)
assert.Equal(t, storeA, *stored.VectorStoreID)
})
t.Run("dstKB empty + source nil VectorStoreID -> new target nil too", func(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = mkKB("src", 1, "embed-1", nil)
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
_, tgt, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "")
require.NoError(t, err)
assert.Nil(t, tgt.VectorStoreID)
})
t.Run("dstKB set + same embedding model + both nil stores -> OK", func(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = mkKB("src", 1, "embed-1", nil)
repo.rows["dst"] = mkKB("dst", 1, "embed-1", nil)
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
_, _, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "dst")
require.NoError(t, err)
})
t.Run("dstKB set + same store UUID -> OK", func(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
repo.rows["dst"] = mkKB("dst", 1, "embed-1", &storeA)
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
_, _, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "dst")
require.NoError(t, err)
})
t.Run("dstKB set + different embedding models -> 400", func(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
repo.rows["dst"] = mkKB("dst", 1, "embed-2", &storeA)
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
_, _, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "dst")
require.Error(t, err)
assert.Contains(t, err.Error(), "different embedding models")
})
t.Run("dstKB set + different stores -> 400 (no Phase number)", func(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = mkKB("src", 1, "embed-1", &storeA)
repo.rows["dst"] = mkKB("dst", 1, "embed-1", &storeB)
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
_, _, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "dst")
require.Error(t, err)
assert.Contains(t, err.Error(), "different vector stores")
assert.NotContains(t, err.Error(), "Phase 4", "internal roadmap labels must not leak to end-user error messages")
})
t.Run("dstKB set + one nil + one set -> 400", func(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = mkKB("src", 1, "embed-1", nil)
repo.rows["dst"] = mkKB("dst", 1, "embed-1", &storeA)
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
_, _, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "dst")
require.Error(t, err)
assert.Contains(t, err.Error(), "different vector stores")
})
}
@@ -45,6 +45,50 @@ type TenantStoreOwnership interface {
StoreOwnedBy(ctx context.Context, storeID string, tenantID uint64) (bool, error)
}
// VerifyBinding asserts that a non-empty storeID is owned by tenantID and
// registered in the in-memory engine registry. It encapsulates the two
// checks that gate every store-bound resolution so that callers outside
// the retriever package (notably the KB create-validation path) can reuse
// the same sentinel hierarchy instead of duplicating the logic.
//
// Resolution rules:
//
// - ownership.StoreOwnedBy returns an infrastructure error → that error
// is returned verbatim so callers can decide retry/abort.
// - ownership returns (false, nil) → ErrVectorStoreForbidden.
// - ownership returns (true, nil) + registry.GetByStoreID fails →
// ErrVectorStoreNotFound.
// - all checks succeed → nil.
//
// VerifyBinding itself never echoes the store UUID; callers MUST wrap the
// sentinels into user-facing errors at the boundary (and log the
// tenant/store pair via structured fields when appropriate).
//
// resolveBoundEngine (below) intentionally does NOT delegate to VerifyBinding
// because it also needs the resolved engine service; sharing would require
// either a second registry lookup or returning the service from VerifyBinding,
// both of which dilute the helper's single purpose. The two paths are kept
// in lockstep by the factory_test.go matrix.
func VerifyBinding(
ctx context.Context,
registry interfaces.RetrieveEngineRegistry,
ownership TenantStoreOwnership,
tenantID uint64,
storeID string,
) error {
owned, err := ownership.StoreOwnedBy(ctx, storeID, tenantID)
if err != nil {
return err
}
if !owned {
return ErrVectorStoreForbidden
}
if _, err := registry.GetByStoreID(storeID); err != nil {
return ErrVectorStoreNotFound
}
return nil
}
// CreateRetrieveEngineForKB returns a CompositeRetrieveEngine resolved from
// a KB's VectorStore binding.
//
@@ -384,6 +384,71 @@ func TestFactoryParallelInvocation(t *testing.T) {
}
}
// ---------------------------------------------------------------------------
// VerifyBinding tests — sentinel SSOT used by the KB create-validation
// path. Mirrors the branches of resolveBoundEngine without constructing an
// actual CompositeRetrieveEngine.
// ---------------------------------------------------------------------------
func TestVerifyBinding(t *testing.T) {
ctx := context.Background()
esEngine := &fakeEngine{
engineType: types.ElasticsearchRetrieverEngineType,
support: []types.RetrieverType{types.VectorRetrieverType},
}
t.Run("ownership infra error is returned verbatim", func(t *testing.T) {
registry := registryWithStores(t, nil, nil)
ownership := &fakeOwnership{err: errors.New("db boom")}
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
if err == nil || err.Error() != "db boom" {
t.Fatalf("expected verbatim infra error, got %v", err)
}
})
t.Run("not owned -> ErrVectorStoreForbidden", func(t *testing.T) {
registry := registryWithStores(t, nil, nil)
ownership := &fakeOwnership{owned: map[string]uint64{}}
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
if !errors.Is(err, ErrVectorStoreForbidden) {
t.Fatalf("expected ErrVectorStoreForbidden, got %v", err)
}
})
t.Run("owned but unregistered -> ErrVectorStoreNotFound", func(t *testing.T) {
registry := registryWithStores(t, nil, nil)
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 1}}
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
if !errors.Is(err, ErrVectorStoreNotFound) {
t.Fatalf("expected ErrVectorStoreNotFound, got %v", err)
}
})
t.Run("owned and registered -> nil", func(t *testing.T) {
registry := registryWithStores(t,
map[string]*fakeEngine{"store-A": esEngine},
nil,
)
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 1}}
if err := VerifyBinding(ctx, registry, ownership, 1, "store-A"); err != nil {
t.Fatalf("expected nil, got %v", err)
}
})
t.Run("cross-tenant returns Forbidden (not Found)", func(t *testing.T) {
// store owned by tenant 2, queried by tenant 1
registry := registryWithStores(t,
map[string]*fakeEngine{"store-A": esEngine},
nil,
)
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 2}}
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
if !errors.Is(err, ErrVectorStoreForbidden) {
t.Fatalf("expected ErrVectorStoreForbidden, got %v", err)
}
})
}
// ----- helpers -----
func strPtr(s string) *string { return &s }
+247 -15
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
stderrors "errors"
"fmt"
"os"
"time"
@@ -11,25 +12,41 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// vectorStoreService implements interfaces.VectorStoreService
type vectorStoreService struct {
repo interfaces.VectorStoreRepository
storeRegistry interfaces.StoreRegistry // for dynamic registry updates on CRUD
factory interfaces.EngineFactory // creates engine services from VectorStore config
kbRepo interfaces.KnowledgeBaseRepository // counts bound KBs for the delete guard
storeRegistry interfaces.StoreRegistry // for dynamic registry updates on CRUD
factory interfaces.EngineFactory // creates engine services from VectorStore config
db *gorm.DB // shared handle for cross-table transactions (delete guard)
envStores []types.VectorStore // env stores derived once at construction for ResolveStoreView fast path
}
// NewVectorStoreService creates a new vector store service
// NewVectorStoreService creates a new vector store service.
//
// kbRepo and db are required by the delete guard, which counts bound KBs
// inside a transaction. storeRegistry and factory are optional in tests
// (passing nil disables dynamic registration / unregistration).
func NewVectorStoreService(
repo interfaces.VectorStoreRepository,
kbRepo interfaces.KnowledgeBaseRepository,
storeRegistry interfaces.StoreRegistry,
factory interfaces.EngineFactory,
db *gorm.DB,
) interfaces.VectorStoreService {
return &vectorStoreService{
repo: repo,
kbRepo: kbRepo,
storeRegistry: storeRegistry,
factory: factory,
db: db,
// Cache the env-store derivation once at construction so per-request
// resolution does not re-read os environment variables every call.
envStores: types.BuildEnvVectorStores(os.Getenv("RETRIEVE_DRIVER"), os.Getenv),
}
}
@@ -62,8 +79,11 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto
return errors.NewConflictError("a vector store with the same endpoint and index already exists")
}
// 4. Duplicate check — env stores (pure function, no os.Getenv in types)
for _, envStore := range types.BuildEnvVectorStores(os.Getenv("RETRIEVE_DRIVER"), os.Getenv) {
// 4. Duplicate check — env stores. We re-derive on each create because
// CreateStore is a low-frequency admin action; consistency with the
// startup-cached envStores is enforced by RETRIEVE_DRIVER being read
// only at process start.
for _, envStore := range s.envStores {
if envStore.EngineType == store.EngineType &&
envStore.ConnectionConfig.GetEndpoint() == endpoint &&
envStore.IndexConfig.GetIndexNameOrDefault(store.EngineType) == indexName {
@@ -91,7 +111,7 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto
return err
}
// 6. Register in registry (best-effort; failure doesn't roll back DB).
// 7. Register in registry (best-effort; failure doesn't roll back DB).
// The store is already persisted, and will be loaded on next app restart (self-healing).
s.registerInRegistry(ctx, store)
@@ -113,22 +133,112 @@ func (s *vectorStoreService) UpdateStore(ctx context.Context, store *types.Vecto
return s.repo.Update(ctx, store)
}
// DeleteStore deletes a vector store by tenant + id.
// Phase 2: KB binding check will be added here.
// DeleteStore deletes a vector store by tenant + id, after verifying that no
// knowledge base is currently bound to it.
//
// Guard rules:
//
// 1. Run inside a transaction so that the binding count and the store
// delete are atomic with respect to other writers holding the store
// row lock. Default isolation is Read Committed; this is a write-lock
// relationship, not a "shared snapshot" relationship.
// 2. PostgreSQL: take a row-level X-lock on the vector_stores row via
// SELECT … FOR UPDATE so concurrent KB-create requests reading the
// same store row block until our transaction completes. SQLite
// serializes writes via WAL + max-open-conns=1, so the lock hint is
// skipped and we rely on the transaction boundary alone.
// 3. Count knowledge_bases rows via the shared CountByVectorStoreID
// repository method (tx-aware), which leverages the composite index
// (tenant_id, vector_store_id). GORM auto-applies the soft-delete
// scope — no explicit deleted_at predicate is needed.
// 4. After commit, unregister from the in-memory registry. Wrapped in
// defer/recover so a panic in UnregisterByStoreID surfaces as a
// structured warning instead of silently leaking the stale engine.
//
// Race window remaining:
//
// A narrow window exists between CreateKnowledgeBase's binding check and
// the INSERT — a KB can be created against a store that is simultaneously
// being deleted. The retrieve-engine factory then rejects searches with
// the ErrVectorStoreForbidden / NotFound sentinel; the KB response view
// surfaces the condition through vector_store_status="unavailable" so the
// UI can guide recovery (admin tool / rebind / KB recreation).
//
// Multi-replica registry staleness:
//
// The in-memory registry is per-process. After a successful commit +
// UnregisterByStoreID on this replica, sibling replicas continue serving
// the engine from their own caches until process restart. This method
// does not broadcast invalidation across the cluster.
func (s *vectorStoreService) DeleteStore(ctx context.Context, tenantID uint64, id string) error {
if err := s.repo.Delete(ctx, tenantID, id); err != nil {
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// tx inherits ctx from WithContext above; no need to re-attach.
// 1. Lock the store row (PG row-level X-lock; skipped on SQLite).
var store types.VectorStore
q := tx.Where("id = ? AND tenant_id = ?", id, tenantID)
if s.isPostgres(tx) {
q = q.Clauses(clause.Locking{Strength: "UPDATE"})
}
if err := q.First(&store).Error; err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
return errors.NewNotFoundError("vector store not found")
}
return err
}
// 2. Binding count under the same write-lock boundary.
count, err := s.kbRepo.CountByVectorStoreID(ctx, tx, tenantID, id)
if err != nil {
return err
}
if count > 0 {
return errors.NewBadRequestError(
fmt.Sprintf(
"vector store still has %d knowledge base(s) bound to it; "+
"unbind or delete them before removing the store", count))
}
// 3. Soft-delete (gorm.DeletedAt fills automatically).
return tx.Delete(&store).Error
})
if err != nil {
return err
}
// Unregister from registry (idempotent)
if s.storeRegistry != nil {
s.storeRegistry.UnregisterByStoreID(id)
}
logger.Infof(ctx, "Deleted vector store: tenant=%d, id=%s", tenantID, id)
// 4. Unregister from registry — wrapped to convert panics into ops
// warnings rather than silent stale-engine leaks.
s.unregisterSafely(ctx, id)
logger.Infof(ctx, "Deleted vector store: tenant=%d, id=%s", tenantID,
secutils.SanitizeForLog(id))
return nil
}
// unregisterSafely calls the registry's idempotent unregister with panic
// containment. A panic here is recoverable because the registry is
// in-memory and self-heals on process restart — but it must be loud
// enough for ops to purge the stale engine on running replicas.
func (s *vectorStoreService) unregisterSafely(ctx context.Context, storeID string) {
defer func() {
if r := recover(); r != nil {
logger.WarnWithFields(ctx, logger.Fields{
"store_id": secutils.SanitizeForLog(storeID),
"panic": fmt.Sprint(r),
}, "[vectorstore.delete] registry unregister panicked; engine may stay stale until restart")
}
}()
if s.storeRegistry != nil {
s.storeRegistry.UnregisterByStoreID(storeID)
}
}
// isPostgres reports whether the active GORM dialector is PostgreSQL.
// Used to gate dialect-specific clauses (e.g., SELECT FOR UPDATE) that
// SQLite would either ignore (recent versions) or fail to compile on.
func (s *vectorStoreService) isPostgres(db *gorm.DB) bool {
return db != nil && db.Dialector != nil && db.Dialector.Name() == "postgres"
}
// SaveDetectedVersion updates the connection_config.version for a stored vector store.
// Works on a copy to avoid mutating the caller's object.
func (s *vectorStoreService) SaveDetectedVersion(ctx context.Context, store *types.VectorStore, version string) error {
@@ -137,6 +247,128 @@ func (s *vectorStoreService) SaveDetectedVersion(ctx context.Context, store *typ
return s.repo.UpdateConnectionConfig(ctx, &updated)
}
// ResolveStoreView returns the API-safe display projection of a single
// store ID for embedding in another resource's response (typically a KB).
//
// Resolution order:
//
// 1. storeID == "" → DefaultStoreDisplay (env fallback semantics).
// 2. DB store row matching (id, tenantID) → user-source display.
// 3. Cached env store with matching ID → env-source display.
// 4. Otherwise → UnavailableStoreDisplay with a structured warn log.
//
// Errors from the underlying repository are returned to the caller so
// transient infrastructure failures can be classified, but the returned
// StoreDisplay is still UnavailableStoreDisplay so a handler that ignores
// the error degrades gracefully rather than panicking on a zero value.
func (s *vectorStoreService) ResolveStoreView(
ctx context.Context, tenantID uint64, storeID string,
) (types.StoreDisplay, error) {
if storeID == "" {
return types.DefaultStoreDisplay(), nil
}
store, err := s.repo.GetByID(ctx, tenantID, storeID)
if err != nil {
return types.UnavailableStoreDisplay(), err
}
if store != nil {
return types.StoreDisplay{
Name: store.Name,
Source: types.StoreSourceUser,
EngineType: string(store.EngineType),
Status: "available",
}, nil
}
for _, env := range s.envStores {
if env.ID == storeID {
return types.StoreDisplay{
Name: env.Name,
Source: types.StoreSourceEnv,
EngineType: string(env.EngineType),
Status: "available",
}, nil
}
}
logger.WarnWithFields(ctx, logger.Fields{
"tenant_id": tenantID,
"store_id": secutils.SanitizeForLog(storeID),
}, "[vectorstore.resolve] bound store missing from DB and env set")
return types.UnavailableStoreDisplay(), nil
}
// BatchResolveStoreView resolves multiple store IDs in a single DB read
// plus the cached env-store match. Returned map keys are the storeIDs
// originally requested; missing IDs map to UnavailableStoreDisplay.
//
// Intended for list endpoints that need store metadata for many KBs at
// once without incurring N+1 ResolveStoreView calls.
//
// Implementation note: the tenant-store count is bounded by operator
// config (typically tens), so iterating the tenant's full store list
// once is cheaper than a SELECT … WHERE id IN (…) round-trip and avoids
// adding a batch-by-ids repository method that has no other caller.
func (s *vectorStoreService) BatchResolveStoreView(
ctx context.Context, tenantID uint64, storeIDs []string,
) (map[string]types.StoreDisplay, error) {
out := make(map[string]types.StoreDisplay, len(storeIDs))
if len(storeIDs) == 0 {
return out, nil
}
requested := make(map[string]bool, len(storeIDs))
hasNonEmpty := false
for _, id := range storeIDs {
if id == "" {
continue
}
requested[id] = true
hasNonEmpty = true
}
if hasNonEmpty {
dbStores, err := s.repo.List(ctx, tenantID)
if err != nil {
return nil, err
}
for _, st := range dbStores {
if requested[st.ID] {
out[st.ID] = types.StoreDisplay{
Name: st.Name,
Source: types.StoreSourceUser,
EngineType: string(st.EngineType),
Status: "available",
}
}
}
for _, env := range s.envStores {
if _, ok := out[env.ID]; ok {
continue
}
if requested[env.ID] {
out[env.ID] = types.StoreDisplay{
Name: env.Name,
Source: types.StoreSourceEnv,
EngineType: string(env.EngineType),
Status: "available",
}
}
}
}
// Fill misses (including empty-string entries) with the appropriate
// sentinel so callers can rely on a key for every requested ID.
for _, id := range storeIDs {
if id == "" {
out[id] = types.DefaultStoreDisplay()
continue
}
if _, ok := out[id]; !ok {
out[id] = types.UnavailableStoreDisplay()
}
}
return out, nil
}
// registerInRegistry creates an engine service and registers it in the registry.
// Logs and skips on failure — the store is already persisted in DB,
// and will be loaded on next app restart (self-healing).
+435 -101
View File
@@ -11,6 +11,8 @@ import (
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sqlitedrv "gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// ---------------------------------------------------------------------------
@@ -155,7 +157,7 @@ func (m *mockEngineService) BatchUpdateChunkTagID(_ context.Context, _ map[strin
func TestCreateStore_Success(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
TenantID: 1,
@@ -173,7 +175,7 @@ func TestCreateStore_Success(t *testing.T) {
func TestCreateStore_ValidationError(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
tests := []struct {
name string
@@ -205,7 +207,7 @@ func TestCreateStore_ValidationError(t *testing.T) {
func TestCreateStore_ConnectionConfigValidation(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
tests := []struct {
name string
@@ -222,22 +224,20 @@ func TestCreateStore_ConnectionConfigValidation(t *testing.T) {
wantError: true,
},
{
name: "postgres without addr or default connection",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.PostgresRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: true,
},
{
name: "postgres with use_default_connection",
// Postgres is no longer registerable as a DB-managed store (see
// validEngineTypes); the Validate() call inside CreateStore short-
// circuits before validateConnectionConfig ever runs. Either
// missing-config or full-config rejects with "unsupported engine
// type". The env-store path (RETRIEVE_DRIVER=postgres) reaches the
// engine registry through BuildEnvVectorStores and does not
// traverse this code path.
name: "postgres rejected as DB store (any config)",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.PostgresRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{UseDefaultConnection: true},
},
wantError: false,
wantError: true,
},
{
name: "qdrant without host",
@@ -267,13 +267,15 @@ func TestCreateStore_ConnectionConfigValidation(t *testing.T) {
wantError: true,
},
{
name: "sqlite with no config (ok)",
// SQLite, like Postgres, is no longer registerable as a DB store
// (see validEngineTypes). Reachable only as an env store.
name: "sqlite rejected as DB store",
store: &types.VectorStore{
TenantID: 1, Name: "test",
EngineType: types.SQLiteRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{},
},
wantError: false,
wantError: true,
},
}
@@ -291,7 +293,7 @@ func TestCreateStore_ConnectionConfigValidation(t *testing.T) {
func TestCreateStore_DuplicateCheck_DBStore(t *testing.T) {
repo := &mockVectorStoreRepo{existsByEndpoint: true}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
TenantID: 1,
@@ -314,7 +316,7 @@ func TestCreateStore_DuplicateCheck_DBError(t *testing.T) {
repo := &mockVectorStoreRepo{
existsByEndpointErr: assert.AnError,
}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
TenantID: 1,
@@ -338,7 +340,7 @@ func TestCreateStore_DuplicateCheck_EnvStore(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "xwrag_default")
repo := &mockVectorStoreRepo{existsByEndpoint: false} // no DB duplicate
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
TenantID: 1,
@@ -368,7 +370,7 @@ func TestCreateStore_DuplicateCheck_EnvStore_DifferentIndex_Allowed(t *testing.T
t.Setenv("ELASTICSEARCH_INDEX", "xwrag_default")
repo := &mockVectorStoreRepo{existsByEndpoint: false}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
TenantID: 1,
@@ -387,22 +389,23 @@ func TestCreateStore_DuplicateCheck_EnvStore_DifferentIndex_Allowed(t *testing.T
}
func TestCreateStore_DifferentEndpointSameIndex_Allowed(t *testing.T) {
repo := &mockVectorStoreRepo{existsByEndpoint: false}
svc := NewVectorStoreService(repo, nil, nil)
// Use postgres with UseDefaultConnection to avoid needing a real ES endpoint.
// The test verifies duplicate-check logic, not connectivity.
store := &types.VectorStore{
TenantID: 1,
Name: "new-store",
EngineType: types.PostgresRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
UseDefaultConnection: true,
},
}
err := svc.CreateStore(context.Background(), store)
assert.NoError(t, err)
// Historical note — this test used Postgres + UseDefaultConnection so the
// connectivity test step would short-circuit (testPostgresConnection
// returns nil on use_default_connection), letting the duplicate-check
// logic run against a pure in-memory mock. Once Postgres/SQLite were
// dropped from validEngineTypes (DB stores must be a network-reachable
// engine), no engine remaining in the allow list has an equivalent
// "no network needed" fast path: every other engine's connection probe
// dials a real endpoint, which a unit-test environment cannot
// reasonably provide without spinning up a real backend.
//
// The underlying invariant (same endpoint + different index name is
// allowed) is still indirectly exercised by the live ParadeDB/Qdrant
// flows in CI integration and by manual E2E tests. A proper unit-test
// substitute requires either an injectable TestConnection mock or a
// dedicated repository-only test that exercises ExistsByEndpointAndIndex
// without going through the service-level CreateStore pipeline.
t.Skip("requires mockable TestConnection or repository-only test; track separately")
}
// ---------------------------------------------------------------------------
@@ -413,7 +416,7 @@ func TestCreateStore_RegistersInRegistry(t *testing.T) {
repo := &mockVectorStoreRepo{}
registry := newMockStoreRegistry()
factory := mockEngineFactory(nil)
svc := NewVectorStoreService(repo, registry, factory)
svc := NewVectorStoreService(repo, nil, registry, factory, nil)
store := &types.VectorStore{
TenantID: 1,
@@ -436,7 +439,7 @@ func TestCreateStore_RegistryFailureDoesNotRollBackDB(t *testing.T) {
repo := &mockVectorStoreRepo{}
registry := newMockStoreRegistry()
factory := mockEngineFactory(assert.AnError) // factory fails
svc := NewVectorStoreService(repo, registry, factory)
svc := NewVectorStoreService(repo, nil, registry, factory, nil)
store := &types.VectorStore{
TenantID: 1,
@@ -459,7 +462,7 @@ func TestCreateStore_RegistryFailureDoesNotRollBackDB(t *testing.T) {
func TestCreateStore_NilRegistryAndFactory(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil) // no registry
svc := NewVectorStoreService(repo, nil, nil, nil, nil) // no registry
store := &types.VectorStore{
TenantID: 1,
@@ -478,52 +481,21 @@ func TestCreateStore_NilRegistryAndFactory(t *testing.T) {
// ---------------------------------------------------------------------------
// DeleteStore + Registry integration tests
//
// The DeleteStore path runs through a transactional guard that requires
// both a kbRepo and a *gorm.DB handle, so the in-memory mock cannot
// exercise it. The TestDeleteStore_Guard_* family below covers the same
// outcomes (success, missing store, registry interaction, rollback)
// against an actual sqlite transaction.
// ---------------------------------------------------------------------------
func TestDeleteStore_UnregistersFromRegistry(t *testing.T) {
repo := &mockVectorStoreRepo{}
registry := newMockStoreRegistry()
registry.registered["store-1"] = true
svc := NewVectorStoreService(repo, registry, nil)
err := svc.DeleteStore(context.Background(), 1, "store-1")
require.NoError(t, err)
// Should be unregistered
assert.Contains(t, registry.unregistered, "store-1")
assert.False(t, registry.registered["store-1"])
}
func TestDeleteStore_NilRegistryGraceful(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
// Should not panic with nil registry
err := svc.DeleteStore(context.Background(), 1, "store-1")
assert.NoError(t, err)
}
func TestDeleteStore_RepoErrorSkipsUnregister(t *testing.T) {
repo := &mockVectorStoreRepo{deleteErr: assert.AnError}
registry := newMockStoreRegistry()
registry.registered["store-1"] = true
svc := NewVectorStoreService(repo, registry, nil)
err := svc.DeleteStore(context.Background(), 1, "store-1")
assert.Error(t, err)
// Registry should NOT be touched if DB delete fails
assert.True(t, registry.registered["store-1"])
assert.Empty(t, registry.unregistered)
}
// ---------------------------------------------------------------------------
// UpdateStore tests
// ---------------------------------------------------------------------------
func TestUpdateStore_Success(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
ID: "test-id",
@@ -537,7 +509,7 @@ func TestUpdateStore_Success(t *testing.T) {
func TestUpdateStore_ValidationError(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
tests := []struct {
name string
@@ -565,21 +537,10 @@ func TestUpdateStore_ValidationError(t *testing.T) {
// DeleteStore tests
// ---------------------------------------------------------------------------
func TestDeleteStore_Success(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
err := svc.DeleteStore(context.Background(), 1, "test-id")
assert.NoError(t, err)
}
func TestDeleteStore_RepoError(t *testing.T) {
repo := &mockVectorStoreRepo{deleteErr: assert.AnError}
svc := NewVectorStoreService(repo, nil, nil)
err := svc.DeleteStore(context.Background(), 1, "test-id")
assert.Error(t, err)
}
// TestDeleteStore_Success and TestDeleteStore_RepoError have been replaced
// by the TestDeleteStore_Guard_* family below, which exercises the
// transactional delete-guard path against an actual sqlite database (a mock
// repo would not honor the row-lock + binding-count semantics).
// ---------------------------------------------------------------------------
// SaveDetectedVersion tests
@@ -587,7 +548,7 @@ func TestDeleteStore_RepoError(t *testing.T) {
func TestSaveDetectedVersion_Success(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
ID: "store-1",
@@ -601,7 +562,7 @@ func TestSaveDetectedVersion_Success(t *testing.T) {
func TestSaveDetectedVersion_RepoError(t *testing.T) {
repo := &mockVectorStoreRepo{updateErr: assert.AnError}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{ID: "store-1", TenantID: 1}
err := svc.SaveDetectedVersion(context.Background(), store, "8.11.0")
@@ -610,7 +571,7 @@ func TestSaveDetectedVersion_RepoError(t *testing.T) {
func TestSaveDetectedVersion_DoesNotMutateOriginal(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
store := &types.VectorStore{
ID: "store-1",
@@ -631,7 +592,7 @@ func TestSaveDetectedVersion_DoesNotMutateOriginal(t *testing.T) {
func TestTestConnection_UnsupportedEngineType(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
_, err := svc.TestConnection(context.Background(), "unknown_engine", types.ConnectionConfig{})
require.Error(t, err)
@@ -643,7 +604,7 @@ func TestTestConnection_UnsupportedEngineType(t *testing.T) {
func TestTestConnection_SQLiteAlwaysSucceeds(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
version, err := svc.TestConnection(context.Background(), types.SQLiteRetrieverEngineType, types.ConnectionConfig{})
assert.NoError(t, err)
@@ -652,7 +613,7 @@ func TestTestConnection_SQLiteAlwaysSucceeds(t *testing.T) {
func TestTestConnection_PostgresDefaultConnection(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
version, err := svc.TestConnection(context.Background(), types.PostgresRetrieverEngineType,
types.ConnectionConfig{UseDefaultConnection: true})
@@ -663,7 +624,7 @@ func TestTestConnection_PostgresDefaultConnection(t *testing.T) {
func TestTestConnection_DorisInvalidAddr(t *testing.T) {
// 给一个不可达的地址 + 5s timeout,期望返回 BadRequestError 而非 panic。
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
@@ -678,7 +639,7 @@ func TestTestConnection_DorisInvalidAddr(t *testing.T) {
func TestTestConnection_DorisMissingAddr(t *testing.T) {
repo := &mockVectorStoreRepo{}
svc := NewVectorStoreService(repo, nil, nil)
svc := NewVectorStoreService(repo, nil, nil, nil, nil)
_, err := svc.TestConnection(context.Background(), types.DorisRetrieverEngineType,
types.ConnectionConfig{})
@@ -799,3 +760,376 @@ func TestValidateConnectionConfig(t *testing.T) {
})
}
}
// ---------------------------------------------------------------------------
// DeleteStore guard + ResolveStoreView + BatchResolveStoreView integration
//
// These use a real sqlite in-memory database because the delete guard relies
// on GORM transactions and the soft-delete auto-scope; an interface-level
// mock would not catch divergence between the row-lock path and the count.
// ---------------------------------------------------------------------------
// guardTestDDL inlines the subset of migrations/sqlite/000000_init.up.sql
// that the delete-guard tests touch. We do not use AutoMigrate because the
// KnowledgeBase struct carries `type:jsonb` GORM tags that SQLite cannot
// map cleanly.
const guardTestDDL = `
CREATE TABLE IF NOT EXISTS vector_stores (
id VARCHAR(36) NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
engine_type VARCHAR(50) NOT NULL,
connection_config TEXT NOT NULL DEFAULT '{}',
index_config TEXT NOT NULL DEFAULT '{}',
tenant_id INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME NULL
);
CREATE TABLE IF NOT EXISTS knowledge_bases (
id VARCHAR(36) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
tenant_id INTEGER NOT NULL,
type VARCHAR(32) NOT NULL DEFAULT 'document',
chunking_config TEXT NOT NULL DEFAULT '{}',
image_processing_config TEXT NOT NULL DEFAULT '{}',
embedding_model_id VARCHAR(64) NOT NULL,
summary_model_id VARCHAR(64) NOT NULL,
cos_config TEXT NOT NULL DEFAULT '{}',
storage_provider_config TEXT DEFAULT NULL,
vlm_config TEXT NOT NULL DEFAULT '{}',
extract_config TEXT NULL DEFAULT NULL,
faq_config TEXT,
question_generation_config TEXT NULL,
is_temporary BOOLEAN NOT NULL DEFAULT 0,
is_pinned INTEGER NOT NULL DEFAULT 0,
pinned_at DATETIME NULL,
asr_config TEXT,
vector_store_id VARCHAR(36),
wiki_config TEXT,
indexing_strategy TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
);
`
func newGuardTestService(t *testing.T) (*vectorStoreService, *gorm.DB, *mockStoreRegistry) {
t.Helper()
db, err := gorm.Open(sqlitedrv.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.Exec(guardTestDDL).Error)
registry := newMockStoreRegistry()
svc := &vectorStoreService{
repo: &realStoreRepo{db: db},
kbRepo: &realKBRepo{db: db},
storeRegistry: registry,
factory: nil,
db: db,
envStores: []types.VectorStore{},
}
return svc, db, registry
}
// realStoreRepo is a hand-rolled VectorStoreRepository against an in-memory
// sqlite handle. We avoid pulling in the repository package to keep this
// test file self-contained.
type realStoreRepo struct{ db *gorm.DB }
func (r *realStoreRepo) Create(ctx context.Context, s *types.VectorStore) error {
return r.db.WithContext(ctx).Create(s).Error
}
func (r *realStoreRepo) GetByID(ctx context.Context, tenantID uint64, id string) (*types.VectorStore, error) {
var s types.VectorStore
err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&s).Error
if err == gorm.ErrRecordNotFound {
return nil, nil
}
if err != nil {
return nil, err
}
return &s, nil
}
func (r *realStoreRepo) List(ctx context.Context, tenantID uint64) ([]*types.VectorStore, error) {
var stores []*types.VectorStore
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Find(&stores).Error
return stores, err
}
func (r *realStoreRepo) Update(_ context.Context, _ *types.VectorStore) error {
return nil
}
func (r *realStoreRepo) UpdateConnectionConfig(_ context.Context, _ *types.VectorStore) error {
return nil
}
func (r *realStoreRepo) Delete(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.VectorStore{}).Error
}
func (r *realStoreRepo) ExistsByEndpointAndIndex(_ context.Context, _ uint64, _ types.RetrieverEngineType, _ string, _ string) (bool, error) {
return false, nil
}
// realKBRepo is the minimal KnowledgeBaseRepository slice required by the
// vector-store service (only CountByVectorStoreID is exercised here).
type realKBRepo struct{ db *gorm.DB }
func (r *realKBRepo) CountByVectorStoreID(ctx context.Context, db *gorm.DB, tenantID uint64, storeID string) (int64, error) {
if db == nil {
db = r.db
}
var count int64
err := db.WithContext(ctx).
Model(&types.KnowledgeBase{}).
Where("tenant_id = ? AND vector_store_id = ?", tenantID, storeID).
Count(&count).Error
return count, err
}
// The remaining methods are not called by the tested code paths; declare them
// so realKBRepo satisfies interfaces.KnowledgeBaseRepository.
func (r *realKBRepo) CreateKnowledgeBase(_ context.Context, kb *types.KnowledgeBase) error {
return r.db.Create(kb).Error
}
func (r *realKBRepo) GetKnowledgeBaseByID(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, nil
}
func (r *realKBRepo) GetKnowledgeBaseByIDAndTenant(_ context.Context, _ string, _ uint64) (*types.KnowledgeBase, error) {
return nil, nil
}
func (r *realKBRepo) GetKnowledgeBaseByIDs(_ context.Context, _ []string) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (r *realKBRepo) ListKnowledgeBases(_ context.Context) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (r *realKBRepo) ListKnowledgeBasesByTenantID(_ context.Context, _ uint64) ([]*types.KnowledgeBase, error) {
return nil, nil
}
func (r *realKBRepo) UpdateKnowledgeBase(_ context.Context, _ *types.KnowledgeBase) error {
return nil
}
func (r *realKBRepo) DeleteKnowledgeBase(_ context.Context, _ string) error {
return nil
}
func (r *realKBRepo) TogglePinKnowledgeBase(_ context.Context, _ string, _ uint64) (*types.KnowledgeBase, error) {
return nil, nil
}
func insertGuardStore(t *testing.T, db *gorm.DB, id string, tenantID uint64) {
t.Helper()
require.NoError(t, db.Create(&types.VectorStore{
ID: id, Name: id, EngineType: types.QdrantRetrieverEngineType, TenantID: tenantID,
}).Error)
}
func insertGuardKB(t *testing.T, db *gorm.DB, tenantID uint64, vsid *string) string {
t.Helper()
id := "kb-" + tenantID2s(tenantID) + "-" + ptrOrEmpty(vsid)
kb := &types.KnowledgeBase{
ID: id,
Name: id,
TenantID: tenantID,
EmbeddingModelID: "embed",
SummaryModelID: "sum",
VectorStoreID: vsid,
}
require.NoError(t, db.Create(kb).Error)
return id
}
func tenantID2s(t uint64) string {
if t == 1 {
return "t1"
}
if t == 2 {
return "t2"
}
return "tN"
}
func ptrOrEmpty(p *string) string {
if p == nil {
return "nil"
}
return *p
}
func TestDeleteStore_Guard_Success(t *testing.T) {
ctx := context.Background()
svc, db, registry := newGuardTestService(t)
insertGuardStore(t, db, "store-A", 1)
err := svc.DeleteStore(ctx, 1, "store-A")
require.NoError(t, err)
// store row soft-deleted, no longer visible to default GORM scope.
var got types.VectorStore
err = db.Where("id = ?", "store-A").First(&got).Error
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
// registry unregister was invoked once.
require.Equal(t, []string{"store-A"}, registry.unregistered)
}
func TestDeleteStore_Guard_RejectsBoundKB(t *testing.T) {
ctx := context.Background()
svc, db, registry := newGuardTestService(t)
insertGuardStore(t, db, "store-A", 1)
storeID := "store-A"
insertGuardKB(t, db, 1, &storeID)
err := svc.DeleteStore(ctx, 1, "store-A")
require.Error(t, err)
assert.Contains(t, err.Error(), "still has 1 knowledge base")
// store row must still be present (rollback succeeded).
var got types.VectorStore
require.NoError(t, db.Where("id = ?", "store-A").First(&got).Error)
require.Empty(t, registry.unregistered, "registry must NOT be unregistered when guard fires")
}
func TestDeleteStore_Guard_IgnoresSoftDeletedKB(t *testing.T) {
ctx := context.Background()
svc, db, registry := newGuardTestService(t)
insertGuardStore(t, db, "store-A", 1)
storeID := "store-A"
kbID := insertGuardKB(t, db, 1, &storeID)
require.NoError(t, db.Where("id = ?", kbID).Delete(&types.KnowledgeBase{}).Error)
err := svc.DeleteStore(ctx, 1, "store-A")
require.NoError(t, err)
require.Equal(t, []string{"store-A"}, registry.unregistered)
}
func TestDeleteStore_Guard_IgnoresOtherTenantKB(t *testing.T) {
ctx := context.Background()
svc, db, registry := newGuardTestService(t)
insertGuardStore(t, db, "store-A", 1)
storeID := "store-A"
insertGuardKB(t, db, 2, &storeID) // cross-tenant binding (should not block)
err := svc.DeleteStore(ctx, 1, "store-A")
require.NoError(t, err)
require.Equal(t, []string{"store-A"}, registry.unregistered)
}
func TestDeleteStore_Guard_StoreNotFound(t *testing.T) {
ctx := context.Background()
svc, _, registry := newGuardTestService(t)
err := svc.DeleteStore(ctx, 1, "store-missing")
require.Error(t, err)
appErr, ok := errors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, 404, appErr.HTTPCode)
require.Empty(t, registry.unregistered)
}
func TestDeleteStore_Guard_RejectsCount3(t *testing.T) {
ctx := context.Background()
svc, db, _ := newGuardTestService(t)
insertGuardStore(t, db, "store-A", 1)
storeID := "store-A"
for i := 0; i < 3; i++ {
kb := &types.KnowledgeBase{
ID: "kb-multi-" + tenantID2s(1) + "-" + ptrOrEmpty(&storeID) + "-" + string(rune('a'+i)),
Name: "kb", TenantID: 1, EmbeddingModelID: "e", SummaryModelID: "s",
VectorStoreID: &storeID,
}
require.NoError(t, db.Create(kb).Error)
}
err := svc.DeleteStore(ctx, 1, "store-A")
require.Error(t, err)
assert.Contains(t, err.Error(), "still has 3 knowledge base")
}
func TestUnregisterSafely_PanicRecovered(t *testing.T) {
svc := &vectorStoreService{
storeRegistry: panickingRegistry{},
}
// Must not panic out of the test process.
svc.unregisterSafely(context.Background(), "store-A")
}
type panickingRegistry struct{}
func (panickingRegistry) RegisterWithStoreID(string, interfaces.RetrieveEngineService) {}
func (panickingRegistry) GetByStoreID(string) (interfaces.RetrieveEngineService, error) {
return nil, nil
}
func (panickingRegistry) UnregisterByStoreID(string) { panic("registry exploded") }
// ---------------------------------------------------------------------------
// ResolveStoreView / BatchResolveStoreView
// ---------------------------------------------------------------------------
func TestResolveStoreView(t *testing.T) {
ctx := context.Background()
svc, db, _ := newGuardTestService(t)
insertGuardStore(t, db, "store-A", 1)
svc.envStores = []types.VectorStore{
{ID: "__env_es__", Name: "Env ES", EngineType: types.ElasticsearchRetrieverEngineType},
}
t.Run("empty store id returns DefaultStoreDisplay", func(t *testing.T) {
v, err := svc.ResolveStoreView(ctx, 1, "")
require.NoError(t, err)
assert.Equal(t, "System default", v.Name)
assert.Equal(t, types.StoreSourceEnv, v.Source)
})
t.Run("DB hit", func(t *testing.T) {
v, err := svc.ResolveStoreView(ctx, 1, "store-A")
require.NoError(t, err)
assert.Equal(t, "store-A", v.Name)
assert.Equal(t, types.StoreSourceUser, v.Source)
assert.Equal(t, string(types.QdrantRetrieverEngineType), v.EngineType)
})
t.Run("env hit", func(t *testing.T) {
v, err := svc.ResolveStoreView(ctx, 1, "__env_es__")
require.NoError(t, err)
assert.Equal(t, "Env ES", v.Name)
assert.Equal(t, types.StoreSourceEnv, v.Source)
})
t.Run("miss returns unavailable", func(t *testing.T) {
v, err := svc.ResolveStoreView(ctx, 1, "store-zzz")
require.NoError(t, err)
assert.Equal(t, types.StoreSourceUnavailable, v.Source)
})
t.Run("cross-tenant store is treated as unavailable", func(t *testing.T) {
insertGuardStore(t, db, "store-B", 2) // owned by tenant 2
v, err := svc.ResolveStoreView(ctx, 1, "store-B")
require.NoError(t, err)
assert.Equal(t, types.StoreSourceUnavailable, v.Source)
})
}
func TestBatchResolveStoreView(t *testing.T) {
ctx := context.Background()
svc, db, _ := newGuardTestService(t)
insertGuardStore(t, db, "store-A", 1)
insertGuardStore(t, db, "store-B", 1)
svc.envStores = []types.VectorStore{
{ID: "__env_qd__", Name: "Env QD", EngineType: types.QdrantRetrieverEngineType},
}
got, err := svc.BatchResolveStoreView(ctx, 1, []string{
"store-A", "store-zzz", "__env_qd__", "",
})
require.NoError(t, err)
require.Len(t, got, 4)
assert.Equal(t, types.StoreSourceUser, got["store-A"].Source)
assert.Equal(t, "store-A", got["store-A"].Name)
assert.Equal(t, types.StoreSourceUnavailable, got["store-zzz"].Source)
assert.Equal(t, types.StoreSourceEnv, got["__env_qd__"].Source)
assert.Equal(t, "Env QD", got["__env_qd__"].Name)
assert.Equal(t, types.StoreSourceEnv, got[""].Source)
assert.Equal(t, "System default", got[""].Name)
}
func TestBatchResolveStoreView_Empty(t *testing.T) {
ctx := context.Background()
svc, _, _ := newGuardTestService(t)
got, err := svc.BatchResolveStoreView(ctx, 1, nil)
require.NoError(t, err)
assert.Empty(t, got)
}