WeKnora/internal/application/service/knowledgebase_pr3_test.go

522 lines
19 KiB
Go
Raw Normal View History

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.
2026-05-18 01:10:01 +00:00
package service
import (
"context"
stderrors "errors"
"testing"
"time"
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.
2026-05-18 01:10:01 +00:00
"github.com/Tencent/WeKnora/internal/application/service/retriever"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/storageallowlist"
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.
2026-05-18 01:10:01 +00:00
"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")
}
fix(retriever): rebuild a missing vector store engine on demand The engine registry is per-process, so a store's engine is missing whenever this process did not create it. That happens three ways: - Startup skips a store whose engine fails to construct and never retries it, so that instance cannot serve the store again -- not even after a restart, if the backend is slow to come up. - A store registered on one instance is absent on every other until they restart, because registration is not broadcast. - Registration can fail on the instance handling the create, leaving the store missing even there. Each one surfaces as "vector store is currently unavailable" and is cleared today only by restarting the process. Add GetOrLoadByStoreID, which falls back to building the engine from the store row when the lookup misses, and route the two bound-store lookups through it. The method goes on RetrieveEngineRegistry rather than StoreRegistry because that is the interface the factory functions receive; the two declare GetByStoreID separately and neither embeds the other. Concurrent callers collapse onto one build. That build runs on a context detached from the caller that started it: callers share the result, so letting the first one's cancellation abort it would fail everyone else waiting. A panic inside the build is contained, because singleflight re-raises it on a goroutine the HTTP recovery middleware cannot reach and the build calls third-party client constructors. Publishing is guarded by a per-store generation sampled before the build, so an engine that finishes after the entry was registered or removed by someone else does not overwrite it and leave that engine orphaned with its connections open. A failed build starts a cooldown: collapsing only helps concurrent callers, so without it a backend that stays down would cost a full build timeout on every sequential request. Separate "the store is gone" from "its engine cannot be built right now". Async delete handlers answer ErrVectorStoreNotFound with asynq.SkipRetry, so reporting a database blip or a backend outage that way would permanently discard knowledge-base and index delete tasks and orphan the vector data they exist to remove. ErrVectorStoreUnavailable covers the retryable cases; the repository already distinguishes them, returning (nil, nil) for a missing row and an error for a failure. For the same reason a caller's own cancellation is never folded into a store sentinel. The ownership check runs first and queries the database with that context, so on a shutdown it is usually where cancellation is noticed. A search resolves one engine per distinct store, sequentially, and this server sets no HTTP read or write timeout, so the resolution loop gets a budget above a single build. An exhausted budget still leaves the engines warming, since the build is detached, and is reported as an unavailable store because retrying is likely to succeed. Build failures are logged where they happen, with the panic stack. The cause cannot travel back to the caller -- factory errors embed endpoints and credentials -- so without this the one thing an operator needs when self-healing fails to heal would be discarded with the error. Note a deliberate contract change: an ownership lookup failure used to be reported as not-found, and a test asserted that on purpose. A database failure says nothing about whether the store exists, and treating it as permanent is what discards the task, so that assertion is inverted rather than preserved.
2026-07-27 11:25:46 +00:00
// This fake never rebuilds a missing engine, so a miss stays a miss.
func (f *fakeRegistry) GetOrLoadByStoreID(
_ context.Context, _ uint64, storeID string,
) (interfaces.RetrieveEngineService, error) {
return f.GetByStoreID(storeID)
}
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.
2026-05-18 01:10:01 +00:00
// 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
}
2026-07-08 12:43:12 +00:00
func (r *fakeKBRepo) ListKnowledgeBasesByTenantID(_ context.Context, tenantID uint64) ([]*types.KnowledgeBase, error) {
rows := make([]*types.KnowledgeBase, 0, len(r.rows))
for _, kb := range r.rows {
if kb != nil && kb.TenantID == tenantID {
rows = append(rows, kb)
}
}
return rows, nil
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.
2026-05-18 01:10:01 +00:00
}
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
}
func (r *fakeKBRepo) CountByModelID(_ context.Context, _ uint64, _ string) (int64, error) {
return 0, nil
}
func (r *fakeKBRepo) SetUserKBPin(_ context.Context, _ uint64, _ string, _ string, _ bool) (*time.Time, error) {
return nil, nil
}
func (r *fakeKBRepo) ListUserKBPinIDs(_ context.Context, _ uint64, _ string) (map[string]time.Time, error) {
return map[string]time.Time{}, nil
}
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.
2026-05-18 01:10:01 +00:00
// 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)
}
func ctxWithTenantStorage(tenantID uint64, defaultProvider string) context.Context {
ctx := ctxWithTenant(tenantID)
tenant := &types.Tenant{
ID: tenantID,
StorageEngineConfig: &types.StorageEngineConfig{
DefaultProvider: defaultProvider,
},
}
return context.WithValue(ctx, types.TenantInfoContextKey, tenant)
}
func TestCreateKnowledgeBase_DefaultStorageProviderFromTenant(t *testing.T) {
repo := newFakeKBRepo()
svc := newPR3KBService(repo, &fakeRegistry{registered: map[string]struct{}{}}, &fakeOwnership{})
kb, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, "minio"), &types.KnowledgeBase{Name: "kb"})
require.NoError(t, err)
assert.Equal(t, "minio", kb.GetStorageProvider())
kbExplicit, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, "minio"), &types.KnowledgeBase{
Name: "kb2",
StorageProviderConfig: &types.StorageProviderConfig{Provider: "cos"},
})
require.NoError(t, err)
assert.Equal(t, "cos", kbExplicit.GetStorageProvider())
}
func TestCreateKnowledgeBase_DefaultStorageProviderRespectsAllowList(t *testing.T) {
t.Setenv(storageallowlist.AllowListEnv, "minio")
repo := newFakeKBRepo()
svc := newPR3KBService(repo, &fakeRegistry{registered: map[string]struct{}{}}, &fakeOwnership{})
kb, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, ""), &types.KnowledgeBase{Name: "kb"})
require.NoError(t, err)
assert.Equal(t, "minio", kb.GetStorageProvider())
kbDisallowedDefault, err := svc.CreateKnowledgeBase(ctxWithTenantStorage(1, "local"), &types.KnowledgeBase{Name: "kb2"})
require.NoError(t, err)
assert.Equal(t, "minio", kbDisallowedDefault.GetStorageProvider())
}
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.
2026-05-18 01:10:01 +00:00
// ---------------------------------------------------------------------------
// 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")
})
}
2026-07-08 12:43:12 +00:00
func TestDuplicateKnowledgeBase_CreatesSettingsOnlyDuplicate(t *testing.T) {
repo := newFakeKBRepo()
source := &types.KnowledgeBase{
ID: "src",
Name: "Source KB",
Type: types.KnowledgeBaseTypeDocument,
Description: "source description",
TenantID: 1,
CreatorID: "source-owner",
IsTemporary: true,
ChunkingConfig: types.ChunkingConfig{
ChunkSize: 800,
ChunkOverlap: 80,
Separators: []string{"\n\n", "."},
ParserEngineRules: []types.ParserEngineRule{{
FileTypes: []string{"pdf"},
Engine: "docreader",
}},
},
ImageProcessingConfig: types.ImageProcessingConfig{ModelID: "vlm-image"},
EmbeddingModelID: "embed-1",
SummaryModelID: "summary-1",
VLMConfig: types.VLMConfig{Enabled: true, ModelID: "vlm-1"},
ASRConfig: types.ASRConfig{Enabled: true, ModelID: "asr-1", Language: "zh"},
StorageProviderConfig: &types.StorageProviderConfig{Provider: "local"},
ExtractConfig: &types.ExtractConfig{
Enabled: true,
Text: "extract entities",
Tags: []string{"product"},
Nodes: []*types.GraphNode{{Name: "Product"}},
},
QuestionGenerationConfig: &types.QuestionGenerationConfig{Enabled: true, QuestionCount: 5},
WikiConfig: &types.WikiConfig{SynthesisModelID: "wiki-llm", MaxPagesPerIngest: 12},
IndexingStrategy: types.IndexingStrategy{
VectorEnabled: true,
KeywordEnabled: true,
WikiEnabled: true,
GraphEnabled: true,
},
IsPinned: true,
KnowledgeCount: 9,
ChunkCount: 27,
IsProcessing: true,
ProcessingCount: 2,
ShareCount: 3,
CreatorName: "Source Owner",
}
repo.rows["src"] = source
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
ctx := context.WithValue(ctxWithTenant(1), types.UserIDContextKey, "copy-user")
target, err := svc.DuplicateKnowledgeBase(ctx, "src")
2026-07-08 12:43:12 +00:00
require.NoError(t, err)
require.NotEmpty(t, target.ID)
2026-07-08 12:43:12 +00:00
assert.Equal(t, uint64(1), target.TenantID)
assert.Equal(t, "copy-user", target.CreatorID)
assert.Equal(t, "Source KB 副本", target.Name)
assert.Equal(t, source.Description, target.Description)
assert.Equal(t, source.ChunkingConfig, target.ChunkingConfig)
assert.Equal(t, source.ImageProcessingConfig, target.ImageProcessingConfig)
assert.Equal(t, source.EmbeddingModelID, target.EmbeddingModelID)
assert.Equal(t, source.SummaryModelID, target.SummaryModelID)
assert.Equal(t, source.VLMConfig, target.VLMConfig)
assert.Equal(t, source.ASRConfig, target.ASRConfig)
require.NotNil(t, target.StorageProviderConfig)
assert.Equal(t, "local", target.StorageProviderConfig.Provider)
require.NotNil(t, target.ExtractConfig)
assert.Equal(t, source.ExtractConfig.Text, target.ExtractConfig.Text)
require.NotNil(t, target.QuestionGenerationConfig)
assert.Equal(t, 5, target.QuestionGenerationConfig.QuestionCount)
require.NotNil(t, target.WikiConfig)
assert.Equal(t, "wiki-llm", target.WikiConfig.SynthesisModelID)
assert.Equal(t, source.IndexingStrategy, target.IndexingStrategy)
assert.False(t, target.IsTemporary)
assert.False(t, target.IsPinned)
assert.Nil(t, target.PinnedAt)
assert.Zero(t, target.KnowledgeCount)
assert.Zero(t, target.ChunkCount)
assert.False(t, target.IsProcessing)
assert.Zero(t, target.ProcessingCount)
assert.Zero(t, target.ShareCount)
assert.Empty(t, target.CreatorName)
require.Same(t, target, repo.rows[target.ID])
2026-07-08 12:43:12 +00:00
}
func TestDuplicateKnowledgeBase_UsesDistinctNameWhenDuplicateExists(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = &types.KnowledgeBase{
ID: "src",
Name: "Source KB",
Type: types.KnowledgeBaseTypeDocument,
TenantID: 1,
}
repo.rows["existing-copy"] = &types.KnowledgeBase{
ID: "existing-copy",
Name: "Source KB 副本",
Type: types.KnowledgeBaseTypeDocument,
TenantID: 1,
}
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
target, err := svc.DuplicateKnowledgeBase(ctxWithTenant(1), "src")
2026-07-08 12:43:12 +00:00
require.NoError(t, err)
assert.Equal(t, "Source KB 副本 2", target.Name)
}
func TestDuplicateKnowledgeBase_UsesLocalizedEnglishSuffix(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = &types.KnowledgeBase{
ID: "src",
Name: "Source KB",
Type: types.KnowledgeBaseTypeDocument,
TenantID: 1,
}
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
ctx := context.WithValue(ctxWithTenant(1), types.LanguageContextKey, "en-US")
target, err := svc.DuplicateKnowledgeBase(ctx, "src")
require.NoError(t, err)
assert.Equal(t, "Source KB Copy", target.Name)
}