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:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user