WeKnora/internal/application/repository/knowledgebase.go

275 lines
9.6 KiB
Go
Raw Normal View History

2025-08-05 07:08:07 +00:00
package repository
import (
"context"
"errors"
"time"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
var ErrKnowledgeBaseNotFound = errors.New("knowledge base not found")
// knowledgeBaseRepository implements the KnowledgeBaseRepository interface
type knowledgeBaseRepository struct {
db *gorm.DB
}
// NewKnowledgeBaseRepository creates a new knowledge base repository
func NewKnowledgeBaseRepository(db *gorm.DB) interfaces.KnowledgeBaseRepository {
return &knowledgeBaseRepository{db: db}
}
// CreateKnowledgeBase creates a new knowledge base
func (r *knowledgeBaseRepository) CreateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error {
return r.db.WithContext(ctx).Create(kb).Error
}
// GetKnowledgeBaseByID gets a knowledge base by id (no tenant scope; caller must enforce isolation where needed)
2025-08-05 07:08:07 +00:00
func (r *knowledgeBaseRepository) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
var kb types.KnowledgeBase
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&kb).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrKnowledgeBaseNotFound
}
return nil, err
}
return &kb, nil
}
// GetKnowledgeBaseByIDAndTenant gets a knowledge base by id only if it belongs to the given tenant (enforces tenant isolation)
func (r *knowledgeBaseRepository) GetKnowledgeBaseByIDAndTenant(ctx context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error) {
var kb types.KnowledgeBase
if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&kb).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrKnowledgeBaseNotFound
}
return nil, err
}
return &kb, nil
}
// GetKnowledgeBaseByIDs gets knowledge bases by multiple ids
func (r *knowledgeBaseRepository) GetKnowledgeBaseByIDs(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error) {
if len(ids) == 0 {
return []*types.KnowledgeBase{}, nil
}
var kbs []*types.KnowledgeBase
if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&kbs).Error; err != nil {
return nil, err
}
return kbs, nil
}
2025-08-05 07:08:07 +00:00
// ListKnowledgeBases lists all knowledge bases
func (r *knowledgeBaseRepository) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
var kbs []*types.KnowledgeBase
if err := r.db.WithContext(ctx).Find(&kbs).Error; err != nil {
return nil, err
}
return kbs, nil
}
// ListKnowledgeBasesByTenantID lists all knowledge bases by tenant id.
//
// Ordering used to also include `is_pinned DESC, pinned_at DESC` so the
// repository would return tenant-wide pinned rows first. That column is
// no longer the source of truth (see migration 000050) — pin state is
// now per (user, kb) and applied by the service layer after enrichment.
// We keep `created_at DESC` here so callers that don't enrich (chat
// pipeline, agent editor, IM commands) still get a stable ordering.
2025-08-05 07:08:07 +00:00
func (r *knowledgeBaseRepository) ListKnowledgeBasesByTenantID(
ctx context.Context, tenantID uint64,
2025-08-05 07:08:07 +00:00
) ([]*types.KnowledgeBase, error) {
var kbs []*types.KnowledgeBase
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND is_temporary = ?", tenantID, false).
Order("created_at DESC").Find(&kbs).Error; err != nil {
2025-08-05 07:08:07 +00:00
return nil, err
}
return kbs, nil
}
// userKBPinRow mirrors the user_kb_pins table. Kept local to the
// repository because it never escapes the package; callers see the
// higher-level map[kb_id]pinned_at returned by ListUserKBPinIDs.
type userKBPinRow struct {
TenantID uint64 `gorm:"column:tenant_id"`
UserID string `gorm:"column:user_id"`
KBID string `gorm:"column:kb_id"`
PinnedAt time.Time `gorm:"column:pinned_at"`
}
func (userKBPinRow) TableName() string { return "user_kb_pins" }
// SetUserKBPin upserts (pinned=true) or deletes (pinned=false) the row
// for the given (tenant, user, kb) triple. The returned pinned_at is
// nil when pinned=false; otherwise it carries the timestamp written
// to the row (either the existing one if the row already existed, or
// the current time on insert) so the caller can stamp the response
// without a follow-up SELECT.
func (r *knowledgeBaseRepository) SetUserKBPin(
ctx context.Context, tenantID uint64, userID string, kbID string, pinned bool,
) (*time.Time, error) {
if userID == "" {
return nil, errors.New("user_kb_pins: empty user_id")
}
if !pinned {
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND kb_id = ?", tenantID, userID, kbID).
Delete(&userKBPinRow{}).Error
if err != nil {
return nil, err
}
return nil, nil
}
// Upsert with idempotent INSERT … ON CONFLICT DO NOTHING. We then
// SELECT to learn whether an existing row's pinned_at survived (so
// repeated calls return a stable timestamp instead of bumping it).
row := userKBPinRow{
TenantID: tenantID,
UserID: userID,
KBID: kbID,
PinnedAt: time.Now(),
}
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND kb_id = ?", tenantID, userID, kbID).
Attrs(userKBPinRow{PinnedAt: row.PinnedAt}).
FirstOrCreate(&row).Error; err != nil {
return nil, err
}
pa := row.PinnedAt
return &pa, nil
}
// ListUserKBPinIDs returns every KB id this user has personally pinned
// in this tenant, mapped to its pinned_at. Returns an empty map (not
// nil) when there are no pins, so callers can do `len(m) == 0` checks
// without a nil guard.
func (r *knowledgeBaseRepository) ListUserKBPinIDs(
ctx context.Context, tenantID uint64, userID string,
) (map[string]time.Time, error) {
out := make(map[string]time.Time)
if userID == "" {
return out, nil
}
var rows []userKBPinRow
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ?", tenantID, userID).
Find(&rows).Error; err != nil {
return nil, err
}
for _, row := range rows {
out[row.KBID] = row.PinnedAt
}
return out, nil
}
2025-08-05 07:08:07 +00:00
// UpdateKnowledgeBase updates a knowledge base
func (r *knowledgeBaseRepository) UpdateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error {
return r.db.WithContext(ctx).Save(kb).Error
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
// UpdateKnowledgeBaseGeneratedProfile writes the generated_profile column
// only. The rest of the row is left untouched so a settings save that lands
// while a profile is being generated is not overwritten by the worker.
func (r *knowledgeBaseRepository) UpdateKnowledgeBaseGeneratedProfile(
ctx context.Context, id string, profile *types.KnowledgeBaseProfile,
) error {
if id == "" {
return errors.New("knowledge base ID cannot be empty")
}
var value interface{}
if profile != nil {
value = *profile
}
return r.db.WithContext(ctx).Model(&types.KnowledgeBase{}).
Where("id = ?", id).
Updates(map[string]interface{}{
"generated_profile": value,
"updated_at": time.Now(),
}).Error
}
2025-08-05 07:08:07 +00:00
// DeleteKnowledgeBase deletes a knowledge base
func (r *knowledgeBaseRepository) DeleteKnowledgeBase(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.KnowledgeBase{}).Error
}
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
// CountByVectorStoreID counts active knowledge bases that are bound to the
// given vector store within a tenant scope.
//
// Soft-delete filter is applied automatically by GORM because KnowledgeBase
// has a gorm.DeletedAt column — we deliberately do not add an explicit
// `deleted_at IS NULL` predicate to keep the single source of truth on the
// auto-scope.
//
// Pass db == nil to use the repository's default db handle; pass a *gorm.DB
// bound to a transaction (e.g., from db.Transaction) to share the same
// write-lock context as the caller. Query column order matches the
// composite index idx_knowledge_bases_tenant_vector_store(tenant_id,
// vector_store_id).
func (r *knowledgeBaseRepository) CountByVectorStoreID(
ctx context.Context, db *gorm.DB, tenantID uint64, storeID string,
) (int64, error) {
if db == nil {
db = r.db
}
var count int64
err := db.WithContext(ctx).
Model(&types.KnowledgeBase{}).
Where("tenant_id = ? AND vector_store_id = ?", tenantID, storeID).
Count(&count).Error
return count, err
}
// CountByModelID counts active knowledge bases that reference modelID in any
// model-binding column (scalar fields or JSON config blobs).
func (r *knowledgeBaseRepository) CountByModelID(
ctx context.Context, tenantID uint64, modelID string,
) (int64, error) {
var count int64
query := r.db.WithContext(ctx).
Model(&types.KnowledgeBase{}).
Where("tenant_id = ?", tenantID)
query = scopeKnowledgeBasesByModelID(query, modelID)
err := query.Count(&count).Error
return count, err
}
// ListModelUsages returns active knowledge bases that reference modelID. It
// selects only the columns needed to identify the resource and its bindings;
// GORM's default scope excludes soft-deleted rows.
func (r *knowledgeBaseRepository) ListModelUsages(
ctx context.Context, tenantID uint64, modelID string,
) ([]types.ModelUsageResource, error) {
rows := make([]*types.KnowledgeBase, 0)
query := r.db.WithContext(ctx).
Model(&types.KnowledgeBase{}).
Select(
"id", "name", "embedding_model_id", "summary_model_id",
"image_processing_config", "vlm_config", "asr_config", "wiki_config", "auto_tag_config",
).
Where("tenant_id = ?", tenantID)
query = scopeKnowledgeBasesByModelID(query, modelID)
if err := query.Order("name ASC, id ASC").Limit(types.ModelUsageListLimit).Find(&rows).Error; err != nil {
return nil, err
}
usages := make([]types.ModelUsageResource, 0, len(rows))
for _, row := range rows {
bindings := knowledgeBaseModelUsageBindings(row, modelID)
if len(bindings) == 0 {
continue
}
usages = append(usages, types.ModelUsageResource{
ID: row.ID,
Name: row.Name,
Bindings: bindings,
})
}
return usages, nil
}