refactor(retriever): introduce factory for KB-scoped retrieve engine resolution
Extracts the 25 repeated NewCompositeRetrieveEngine call sites across seven services into two factory functions with tenant-ownership verification: CreateRetrieveEngineForKB (synchronous) and CreateRetrieveEngineFromPayload (async task handlers). Promotes GetByStoreID from concrete-only to interfaces.RetrieveEngineRegistry. Extends KBDeletePayload / IndexDeletePayload with an omitempty VectorStoreID snapshot. Design highlights - Factory verifies tenant ownership of the resolved store (defense-in-depth) so a gap in PR3 validation or a tampered Asynq payload cannot cross tenants. Cross-tenant attempts return ErrVectorStoreForbidden with a structured log entry. - Sentinel errors (ErrTenantInfoMissing, ErrVectorStoreNotFound, ErrVectorStoreForbidden) let async handlers classify non-retryable failures as asynq.SkipRetry. - nil and empty-string pointers for vectorStoreID normalize to "unbound" so callers never send an empty UUID to GetByStoreID. - resolveBoundEngine constructs engineInfos directly (with slices.Clone of Support()) instead of going through NewCompositeRetrieveEngine. The latter only reads from the byEngineType map and cannot reach DB stores in byStoreID -- multiple stores can share the same engine type. Unbound fallbacks still reuse NewCompositeRetrieveEngine so the tenant effective-engines path is byte-for-byte unchanged. - DeleteKnowledgeBase now reads the KB before soft-delete so the enqueued KBDeletePayload carries a VectorStoreID snapshot; once the row is soft-deleted GORM's default scope hides it. Cost: +1 SELECT per KB-delete request (a rare admin operation). - enqueueIndexDeleteTask gains a vectorStoreID *string parameter that the single caller (tag.go) populates from the owning KB. The worker (ProcessIndexDelete) validates ownership via the factory. - cleanupKnowledgeResources loads the KB so bound-store cleanup routes correctly. If the load fails it warns and falls back to tenant effective engines; orphan vectors become observable in logs instead of disappearing silently. - DeleteKnowledges (batch) stays on the tenant effective-engines path -- batches can span stores and multi-store fan-out is PR4 scope. Noted inline. Merge safety All knowledge bases have VectorStoreID = NULL at merge time (introduced nullable in PR1, Tencent/WeKnora#994). Every factory call falls back to NewCompositeRetrieveEngine(registry, tenantInfo.GetEffectiveEngines()), which is the existing code path for these KBs. Async payloads from before this change decode to VectorStoreID = nil (omitempty) and take the same fallback. Testing - go build ./... - go vet ./... - go test -race -count=1 ./internal/application/service/retriever/... covers unbound (nil/empty), bound, cross-tenant, unregistered store, ownership infra error, legacy payload shapes (missing field/null/ empty string/nil), tampered payload, and parallel invocation. - grep -r NewCompositeRetrieveEngine internal/application/service returns zero results outside factory.go/composite.go. Refs: Part of Tencent/WeKnora#993. Depends on Tencent/WeKnora#994.
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
package retriever
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Sentinel errors returned by factory functions. Callers may use errors.Is to
|
||||
// classify. User-facing responses MUST wrap or replace these with generic
|
||||
// messages — the sentinels intentionally omit store UUIDs to avoid enumeration
|
||||
// leaks. Structured logs inside the factory record the tenant/store IDs.
|
||||
var (
|
||||
// ErrTenantInfoMissing is returned when the factory needs a tenant from
|
||||
// context (synchronous, unbound KB path) and none is present.
|
||||
ErrTenantInfoMissing = errors.New("tenant info not found in context")
|
||||
|
||||
// ErrVectorStoreNotFound is returned when the store ID is not registered
|
||||
// (or an internal lookup for ownership failed). Async workers should treat
|
||||
// this as non-retryable.
|
||||
ErrVectorStoreNotFound = errors.New("vector store not available")
|
||||
|
||||
// ErrVectorStoreForbidden is returned when the resolved store is not
|
||||
// owned by the given tenant. This guards against cross-tenant access
|
||||
// in case the upstream validation layer has a gap. Async workers should
|
||||
// treat this as non-retryable.
|
||||
ErrVectorStoreForbidden = errors.New("vector store access denied")
|
||||
)
|
||||
|
||||
// TenantStoreOwnership abstracts the lookup used by factory functions to
|
||||
// verify that a given vector store ID is owned by the given tenant ID.
|
||||
//
|
||||
// Production implementations wrap the VectorStoreRepository; tests inject
|
||||
// in-memory fakes so they can cover the ownership branches without touching
|
||||
// a database.
|
||||
type TenantStoreOwnership interface {
|
||||
// StoreOwnedBy reports whether the store with the given ID is owned
|
||||
// by the given tenant. When the store does not exist, it returns
|
||||
// (false, nil). Errors are reserved for infrastructure failures such as
|
||||
// database connectivity issues.
|
||||
StoreOwnedBy(ctx context.Context, storeID string, tenantID uint64) (bool, error)
|
||||
}
|
||||
|
||||
// CreateRetrieveEngineForKB returns a CompositeRetrieveEngine resolved from
|
||||
// a KB's VectorStore binding.
|
||||
//
|
||||
// Resolution rules:
|
||||
//
|
||||
// - vectorStoreID == nil || *vectorStoreID == "" →
|
||||
// falls back to the tenant's effective engines (env-store flow driven
|
||||
// by RETRIEVE_DRIVER). TenantInfo is read from ctx.
|
||||
// - otherwise →
|
||||
// 1) ownership.StoreOwnedBy(*storeID, tenantID) must return true;
|
||||
// cross-tenant attempts yield ErrVectorStoreForbidden.
|
||||
// 2) registry.GetByStoreID(*storeID) must succeed;
|
||||
// unregistered stores yield ErrVectorStoreNotFound.
|
||||
// 3) the single engine is wrapped by NewCompositeRetrieveEngine so
|
||||
// that its Support()-based retriever-type matching is preserved.
|
||||
//
|
||||
// Use this for 23 synchronous call sites across the application services.
|
||||
// Async task handlers that cannot rely on ctx-based TenantInfo (currently:
|
||||
// ProcessKBDeleteTask, ProcessIndexDelete) must use
|
||||
// CreateRetrieveEngineFromPayload instead.
|
||||
func CreateRetrieveEngineForKB(
|
||||
ctx context.Context,
|
||||
registry interfaces.RetrieveEngineRegistry,
|
||||
ownership TenantStoreOwnership,
|
||||
tenantID uint64,
|
||||
vectorStoreID *string,
|
||||
) (*CompositeRetrieveEngine, error) {
|
||||
// Normalize nil and empty-string pointer to "unbound" so that callers
|
||||
// cannot accidentally route an empty UUID into GetByStoreID.
|
||||
if vectorStoreID == nil || *vectorStoreID == "" {
|
||||
tenantInfo, ok := types.TenantInfoFromContext(ctx)
|
||||
if !ok {
|
||||
return nil, ErrTenantInfoMissing
|
||||
}
|
||||
return NewCompositeRetrieveEngine(registry, tenantInfo.GetEffectiveEngines())
|
||||
}
|
||||
|
||||
return resolveBoundEngine(ctx, registry, ownership, tenantID, *vectorStoreID)
|
||||
}
|
||||
|
||||
// CreateRetrieveEngineFromPayload is the async-task variant. It does not
|
||||
// read TenantInfo from ctx because async handlers do not populate it.
|
||||
// Instead, tenantID is passed explicitly from the deserialized payload and
|
||||
// is verified against the store's tenant when vectorStoreID is non-empty.
|
||||
//
|
||||
// Tasks enqueued before vectorStoreID was added to the payload decode it as
|
||||
// nil and transparently fall back to the pre-serialized effectiveEngines
|
||||
// path — no in-flight task is lost across upgrades.
|
||||
func CreateRetrieveEngineFromPayload(
|
||||
ctx context.Context,
|
||||
registry interfaces.RetrieveEngineRegistry,
|
||||
ownership TenantStoreOwnership,
|
||||
tenantID uint64,
|
||||
effectiveEngines []types.RetrieverEngineParams,
|
||||
vectorStoreID *string,
|
||||
) (*CompositeRetrieveEngine, error) {
|
||||
if vectorStoreID == nil || *vectorStoreID == "" {
|
||||
return NewCompositeRetrieveEngine(registry, effectiveEngines)
|
||||
}
|
||||
|
||||
return resolveBoundEngine(ctx, registry, ownership, tenantID, *vectorStoreID)
|
||||
}
|
||||
|
||||
// resolveBoundEngine is the shared ownership-verified lookup path used by
|
||||
// both CreateRetrieveEngineForKB and CreateRetrieveEngineFromPayload. It
|
||||
// returns sentinel errors so that handlers can classify them (for example,
|
||||
// async workers convert Forbidden/NotFound into asynq.SkipRetry).
|
||||
func resolveBoundEngine(
|
||||
ctx context.Context,
|
||||
registry interfaces.RetrieveEngineRegistry,
|
||||
ownership TenantStoreOwnership,
|
||||
tenantID uint64,
|
||||
storeID string,
|
||||
) (*CompositeRetrieveEngine, error) {
|
||||
owned, err := ownership.StoreOwnedBy(ctx, storeID, tenantID)
|
||||
if err != nil {
|
||||
// Infrastructure failure — record the raw error for operators but
|
||||
// do not leak internals to the caller.
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"store_id": storeID,
|
||||
"reason": "ownership lookup failed",
|
||||
})
|
||||
return nil, ErrVectorStoreNotFound
|
||||
}
|
||||
if !owned {
|
||||
// Cross-tenant attempt (or the store has been deleted in the
|
||||
// meantime). Log with WARN so that audits can surface probing.
|
||||
logger.Warnf(ctx,
|
||||
"[retriever.factory] cross-tenant store access attempted: tenant=%d store=%s",
|
||||
tenantID, storeID)
|
||||
return nil, ErrVectorStoreForbidden
|
||||
}
|
||||
|
||||
svc, err := registry.GetByStoreID(storeID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"store_id": storeID,
|
||||
"reason": "store not registered",
|
||||
})
|
||||
return nil, ErrVectorStoreNotFound
|
||||
}
|
||||
|
||||
// Build the composite directly from the resolved service.
|
||||
//
|
||||
// We cannot delegate to NewCompositeRetrieveEngine here because that
|
||||
// function resolves engines through registry.GetRetrieveEngineService,
|
||||
// which reads from the byEngineType map (env stores). DB stores live
|
||||
// in the byStoreID map and are not reachable via engine type alone —
|
||||
// multiple stores can share the same engine type.
|
||||
//
|
||||
// Semantics: a KB bound to a DB store uses every retriever type that
|
||||
// store supports. This intentionally overrides the tenant-level
|
||||
// effective-engines filter, because binding a KB to a specific store
|
||||
// is an explicit opt-out of tenant-default routing.
|
||||
return &CompositeRetrieveEngine{
|
||||
engineInfos: []*engineInfo{{
|
||||
retrieveEngine: svc,
|
||||
retrieverType: slices.Clone(svc.Support()),
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package retriever
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ----- test fakes -----
|
||||
|
||||
// fakeOwnership is an in-memory TenantStoreOwnership implementation.
|
||||
// All mutable state is guarded by mu so that the race test exercises a
|
||||
// safe fake and surfaces only genuine races inside the factory code.
|
||||
type fakeOwnership struct {
|
||||
mu sync.Mutex
|
||||
// owned maps storeID → tenantID that owns it. Absence means "not owned".
|
||||
owned map[string]uint64
|
||||
// err, when non-nil, is returned from every StoreOwnedBy call
|
||||
// (used to simulate infrastructure failures).
|
||||
err error
|
||||
// calls records every (storeID, tenantID) pair asked. Tests use this
|
||||
// to assert that the factory short-circuits to the fallback path
|
||||
// without calling ownership when vectorStoreID is nil/empty.
|
||||
calls []ownershipCall
|
||||
}
|
||||
|
||||
type ownershipCall struct {
|
||||
storeID string
|
||||
tenantID uint64
|
||||
}
|
||||
|
||||
func (f *fakeOwnership) StoreOwnedBy(ctx context.Context, storeID string, tenantID uint64) (bool, error) {
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, ownershipCall{storeID: storeID, tenantID: tenantID})
|
||||
err := f.err
|
||||
ownedTenant, ok := f.owned[storeID]
|
||||
f.mu.Unlock()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return ok && ownedTenant == tenantID, nil
|
||||
}
|
||||
|
||||
// callCount returns the number of StoreOwnedBy calls recorded so far.
|
||||
// Safe for concurrent use alongside StoreOwnedBy.
|
||||
func (f *fakeOwnership) callCount() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.calls)
|
||||
}
|
||||
|
||||
// fakeEngine implements interfaces.RetrieveEngineService with only the
|
||||
// methods that factory paths exercise. All other methods panic so that
|
||||
// accidental use during testing is loud.
|
||||
type fakeEngine struct {
|
||||
engineType types.RetrieverEngineType
|
||||
support []types.RetrieverType
|
||||
}
|
||||
|
||||
func (f *fakeEngine) EngineType() types.RetrieverEngineType { return f.engineType }
|
||||
|
||||
func (f *fakeEngine) Support() []types.RetrieverType { return f.support }
|
||||
|
||||
func (f *fakeEngine) Retrieve(ctx context.Context, _ types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
panic("fakeEngine.Retrieve: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) Index(ctx context.Context, _ embedding.Embedder, _ *types.IndexInfo, _ []types.RetrieverType) error {
|
||||
panic("fakeEngine.Index: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) BatchIndex(ctx context.Context, _ embedding.Embedder, _ []*types.IndexInfo, _ []types.RetrieverType) error {
|
||||
panic("fakeEngine.BatchIndex: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) EstimateStorageSize(ctx context.Context, _ embedding.Embedder, _ []*types.IndexInfo, _ []types.RetrieverType) int64 {
|
||||
panic("fakeEngine.EstimateStorageSize: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) CopyIndices(ctx context.Context, _ string, _ map[string]string, _ map[string]string, _ string, _ int, _ string) error {
|
||||
panic("fakeEngine.CopyIndices: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) DeleteByChunkIDList(ctx context.Context, _ []string, _ int, _ string) error {
|
||||
panic("fakeEngine.DeleteByChunkIDList: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) DeleteBySourceIDList(ctx context.Context, _ []string, _ int, _ string) error {
|
||||
panic("fakeEngine.DeleteBySourceIDList: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) DeleteByKnowledgeIDList(ctx context.Context, _ []string, _ int, _ string) error {
|
||||
panic("fakeEngine.DeleteByKnowledgeIDList: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) BatchUpdateChunkEnabledStatus(ctx context.Context, _ map[string]bool) error {
|
||||
panic("fakeEngine.BatchUpdateChunkEnabledStatus: not used in factory tests")
|
||||
}
|
||||
|
||||
func (f *fakeEngine) BatchUpdateChunkTagID(ctx context.Context, _ map[string]string) error {
|
||||
panic("fakeEngine.BatchUpdateChunkTagID: not used in factory tests")
|
||||
}
|
||||
|
||||
// registryWithStores builds a registry with the given storeID → service
|
||||
// pairs populated in the byStoreID map. Engine-type entries are also
|
||||
// registered so that the unbound path can resolve engines via the
|
||||
// tenant's effective engines.
|
||||
func registryWithStores(t *testing.T, stores map[string]*fakeEngine, engineTypes map[types.RetrieverEngineType]*fakeEngine) *RetrieveEngineRegistry {
|
||||
t.Helper()
|
||||
r := &RetrieveEngineRegistry{
|
||||
byEngineType: map[types.RetrieverEngineType]interfaces.RetrieveEngineService{},
|
||||
byStoreID: map[string]interfaces.RetrieveEngineService{},
|
||||
}
|
||||
for id, svc := range stores {
|
||||
r.byStoreID[id] = svc
|
||||
}
|
||||
for et, svc := range engineTypes {
|
||||
r.byEngineType[et] = svc
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// newTenantCtx returns a context carrying a Tenant with the given
|
||||
// EffectiveEngines. Factory's unbound path consumes this via
|
||||
// types.TenantInfoFromContext.
|
||||
func newTenantCtx(engines []types.RetrieverEngineParams) context.Context {
|
||||
tenant := &types.Tenant{
|
||||
RetrieverEngines: types.RetrieverEngines{Engines: engines},
|
||||
}
|
||||
return context.WithValue(context.Background(), types.TenantInfoContextKey, tenant)
|
||||
}
|
||||
|
||||
// ----- CreateRetrieveEngineForKB -----
|
||||
|
||||
func TestCreateRetrieveEngineForKB_Unbound(t *testing.T) {
|
||||
postgresEngine := &fakeEngine{
|
||||
engineType: types.PostgresRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType},
|
||||
}
|
||||
registry := registryWithStores(t, nil, map[types.RetrieverEngineType]*fakeEngine{
|
||||
types.PostgresRetrieverEngineType: postgresEngine,
|
||||
})
|
||||
ownership := &fakeOwnership{}
|
||||
|
||||
tenantCtx := newTenantCtx([]types.RetrieverEngineParams{
|
||||
{RetrieverEngineType: types.PostgresRetrieverEngineType, RetrieverType: types.VectorRetrieverType},
|
||||
})
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
store *string
|
||||
}{
|
||||
{"nil pointer", nil},
|
||||
{"empty string pointer", strPtr("")},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
engine, err := CreateRetrieveEngineForKB(tenantCtx, registry, ownership, 1, tc.store)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, engine)
|
||||
assert.Len(t, engine.engineInfos, 1, "unbound path uses tenant effective engines")
|
||||
assert.Same(t, postgresEngine, engine.engineInfos[0].retrieveEngine)
|
||||
assert.Zero(t, ownership.callCount(),
|
||||
"ownership must not be called on the unbound path")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRetrieveEngineForKB_UnboundMissingTenant(t *testing.T) {
|
||||
registry := registryWithStores(t, nil, nil)
|
||||
ownership := &fakeOwnership{}
|
||||
|
||||
_, err := CreateRetrieveEngineForKB(context.Background(), registry, ownership, 1, nil)
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrTenantInfoMissing),
|
||||
"err %q must wrap ErrTenantInfoMissing", err)
|
||||
}
|
||||
|
||||
func TestCreateRetrieveEngineForKB_StoreBound(t *testing.T) {
|
||||
esEngine := &fakeEngine{
|
||||
engineType: types.ElasticsearchRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType},
|
||||
}
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"store-A": esEngine},
|
||||
nil,
|
||||
)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 1}}
|
||||
|
||||
storeID := "store-A"
|
||||
engine, err := CreateRetrieveEngineForKB(context.Background(), registry, ownership, 1, &storeID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, engine)
|
||||
require.Len(t, engine.engineInfos, 1)
|
||||
assert.Same(t, esEngine, engine.engineInfos[0].retrieveEngine)
|
||||
assert.Equal(t,
|
||||
[]types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType},
|
||||
engine.engineInfos[0].retrieverType,
|
||||
"store-bound KB uses every retriever type the store supports")
|
||||
}
|
||||
|
||||
func TestCreateRetrieveEngineForKB_CrossTenant(t *testing.T) {
|
||||
esEngine := &fakeEngine{
|
||||
engineType: types.ElasticsearchRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.VectorRetrieverType},
|
||||
}
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"store-A": esEngine},
|
||||
nil,
|
||||
)
|
||||
// store-A is owned by tenant 2, not tenant 1
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 2}}
|
||||
|
||||
storeID := "store-A"
|
||||
_, err := CreateRetrieveEngineForKB(context.Background(), registry, ownership, 1, &storeID)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrVectorStoreForbidden),
|
||||
"cross-tenant access must yield ErrVectorStoreForbidden; got %q", err)
|
||||
// Sanity: no store UUID in the sentinel's message — the structured log
|
||||
// emitted inside the factory is where UUIDs live. The user-visible
|
||||
// error is intentionally opaque.
|
||||
assert.NotContains(t, err.Error(), "store-A",
|
||||
"sentinel error must not expose store UUIDs to callers")
|
||||
}
|
||||
|
||||
func TestCreateRetrieveEngineForKB_StoreNotRegistered(t *testing.T) {
|
||||
// Ownership says the tenant owns the store, but registry has not
|
||||
// loaded it. This happens when a VectorStore row exists in the DB
|
||||
// but its engine initialization failed at app start.
|
||||
registry := registryWithStores(t, nil, nil)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 1}}
|
||||
|
||||
storeID := "store-A"
|
||||
_, err := CreateRetrieveEngineForKB(context.Background(), registry, ownership, 1, &storeID)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrVectorStoreNotFound),
|
||||
"unregistered store must yield ErrVectorStoreNotFound; got %q", err)
|
||||
}
|
||||
|
||||
func TestCreateRetrieveEngineForKB_OwnershipLookupError(t *testing.T) {
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"store-A": {engineType: types.PostgresRetrieverEngineType}},
|
||||
nil,
|
||||
)
|
||||
ownership := &fakeOwnership{err: errors.New("db connection refused")}
|
||||
|
||||
storeID := "store-A"
|
||||
_, err := CreateRetrieveEngineForKB(context.Background(), registry, ownership, 1, &storeID)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrVectorStoreNotFound),
|
||||
"ownership infrastructure error must collapse to ErrVectorStoreNotFound; got %q", err)
|
||||
}
|
||||
|
||||
// ----- CreateRetrieveEngineFromPayload -----
|
||||
|
||||
func TestCreateRetrieveEngineFromPayload_LegacyUnbound(t *testing.T) {
|
||||
// Four ways a payload can express "no binding": missing field,
|
||||
// explicit null, empty string, and programmatically nil. All four
|
||||
// should take the fallback path using the payload's effectiveEngines.
|
||||
postgresEngine := &fakeEngine{
|
||||
engineType: types.PostgresRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.VectorRetrieverType},
|
||||
}
|
||||
registry := registryWithStores(t, nil, map[types.RetrieverEngineType]*fakeEngine{
|
||||
types.PostgresRetrieverEngineType: postgresEngine,
|
||||
})
|
||||
ownership := &fakeOwnership{}
|
||||
engines := []types.RetrieverEngineParams{{
|
||||
RetrieverEngineType: types.PostgresRetrieverEngineType,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
}}
|
||||
|
||||
// simulate payload decoding from JSON for each legacy shape
|
||||
decode := func(t *testing.T, body string) *string {
|
||||
t.Helper()
|
||||
var p types.KBDeletePayload
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &p))
|
||||
return p.VectorStoreID
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
ptr *string
|
||||
}{
|
||||
{"missing field", decode(t, `{"tenant_id":1}`)},
|
||||
{"explicit null", decode(t, `{"tenant_id":1,"vector_store_id":null}`)},
|
||||
{"empty string", decode(t, `{"tenant_id":1,"vector_store_id":""}`)},
|
||||
{"programmatic nil", nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
engine, err := CreateRetrieveEngineFromPayload(
|
||||
context.Background(), registry, ownership, 1, engines, tc.ptr)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, engine)
|
||||
require.Len(t, engine.engineInfos, 1)
|
||||
assert.Same(t, postgresEngine, engine.engineInfos[0].retrieveEngine)
|
||||
assert.Zero(t, ownership.callCount(),
|
||||
"unbound payload must not trigger ownership lookup")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRetrieveEngineFromPayload_Bound(t *testing.T) {
|
||||
qdrantEngine := &fakeEngine{
|
||||
engineType: types.QdrantRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.VectorRetrieverType},
|
||||
}
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"qd-1": qdrantEngine},
|
||||
nil,
|
||||
)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"qd-1": 42}}
|
||||
|
||||
storeID := "qd-1"
|
||||
engine, err := CreateRetrieveEngineFromPayload(
|
||||
context.Background(), registry, ownership, 42, nil, &storeID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, engine)
|
||||
require.Len(t, engine.engineInfos, 1)
|
||||
assert.Same(t, qdrantEngine, engine.engineInfos[0].retrieveEngine)
|
||||
}
|
||||
|
||||
func TestCreateRetrieveEngineFromPayload_TamperedCrossTenant(t *testing.T) {
|
||||
esEngine := &fakeEngine{engineType: types.ElasticsearchRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.VectorRetrieverType}}
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"store-A": esEngine}, nil)
|
||||
// Store is owned by tenant 99, but the (possibly tampered) payload
|
||||
// claims tenant 1. Factory must reject.
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 99}}
|
||||
|
||||
storeID := "store-A"
|
||||
_, err := CreateRetrieveEngineFromPayload(
|
||||
context.Background(), registry, ownership, 1,
|
||||
[]types.RetrieverEngineParams{}, &storeID)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrVectorStoreForbidden))
|
||||
}
|
||||
|
||||
// ----- Race -----
|
||||
|
||||
// TestFactoryParallelInvocation is primarily meaningful when run under
|
||||
// `go test -race`. Factory functions themselves are stateless; the test
|
||||
// guards against accidental shared state being introduced later.
|
||||
func TestFactoryParallelInvocation(t *testing.T) {
|
||||
esEngine := &fakeEngine{
|
||||
engineType: types.ElasticsearchRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.VectorRetrieverType},
|
||||
}
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"store-A": esEngine},
|
||||
nil,
|
||||
)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 1}}
|
||||
|
||||
done := make(chan error, 16)
|
||||
for i := 0; i < 16; i++ {
|
||||
go func() {
|
||||
storeID := "store-A"
|
||||
_, err := CreateRetrieveEngineForKB(
|
||||
context.Background(), registry, ownership, 1, &storeID)
|
||||
done <- err
|
||||
}()
|
||||
}
|
||||
for i := 0; i < 16; i++ {
|
||||
if err := <-done; err != nil {
|
||||
t.Errorf("concurrent call %d failed: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----- helpers -----
|
||||
|
||||
func strPtr(s string) *string { return &s }
|
||||
@@ -0,0 +1,35 @@
|
||||
package retriever
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// vectorStoreRepoOwnership adapts a VectorStoreRepository to the
|
||||
// TenantStoreOwnership interface consumed by the factory functions.
|
||||
//
|
||||
// The repository's GetByID already scopes to the given tenantID
|
||||
// (WHERE id = ? AND tenant_id = ?), so "exists under this tenant"
|
||||
// is equivalent to "owned by this tenant" — no additional tenant
|
||||
// comparison is needed on top of the returned row.
|
||||
type vectorStoreRepoOwnership struct {
|
||||
repo interfaces.VectorStoreRepository
|
||||
}
|
||||
|
||||
// NewVectorStoreRepoOwnership returns the production
|
||||
// TenantStoreOwnership implementation backed by VectorStoreRepository.
|
||||
func NewVectorStoreRepoOwnership(repo interfaces.VectorStoreRepository) TenantStoreOwnership {
|
||||
return &vectorStoreRepoOwnership{repo: repo}
|
||||
}
|
||||
|
||||
// StoreOwnedBy returns true iff a vector store with the given ID exists
|
||||
// under the given tenant. Errors are reserved for infrastructure failures;
|
||||
// a non-existent (but well-formed) store ID returns (false, nil).
|
||||
func (o *vectorStoreRepoOwnership) StoreOwnedBy(ctx context.Context, storeID string, tenantID uint64) (bool, error) {
|
||||
store, err := o.repo.GetByID(ctx, tenantID, storeID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return store != nil, nil
|
||||
}
|
||||
@@ -112,3 +112,7 @@ func (r *RetrieveEngineRegistry) UnregisterByStoreID(storeID string) {
|
||||
|
||||
delete(r.byStoreID, storeID)
|
||||
}
|
||||
|
||||
// Compile-time assertion: *RetrieveEngineRegistry satisfies the
|
||||
// interfaces.RetrieveEngineRegistry contract, including GetByStoreID.
|
||||
var _ interfaces.RetrieveEngineRegistry = (*RetrieveEngineRegistry)(nil)
|
||||
|
||||
Reference in New Issue
Block a user