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
@@ -9,6 +9,7 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/hibiken/asynq"
"gorm.io/gorm"
)
// KnowledgeBaseService defines the knowledge base service interface
@@ -207,4 +208,14 @@ type KnowledgeBaseRepository interface {
// TogglePinKnowledgeBase toggles the pin status of a knowledge base
TogglePinKnowledgeBase(ctx context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error)
// CountByVectorStoreID counts active KBs bound to the given vector store
// within a tenant scope. Accepts a *gorm.DB handle so callers can share a
// transaction (e.g., the VectorStore delete guard's row-lock context) or
// run standalone (pass nil → uses the repository's default db).
//
// The soft-delete filter is applied automatically by the gorm.DeletedAt
// scope on KnowledgeBase; implementations MUST NOT add an explicit
// `deleted_at IS NULL` predicate (avoids divergence with the auto-scope).
CountByVectorStoreID(ctx context.Context, db *gorm.DB, tenantID uint64, storeID string) (int64, error)
}
+20
View File
@@ -31,12 +31,32 @@ type VectorStoreService interface {
// UpdateStore updates an existing vector store (name only).
UpdateStore(ctx context.Context, store *types.VectorStore) error
// DeleteStore deletes a vector store by tenant + id.
// Rejects deletion when any active knowledge base is bound to the store
// (binding guard); the caller must unbind or delete those KBs first.
DeleteStore(ctx context.Context, tenantID uint64, id string) error
// TestConnection tests connectivity to a vector database.
// Returns the detected server version on success (e.g., "7.10.1"), empty string if unknown.
TestConnection(ctx context.Context, engineType types.RetrieverEngineType, config types.ConnectionConfig) (string, error)
// SaveDetectedVersion updates the connection_config.version for a stored vector store.
SaveDetectedVersion(ctx context.Context, store *types.VectorStore, version string) error
// ResolveStoreView returns the API-safe display projection of a single
// store ID, scoped to the given tenant. Tries DB stores first, then the
// cached env-store set. Returns types.UnavailableStoreDisplay() when the
// store cannot be resolved — callers should still succeed in such cases
// (the response carries a "unavailable" status signal for the UI).
//
// Never returns connection credentials in any form: the StoreDisplay
// payload carries only Name / Source / EngineType / Status.
ResolveStoreView(ctx context.Context, tenantID uint64, storeID string) (types.StoreDisplay, error)
// 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 types.UnavailableStoreDisplay().
//
// Intended for list endpoints that need store metadata for many KBs at
// once without incurring N+1 ResolveStoreView calls.
BatchResolveStoreView(ctx context.Context, tenantID uint64, storeIDs []string) (map[string]types.StoreDisplay, error)
}
// VectorStoreRepository defines the repository interface for VectorStore CRUD.
+61
View File
@@ -633,3 +633,64 @@ func (kb *KnowledgeBase) IsMultimodalEnabled() bool {
}
return false
}
// HasVectorStore reports whether the KB is bound to a DB-managed VectorStore
// (as opposed to the tenant's env-store fallback).
//
// Safe to call on a nil receiver (returns false). Mirrors the convention of
// other Is*Enabled / Capabilities accessors in this file.
func (kb *KnowledgeBase) HasVectorStore() bool {
return kb != nil && kb.VectorStoreID != nil && *kb.VectorStoreID != ""
}
// Normalize folds the empty-string vector store id into nil so a single
// representation reaches both the DB and the retrieve-engine factory, which
// treats nil and `&""` as the same "no binding" signal. Idempotent and safe
// to call repeatedly.
//
// Callers that accept unvalidated user input (CreateKnowledgeBase, async
// payload decoders) should invoke this before persistence or validation.
// Safe to call on a nil receiver (no-op).
func (kb *KnowledgeBase) Normalize() {
if kb == nil {
return
}
if kb.VectorStoreID != nil && *kb.VectorStoreID == "" {
kb.VectorStoreID = nil
}
}
// SharesStoreWith reports whether two knowledge bases are bound to the same
// vector store. Both env-fallback (nil) → true; both same UUID → true;
// otherwise false. Safe to call when either receiver or argument is nil
// (returns true iff both are nil).
//
// Empty-string VectorStoreID is treated as equivalent to nil so that rows
// persisted by callers that did not run Normalize first (raw-SQL writes,
// external migrations, ops scripts) still compare correctly. The alternative
// — treating `&""` as a distinct binding — would reject otherwise valid
// CopyKnowledgeBase clones with a confusing "different vector stores" 400.
// This normalization is read-only; it does not mutate the receivers.
//
// Lives on *KnowledgeBase next to HasVectorStore() so the binding semantics
// stay co-located with the type they describe.
func (kb *KnowledgeBase) SharesStoreWith(other *KnowledgeBase) bool {
if kb == nil || other == nil {
return kb == other
}
a, b := kb.VectorStoreID, other.VectorStoreID
if a != nil && *a == "" {
a = nil
}
if b != nil && *b == "" {
b = nil
}
switch {
case a == nil && b == nil:
return true
case a == nil || b == nil:
return false
default:
return *a == *b
}
}
+117 -4
View File
@@ -65,10 +65,11 @@ func strPtr(s string) *string { return &s }
// VectorStoreID pointer, including the `omitempty` behavior and the three
// distinct JSON inputs (missing field, explicit null, explicit value).
//
// The `empty string pointer` case is fixed here as a behavior snapshot: PR1
// accepts it and stores &"" verbatim because validation has not been added
// yet. A follow-up PR that introduces validation will convert this case into
// a rejection and flip the expectation in this test accordingly.
// The `empty string pointer` case is fixed here as a behavior snapshot:
// raw JSON encoding accepts it and stores &"" verbatim. Service-layer
// CreateKnowledgeBase normalizes &"" to nil before persistence
// (see (*KnowledgeBase).Normalize), so the stored DB row is NULL — but the
// JSON shape on the way in is whatever the client sent.
func TestKnowledgeBase_VectorStoreID_JSON(t *testing.T) {
t.Run("marshal nil omits field (omitempty)", func(t *testing.T) {
kb := KnowledgeBase{ID: "kb-1", VectorStoreID: nil}
@@ -156,3 +157,115 @@ func TestKnowledgeBase_UnmarshalJSON_WithVectorStoreID(t *testing.T) {
// If a future change introduces such a shadow, the value above would fail to populate.
}
// TestKnowledgeBase_HasVectorStore covers the nil-safe binding accessor.
func TestKnowledgeBase_HasVectorStore(t *testing.T) {
t.Run("nil receiver returns false", func(t *testing.T) {
var kb *KnowledgeBase
if kb.HasVectorStore() {
t.Fatal("nil receiver should return false")
}
})
t.Run("nil pointer returns false", func(t *testing.T) {
kb := &KnowledgeBase{}
if kb.HasVectorStore() {
t.Fatal("nil VectorStoreID should return false")
}
})
t.Run("empty string returns false", func(t *testing.T) {
empty := ""
kb := &KnowledgeBase{VectorStoreID: &empty}
if kb.HasVectorStore() {
t.Fatal("empty string VectorStoreID should return false")
}
})
t.Run("non-empty returns true", func(t *testing.T) {
s := "store-uuid"
kb := &KnowledgeBase{VectorStoreID: &s}
if !kb.HasVectorStore() {
t.Fatal("non-empty VectorStoreID should return true")
}
})
}
// TestKnowledgeBase_Normalize covers the empty-string -> nil fold used to
// keep a single representation between the create path and the factory.
func TestKnowledgeBase_Normalize(t *testing.T) {
t.Run("nil receiver is no-op", func(t *testing.T) {
var kb *KnowledgeBase
kb.Normalize() // must not panic
})
t.Run("empty string -> nil", func(t *testing.T) {
empty := ""
kb := &KnowledgeBase{VectorStoreID: &empty}
kb.Normalize()
if kb.VectorStoreID != nil {
t.Fatalf("expected nil after normalize, got %v", kb.VectorStoreID)
}
})
t.Run("non-empty unchanged", func(t *testing.T) {
s := "store-uuid"
kb := &KnowledgeBase{VectorStoreID: &s}
kb.Normalize()
if kb.VectorStoreID == nil || *kb.VectorStoreID != "store-uuid" {
t.Fatalf("expected store-uuid, got %v", kb.VectorStoreID)
}
})
t.Run("already nil unchanged", func(t *testing.T) {
kb := &KnowledgeBase{}
kb.Normalize()
if kb.VectorStoreID != nil {
t.Fatal("nil should stay nil")
}
})
t.Run("idempotent", func(t *testing.T) {
empty := ""
kb := &KnowledgeBase{VectorStoreID: &empty}
kb.Normalize()
kb.Normalize() // second call no-op
if kb.VectorStoreID != nil {
t.Fatal("idempotent normalize broke")
}
})
}
// TestKnowledgeBase_SharesStoreWith covers the binding-equality helper used
// by CopyKnowledgeBase's same-store defense. The empty-string cases are a
// regression guard: rows persisted by callers that did not run Normalize
// first can carry `vector_store_id = ""` instead of NULL; without the
// normalization inside SharesStoreWith such rows would falsely fail
// same-store clone checks.
func TestKnowledgeBase_SharesStoreWith(t *testing.T) {
mk := func(p *string) *KnowledgeBase { return &KnowledgeBase{VectorStoreID: p} }
a, b := "store-A", "store-B"
empty := ""
tests := []struct {
name string
kb *KnowledgeBase
oth *KnowledgeBase
want bool
}{
{"both nil receivers", nil, nil, true},
{"one nil receiver", nil, mk(nil), false},
{"both nil store IDs", mk(nil), mk(nil), true},
{"left nil store ID", mk(nil), mk(&a), false},
{"right nil store ID", mk(&a), mk(nil), false},
{"same store IDs", mk(&a), mk(&a), true},
{"different store IDs", mk(&a), mk(&b), false},
// empty-string == nil normalization (regression guard)
{"left empty-string vs right nil", mk(&empty), mk(nil), true},
{"left nil vs right empty-string", mk(nil), mk(&empty), true},
{"both empty-string", mk(&empty), mk(&empty), true},
{"left empty-string vs right UUID", mk(&empty), mk(&a), false},
{"left UUID vs right empty-string", mk(&a), mk(&empty), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.kb.SharesStoreWith(tt.oth); got != tt.want {
t.Fatalf("SharesStoreWith: got %v, want %v", got, tt.want)
}
})
}
}
+75 -5
View File
@@ -64,17 +64,27 @@ func (v *VectorStore) BeforeCreate(tx *gorm.DB) error {
return nil
}
// validEngineTypes defines the engine types that can be registered as VectorStore.
// InfinityRetrieverEngineType and ElasticFaissRetrieverEngineType are legacy/experimental
// types that do not have standalone deployable instances, so they are excluded.
// validEngineTypes defines the engine types that can be registered as a
// DB-managed VectorStore (i.e., persisted to the vector_stores table and
// listed in GetVectorStoreTypes for the UI dropdown).
//
// Excluded engines:
// - Infinity / ElasticFaiss — legacy/experimental, no standalone deployable instance.
// - Postgres / SQLite — only meaningful when bound to the app's default DB
// connection (UseDefaultConnection=true). The Postgres retriever's
// embeddings table is a single hard-coded name with no per-store
// partitioning, so registering a second Postgres store on the same
// instance has no separation effect — every KB sharing this engine
// ends up in the same physical table. These engines are still
// reachable via env stores (RETRIEVE_DRIVER=postgres/sqlite), which
// route through a separate code path (BuildEnvVectorStores) and do
// not pass through this validation.
var validEngineTypes = map[RetrieverEngineType]bool{
PostgresRetrieverEngineType: true,
ElasticsearchRetrieverEngineType: true,
QdrantRetrieverEngineType: true,
MilvusRetrieverEngineType: true,
WeaviateRetrieverEngineType: true,
DorisRetrieverEngineType: true,
SQLiteRetrieverEngineType: true,
TencentVectorDBRetrieverEngineType: true,
}
@@ -484,6 +494,66 @@ func ValidateIndexConfig(ic IndexConfig) error {
return nil
}
// ---------------------------------------------------------------------------
// StoreDisplay — API-safe projection embedded in other resource responses
// ---------------------------------------------------------------------------
// Vector store source classifiers used by API responses.
// Kept as package-level constants so handlers and services share a single
// vocabulary instead of repeating magic strings.
const (
StoreSourceEnv = "env" // env-driven (RETRIEVE_DRIVER)
StoreSourceUser = "user" // DB-managed VectorStore row
StoreSourceShared = "shared" // cross-tenant access — metadata suppressed
StoreSourceUnavailable = "unavailable" // bound store row missing / registry miss
)
// StoreDisplay is the API-safe projection of a VectorStore for embedding in
// other resource responses (notably KnowledgeBase). It carries only the
// display-safe identifiers — never connection credentials.
//
// Source is one of the StoreSource* constants. EngineType is the underlying
// engine name (e.g. "elasticsearch"). Status mirrors Source by default but
// is split out to give the UI a stable boolean-like signal independent of
// future Source value additions.
type StoreDisplay struct {
Name string `json:"vector_store_name,omitempty"`
Source string `json:"vector_store_source,omitempty"`
EngineType string `json:"vector_store_engine_type,omitempty"`
Status string `json:"vector_store_status,omitempty"` // "available" / "unavailable"
}
// DefaultStoreDisplay is the display payload for KBs that fall back to the
// tenant's env stores (VectorStoreID == nil).
func DefaultStoreDisplay() StoreDisplay {
return StoreDisplay{
Name: "System default",
Source: StoreSourceEnv,
Status: "available",
}
}
// UnavailableStoreDisplay is used when the bound store cannot be resolved
// (deleted row, registry miss, transient infra error). The UI can branch on
// Status to guide recovery (admin tool, rebind, etc.).
func UnavailableStoreDisplay() StoreDisplay {
return StoreDisplay{
Source: StoreSourceUnavailable,
Status: "unavailable",
}
}
// SharedStoreDisplay is returned for cross-tenant shared KB views so that
// the underlying owner-tenant store's name and engine remain hidden — only
// the fact that "this KB is shared" leaks, which is already implied by the
// share grant itself.
func SharedStoreDisplay() StoreDisplay {
return StoreDisplay{
Source: StoreSourceShared,
Status: "available",
}
}
// ---------------------------------------------------------------------------
// VectorStoreResponse — API response DTO
// ---------------------------------------------------------------------------
+57 -3
View File
@@ -324,7 +324,7 @@ const testAESKey = "01234567890123456789012345678901"
func TestVectorStore_Validate(t *testing.T) {
valid := VectorStore{
Name: "test-store",
EngineType: PostgresRetrieverEngineType,
EngineType: ElasticsearchRetrieverEngineType,
TenantID: 1,
}
@@ -380,12 +380,11 @@ func TestVectorStore_TableName(t *testing.T) {
func TestIsValidEngineType(t *testing.T) {
validTypes := []RetrieverEngineType{
PostgresRetrieverEngineType,
ElasticsearchRetrieverEngineType,
QdrantRetrieverEngineType,
MilvusRetrieverEngineType,
WeaviateRetrieverEngineType,
SQLiteRetrieverEngineType,
DorisRetrieverEngineType,
TencentVectorDBRetrieverEngineType,
}
for _, et := range validTypes {
@@ -394,10 +393,18 @@ func TestIsValidEngineType(t *testing.T) {
})
}
// Postgres and SQLite are intentionally NOT registerable as DB stores —
// they only make sense as env stores driven by RETRIEVE_DRIVER (see the
// doc comment on validEngineTypes). UI/API surface stays consistent:
// GetVectorStoreTypes does not list them, Validate rejects them, and
// env stores reach the engine registry through BuildEnvVectorStores
// instead of through CreateStore.
invalidTypes := []RetrieverEngineType{
"unknown",
"opensearch",
"",
PostgresRetrieverEngineType,
SQLiteRetrieverEngineType,
InfinityRetrieverEngineType,
ElasticFaissRetrieverEngineType,
}
@@ -1051,3 +1058,50 @@ func TestIndexConfig_ScalabilityFieldsRoundTrip(t *testing.T) {
assert.NotContains(t, parsed, "desired_shard_count")
})
}
// TestVectorStore_PostgresSqliteNotRegisterable pins the write-path and
// read-path consistency for the two engines that are only meaningful as env
// stores. They must:
//
// 1. Be rejected by Validate() so POST /vector-stores returns a 4xx
// instead of silently persisting a row that has no separation effect.
// 2. Be absent from GetVectorStoreTypes() so the UI dropdown doesn't
// offer them as a choice.
//
// Both checks live here so a future change that re-introduces one path
// (e.g., adds Postgres back to validEngineTypes for some niche case)
// fails this test pair instead of silently re-opening the inconsistency
// that this fix closed.
func TestVectorStore_PostgresSqliteNotRegisterable(t *testing.T) {
t.Run("Validate rejects postgres as DB store", func(t *testing.T) {
v := &VectorStore{
Name: "test", TenantID: 1,
EngineType: PostgresRetrieverEngineType,
}
err := v.Validate()
require.Error(t, err)
assert.Contains(t, err.Error(), "unsupported engine type")
})
t.Run("Validate rejects sqlite as DB store", func(t *testing.T) {
v := &VectorStore{
Name: "test", TenantID: 1,
EngineType: SQLiteRetrieverEngineType,
}
err := v.Validate()
require.Error(t, err)
assert.Contains(t, err.Error(), "unsupported engine type")
})
t.Run("GetVectorStoreTypes omits postgres and sqlite", func(t *testing.T) {
listed := GetVectorStoreTypes()
var got []string
for _, info := range listed {
got = append(got, info.Type)
}
assert.NotContains(t, got, string(PostgresRetrieverEngineType),
"postgres must not appear in the UI dropdown — env-store only")
assert.NotContains(t, got, string(SQLiteRetrieverEngineType),
"sqlite must not appear in the UI dropdown — env-store only")
})
}