2025-08-05 07:08:07 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2025-09-24 04:15:17 +00:00
|
|
|
"encoding/json"
|
2025-08-05 07:08:07 +00:00
|
|
|
"errors"
|
2026-06-02 11:25:38 +00:00
|
|
|
"fmt"
|
2026-05-18 03:58:46 +00:00
|
|
|
"sort"
|
2026-05-29 05:36:06 +00:00
|
|
|
"strings"
|
2025-08-05 07:08:07 +00:00
|
|
|
"time"
|
|
|
|
|
|
2026-09-08 07:36:33 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/application/access"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/application/repository"
|
2025-08-05 07:08:07 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
2026-06-23 07:45:52 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/datasource"
|
2026-05-18 01:10:01 +00:00
|
|
|
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
2025-08-05 07:08:07 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
2026-07-15 02:57:32 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/storageallowlist"
|
feat(observability): extend Langfuse tracing across asynq pipeline
Previously the Langfuse integration only traced in-process HTTP requests
(chat / search / eval), so file uploads and every downstream asynq task
(document parse, chunk embedding, OCR/VLM, summary / question gen, wiki
ingest, datasource sync, etc.) produced either disconnected shallow
traces or no observation at all.
This change threads one trace end-to-end:
- tracer: add SPAN observation type and StartSpan; add ResumeTrace so a
worker can attach to an upstream trace without emitting a duplicate
trace-create; StartGeneration now auto-picks parentObservationId from
ctx so nested trace -> span -> generation trees render correctly.
- types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq
payloads so trace_id / parent_obs_id / user_id / session_id serialise
into every job.
- langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal
so the HTTP-layer trace survives the Redis hop.
- langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either
resumes the upstream trace or opens a standalone asynq.<type> trace
for scheduled jobs, and wraps the handler in a SPAN with task metadata
(id / queue / retry / payload_bytes) plus ERROR level on failure.
- GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation /
FAQ / wiki / datasource endpoints so the root trace actually starts.
- Tests: tracer_test.go covers span nesting, error status, and
ResumeTrace no-trace-create guarantee; asynq_test.go covers
InjectTracing round-trip, middleware resume path, and standalone
trace fallback.
- Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types
and documents the cross-process propagation model.
No behavioural change when Langfuse is disabled (all new code paths are
no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
2025-08-05 07:08:07 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
2026-05-18 01:10:01 +00:00
|
|
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
2025-08-05 07:08:07 +00:00
|
|
|
"github.com/google/uuid"
|
2025-12-25 11:33:58 +00:00
|
|
|
"github.com/hibiken/asynq"
|
2025-08-05 07:08:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// ErrInvalidTenantID represents an error for invalid tenant ID
|
|
|
|
|
var ErrInvalidTenantID = errors.New("invalid tenant ID")
|
|
|
|
|
|
2026-07-22 20:51:40 +00:00
|
|
|
const kbTaskCleanupTimeout = 5 * time.Second
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
// knowledgeBaseService implements the knowledge base service interface
|
|
|
|
|
type knowledgeBaseService struct {
|
2026-07-15 05:26:29 +00:00
|
|
|
repo interfaces.KnowledgeBaseRepository
|
|
|
|
|
kgRepo interfaces.KnowledgeRepository
|
|
|
|
|
chunkRepo interfaces.ChunkRepository
|
|
|
|
|
shareRepo interfaces.KBShareRepository
|
|
|
|
|
kbShareService interfaces.KBShareService
|
|
|
|
|
modelService interfaces.ModelService
|
|
|
|
|
retrieveEngine interfaces.RetrieveEngineRegistry
|
|
|
|
|
ownership retriever.TenantStoreOwnership
|
|
|
|
|
tenantRepo interfaces.TenantRepository
|
|
|
|
|
fileSvc interfaces.FileService
|
|
|
|
|
storageResolver interfaces.StorageBackendResolver
|
|
|
|
|
graphEngine interfaces.RetrieveGraphRepository
|
|
|
|
|
asynqClient interfaces.TaskEnqueuer
|
2026-07-22 20:51:40 +00:00
|
|
|
taskInspector interfaces.TaskInspector
|
|
|
|
|
taskPendingRepo interfaces.TaskPendingOpsRepository
|
2026-07-15 05:26:29 +00:00
|
|
|
dsRepo interfaces.DataSourceRepository
|
|
|
|
|
syncLogRepo interfaces.SyncLogRepository
|
|
|
|
|
dsScheduler *datasource.Scheduler
|
2026-07-22 11:15:27 +00:00
|
|
|
audit interfaces.AuditLogService
|
2026-08-27 02:30:32 +00:00
|
|
|
resourceCatalog interfaces.ResourceCatalog
|
2026-09-14 13:02:31 +00:00
|
|
|
wikiRepo interfaces.WikiPageRepository
|
2025-08-05 07:08:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewKnowledgeBaseService creates a new knowledge base service
|
|
|
|
|
func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
|
|
|
|
kgRepo interfaces.KnowledgeRepository,
|
|
|
|
|
chunkRepo interfaces.ChunkRepository,
|
2026-01-30 08:28:01 +00:00
|
|
|
shareRepo interfaces.KBShareRepository,
|
|
|
|
|
kbShareService interfaces.KBShareService,
|
2025-08-05 07:08:07 +00:00
|
|
|
modelService interfaces.ModelService,
|
2025-11-11 14:26:59 +00:00
|
|
|
retrieveEngine interfaces.RetrieveEngineRegistry,
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
ownership retriever.TenantStoreOwnership,
|
2025-11-23 09:27:30 +00:00
|
|
|
tenantRepo interfaces.TenantRepository,
|
|
|
|
|
fileSvc interfaces.FileService,
|
2026-07-15 05:26:29 +00:00
|
|
|
storageResolver interfaces.StorageBackendResolver,
|
2025-11-23 09:27:30 +00:00
|
|
|
graphEngine interfaces.RetrieveGraphRepository,
|
2026-02-28 05:22:07 +00:00
|
|
|
asynqClient interfaces.TaskEnqueuer,
|
2026-07-22 20:51:40 +00:00
|
|
|
taskInspector interfaces.TaskInspector,
|
|
|
|
|
taskPendingRepo interfaces.TaskPendingOpsRepository,
|
2026-06-23 07:45:52 +00:00
|
|
|
dsRepo interfaces.DataSourceRepository,
|
|
|
|
|
syncLogRepo interfaces.SyncLogRepository,
|
|
|
|
|
dsScheduler *datasource.Scheduler,
|
2026-07-22 11:15:27 +00:00
|
|
|
audit interfaces.AuditLogService,
|
2026-08-27 02:30:32 +00:00
|
|
|
resourceCatalog interfaces.ResourceCatalog,
|
2026-09-14 13:02:31 +00:00
|
|
|
wikiRepo interfaces.WikiPageRepository,
|
2025-08-05 07:08:07 +00:00
|
|
|
) interfaces.KnowledgeBaseService {
|
|
|
|
|
return &knowledgeBaseService{
|
2026-07-15 05:26:29 +00:00
|
|
|
repo: repo,
|
|
|
|
|
kgRepo: kgRepo,
|
|
|
|
|
chunkRepo: chunkRepo,
|
|
|
|
|
shareRepo: shareRepo,
|
|
|
|
|
kbShareService: kbShareService,
|
|
|
|
|
modelService: modelService,
|
|
|
|
|
retrieveEngine: retrieveEngine,
|
|
|
|
|
ownership: ownership,
|
|
|
|
|
tenantRepo: tenantRepo,
|
|
|
|
|
fileSvc: fileSvc,
|
|
|
|
|
storageResolver: storageResolver,
|
|
|
|
|
graphEngine: graphEngine,
|
|
|
|
|
asynqClient: asynqClient,
|
2026-07-22 20:51:40 +00:00
|
|
|
taskInspector: taskInspector,
|
|
|
|
|
taskPendingRepo: taskPendingRepo,
|
2026-07-15 05:26:29 +00:00
|
|
|
dsRepo: dsRepo,
|
|
|
|
|
syncLogRepo: syncLogRepo,
|
|
|
|
|
dsScheduler: dsScheduler,
|
2026-07-22 11:15:27 +00:00
|
|
|
audit: audit,
|
2026-08-27 02:30:32 +00:00
|
|
|
resourceCatalog: resourceCatalog,
|
2026-09-14 13:02:31 +00:00
|
|
|
wikiRepo: wikiRepo,
|
2025-08-05 07:08:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-19 11:27:25 +00:00
|
|
|
// GetRepository gets the knowledge base repository
|
|
|
|
|
// Parameters:
|
|
|
|
|
// - ctx: Context with authentication and request information
|
|
|
|
|
//
|
|
|
|
|
// Returns:
|
|
|
|
|
// - interfaces.KnowledgeBaseRepository: Knowledge base repository
|
|
|
|
|
func (s *knowledgeBaseService) GetRepository() interfaces.KnowledgeBaseRepository {
|
|
|
|
|
return s.repo
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
// CreateKnowledgeBase creates a new knowledge base.
|
|
|
|
|
//
|
|
|
|
|
// When VectorStoreID is set, the binding is validated against the caller's
|
|
|
|
|
// tenant scope and the engine registry before persisting. A nil or
|
|
|
|
|
// empty-string VectorStoreID is normalized to nil ("use the tenant's
|
|
|
|
|
// effective engines") to match the retrieve-engine factory's pre-condition.
|
2025-08-05 07:08:07 +00:00
|
|
|
func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
|
|
|
|
|
kb *types.KnowledgeBase,
|
|
|
|
|
) (*types.KnowledgeBase, error) {
|
|
|
|
|
// Generate UUID and set creation timestamps
|
2025-08-10 09:04:39 +00:00
|
|
|
if kb.ID == "" {
|
|
|
|
|
kb.ID = uuid.New().String()
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
kb.CreatedAt = time.Now()
|
2026-02-28 10:11:37 +00:00
|
|
|
kb.TenantID = types.MustTenantIDFromContext(ctx)
|
2025-08-05 07:08:07 +00:00
|
|
|
kb.UpdatedAt = time.Now()
|
feat(rbac): enforce tenant role matrix on routes (PR 2 of 3, #1303)
Build on PR 1's tenant_members schema by enforcing the role matrix on
every authenticated route and at agent run time. Enforcement is gated
behind cfg.Tenant.EnableRBAC so the change ships dormant — the same
code paths log the would-be rejection during the rollout window and
start blocking once operators flip the flag.
Middleware (internal/middleware/rbac.go):
- RequireRole(min, cfg): role-only gate using TenantRole.HasPermission.
- RequireOwnershipOrRole(min, lookup, cfg): allows the original creator
through even when their role is below min, otherwise falls back to
the role check. Lookup errors fail closed; an empty creator_id is
treated as tenant-owned and requires the role.
- Both honour cfg.Tenant.EnableRBAC for the rollout window.
Creator lookups (internal/handler/rbac_lookups.go):
- KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID.
- AgentCreatorLookup resolves :id -> CustomAgent.CreatedBy; built-in
agents (IsBuiltin=true) return ("", nil) so they remain Admin+ only.
- Compile-time guards keep the methods aligned with CreatorLookup.
Route guards (internal/router/rbac.go + router.go):
- rbacGuards bundles the matrix into Viewer/Contributor/Admin/Owner
helpers plus OwnedKBOrAdmin / OwnedAgentOrAdmin. Each Register*
function takes *rbacGuards so route lines remain readable.
- KB / Agent / Knowledge / Chunk / Tenant / Model / MCPService /
VectorStore / DataSource / IMChannel routes annotated per the PR 1
design doc matrix. Tenant-wide infra (models, vector stores, MCP,
data sources, IM channels) reads as Viewer+ and writes as Admin+;
per-resource mutations on KB / Agent route through the
ownership-or-Admin guard.
Resource ownership (services):
- CreateKnowledgeBase / CopyKnowledgeBase populate CreatorID from the
authenticated user, so the OwnedKBOrAdmin guard has a creator to
match.
- CreateAgent / CopyAgent populate CreatedBy similarly. Built-in
agents stay tenant-owned.
Agent run-time gate (internal/handler/session/qa.go):
- AgentQA refuses to launch the agent engine for Viewers when the
target agent has RunnableByViewer=false. Same EnableRBAC gating as
the middleware so it's a no-op until enforcement is turned on.
Tests:
- 12 unit tests cover RequireRole / RequireOwnershipOrRole, including
the fail-open and fail-closed branches and the lookup-error path.
2026-05-13 13:16:54 +00:00
|
|
|
// Record the creator so RBAC's RequireOwnershipOrRole can let
|
|
|
|
|
// Contributors edit their own KBs without granting them tenant-wide
|
fix(rbac): address PR 2 review feedback
Middleware
- RequireOwnershipOrRole now skips the creator lookup entirely when
EnableRBAC is off, eliminating a hidden per-request DB roundtrip in
the rollout window.
- New ErrResourceNotFound sentinel lets lookups signal "not visible to
this tenant"; the middleware passes the request through so handlers
can return a real 404 instead of a misleading 403.
- Transient lookup failures now surface as 503 (was 403) so monitoring
can tell denied-by-policy from cannot-verify-right-now.
- Cross-tenant superusers (CanAccessAllTenants) bypass tenant role gates,
restoring DELETE /tenants/:id and ResetAPIKey for org operators that
resolve to Admin in foreign tenants.
- Construction-time warning fires once when cfg is nil/incomplete, so a
wiring bug that disables enforcement globally is visible at boot.
Route coverage
- Add role guards to FAQ, KnowledgeTag, WikiPage, Skill, WebSearch,
WebSearchProvider, WeKnoraCloud, Session, Chat, and Message route
groups so the matrix actually matches the PR description.
Service layer
- KB and agent creators are no longer recorded as the synthetic
system-<tenantID> user used by the X-API-Key path; resources stay
tenant-owned. New types.IsSyntheticUserID helper centralises the
prefix check.
- KBCreatorLookup and AgentCreatorLookup re-check tenant scope so a
same-ID resource in another tenant cannot piggyback through the
ownership shortcut.
Docs
- CustomAgent.RunnableByViewer comment now matches enforcement: it only
blocks Viewer-driven agent-mode runs, not plain RAG/Wiki QA.
Tests
- New cases for the 503/404 paths, lookup-skip behaviour, cross-tenant
superuser bypass, the lookup helpers (not-found, cross-tenant,
built-in agent, missing tenant context), and IsSyntheticUserID.
2026-05-13 13:37:47 +00:00
|
|
|
// edit rights. The X-API-Key auth path attaches a synthetic
|
|
|
|
|
// `system-<tenantID>` user; we deliberately skip those so the KB
|
|
|
|
|
// stays tenant-owned (CreatorID == ""), which matches the original
|
|
|
|
|
// API-key semantics (any human Admin can manage it) and prevents a
|
|
|
|
|
// later "list KBs by creator" feature from surfacing rows nobody can
|
|
|
|
|
// re-attribute.
|
|
|
|
|
if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) {
|
feat(rbac): enforce tenant role matrix on routes (PR 2 of 3, #1303)
Build on PR 1's tenant_members schema by enforcing the role matrix on
every authenticated route and at agent run time. Enforcement is gated
behind cfg.Tenant.EnableRBAC so the change ships dormant — the same
code paths log the would-be rejection during the rollout window and
start blocking once operators flip the flag.
Middleware (internal/middleware/rbac.go):
- RequireRole(min, cfg): role-only gate using TenantRole.HasPermission.
- RequireOwnershipOrRole(min, lookup, cfg): allows the original creator
through even when their role is below min, otherwise falls back to
the role check. Lookup errors fail closed; an empty creator_id is
treated as tenant-owned and requires the role.
- Both honour cfg.Tenant.EnableRBAC for the rollout window.
Creator lookups (internal/handler/rbac_lookups.go):
- KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID.
- AgentCreatorLookup resolves :id -> CustomAgent.CreatedBy; built-in
agents (IsBuiltin=true) return ("", nil) so they remain Admin+ only.
- Compile-time guards keep the methods aligned with CreatorLookup.
Route guards (internal/router/rbac.go + router.go):
- rbacGuards bundles the matrix into Viewer/Contributor/Admin/Owner
helpers plus OwnedKBOrAdmin / OwnedAgentOrAdmin. Each Register*
function takes *rbacGuards so route lines remain readable.
- KB / Agent / Knowledge / Chunk / Tenant / Model / MCPService /
VectorStore / DataSource / IMChannel routes annotated per the PR 1
design doc matrix. Tenant-wide infra (models, vector stores, MCP,
data sources, IM channels) reads as Viewer+ and writes as Admin+;
per-resource mutations on KB / Agent route through the
ownership-or-Admin guard.
Resource ownership (services):
- CreateKnowledgeBase / CopyKnowledgeBase populate CreatorID from the
authenticated user, so the OwnedKBOrAdmin guard has a creator to
match.
- CreateAgent / CopyAgent populate CreatedBy similarly. Built-in
agents stay tenant-owned.
Agent run-time gate (internal/handler/session/qa.go):
- AgentQA refuses to launch the agent engine for Viewers when the
target agent has RunnableByViewer=false. Same EnableRBAC gating as
the middleware so it's a no-op until enforcement is turned on.
Tests:
- 12 unit tests cover RequireRole / RequireOwnershipOrRole, including
the fail-open and fail-closed branches and the lookup-error path.
2026-05-13 13:16:54 +00:00
|
|
|
kb.CreatorID = uid
|
|
|
|
|
}
|
2025-11-14 17:30:17 +00:00
|
|
|
kb.EnsureDefaults()
|
2026-05-29 05:36:06 +00:00
|
|
|
applyTenantDefaultStorageProvider(ctx, kb)
|
2026-07-15 05:26:29 +00:00
|
|
|
if err := s.applyAndValidateStorageBackend(ctx, kb); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
// Fold empty-string vector_store_id into nil so this path and the
|
|
|
|
|
// retrieve-engine factory's pre-condition share a single representation.
|
|
|
|
|
wasEmpty := kb.VectorStoreID != nil && *kb.VectorStoreID == ""
|
|
|
|
|
kb.Normalize()
|
|
|
|
|
if wasEmpty {
|
|
|
|
|
logger.Debugf(ctx,
|
|
|
|
|
"[kb.create] empty vector_store_id normalized to nil for tenant=%d",
|
|
|
|
|
kb.TenantID)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if kb.HasVectorStore() {
|
|
|
|
|
if err := s.validateVectorStoreBinding(ctx, kb.TenantID, *kb.VectorStoreID); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
logger.Infof(ctx, "Creating knowledge base, ID: %s, tenant ID: %d, name: %s", kb.ID, kb.TenantID, kb.Name)
|
|
|
|
|
|
|
|
|
|
if err := s.repo.CreateKnowledgeBase(ctx, kb); err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": kb.ID,
|
|
|
|
|
"tenant_id": kb.TenantID,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, kb.TenantID, kb.ID, types.AuditActionKBCreated,
|
|
|
|
|
"knowledge_base", kb.ID, types.AuditOutcomeSuccess, map[string]any{
|
|
|
|
|
"name": kb.Name, "type": kb.Type,
|
|
|
|
|
})
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Knowledge base created successfully, ID: %s, name: %s", kb.ID, kb.Name)
|
|
|
|
|
return kb, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-15 05:26:29 +00:00
|
|
|
func (s *knowledgeBaseService) applyAndValidateStorageBackend(ctx context.Context, kb *types.KnowledgeBase) error {
|
|
|
|
|
if s.storageResolver == nil || kb == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
tenant, _ := types.TenantInfoFromContext(ctx)
|
|
|
|
|
if tenant == nil {
|
|
|
|
|
return apperrors.NewBadRequestError("workspace context missing")
|
|
|
|
|
}
|
|
|
|
|
id := ""
|
|
|
|
|
if kb.StorageBackendID != nil {
|
|
|
|
|
id = strings.TrimSpace(*kb.StorageBackendID)
|
|
|
|
|
}
|
|
|
|
|
provider := kb.GetStorageProvider()
|
|
|
|
|
// A newly created KB without an explicit instance follows the concrete
|
|
|
|
|
// tenant default. The legacy provider is only a fallback for workspaces
|
|
|
|
|
// that have not been migrated yet.
|
|
|
|
|
if id == "" && tenant.DefaultStorageBackendID != nil && strings.TrimSpace(*tenant.DefaultStorageBackendID) != "" {
|
|
|
|
|
provider = ""
|
|
|
|
|
}
|
|
|
|
|
backend, err := s.storageResolver.ResolveBackend(ctx, tenant, id, provider)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return apperrors.NewBadRequestError("storage backend is unavailable").WithDetails(err.Error())
|
|
|
|
|
}
|
|
|
|
|
if backend == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
kb.StorageBackendID = &backend.ID
|
|
|
|
|
kb.SetStorageProvider(backend.Provider)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-29 05:36:06 +00:00
|
|
|
// applyTenantDefaultStorageProvider fills an empty KB storage provider from the
|
|
|
|
|
// tenant's global default (Settings → Storage engine). Frontend should send the
|
|
|
|
|
// same value; this keeps API clients and legacy UIs consistent.
|
|
|
|
|
func applyTenantDefaultStorageProvider(ctx context.Context, kb *types.KnowledgeBase) {
|
|
|
|
|
if kb == nil || strings.TrimSpace(kb.GetStorageProvider()) != "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
2026-07-15 02:57:32 +00:00
|
|
|
provider := ""
|
2026-05-29 05:36:06 +00:00
|
|
|
if tenant != nil && tenant.StorageEngineConfig != nil {
|
2026-07-15 02:57:32 +00:00
|
|
|
provider = strings.ToLower(strings.TrimSpace(tenant.StorageEngineConfig.DefaultProvider))
|
|
|
|
|
}
|
|
|
|
|
if provider == "" || !storageallowlist.IsAllowed(provider) {
|
|
|
|
|
provider = storageallowlist.FirstAllowed()
|
|
|
|
|
}
|
|
|
|
|
if provider == "" {
|
|
|
|
|
return
|
2026-05-29 05:36:06 +00:00
|
|
|
}
|
|
|
|
|
kb.SetStorageProvider(provider)
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
// validateVectorStoreBinding routes through retriever.VerifyBinding so the
|
|
|
|
|
// ownership + registry sentinel hierarchy stays the single source of truth.
|
|
|
|
|
// The service layer's responsibility is to:
|
|
|
|
|
//
|
|
|
|
|
// 1. fast-reject malformed UUIDs (cheap pre-flight that also avoids a DB
|
|
|
|
|
// round trip for type-confusion inputs like "' OR 1=1 --"),
|
|
|
|
|
// 2. translate retriever sentinels into user-facing AppErrors with
|
|
|
|
|
// generic messages and the typed error codes.
|
|
|
|
|
//
|
|
|
|
|
// UUID parse failures map to the same "vector store not found" message as
|
|
|
|
|
// cross-tenant attempts to avoid an enumeration oracle that distinguishes
|
|
|
|
|
// "malformed input" from "non-existent UUID".
|
|
|
|
|
func (s *knowledgeBaseService) validateVectorStoreBinding(
|
|
|
|
|
ctx context.Context, tenantID uint64, storeID string,
|
|
|
|
|
) error {
|
|
|
|
|
sanitized := secutils.SanitizeForLog(storeID)
|
|
|
|
|
|
|
|
|
|
if _, err := uuid.Parse(storeID); err != nil {
|
|
|
|
|
logger.WarnWithFields(ctx, logger.Fields{
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
"store_id": sanitized,
|
|
|
|
|
"reason": "malformed vector_store_id",
|
|
|
|
|
}, "[kb.create] vector store id is not a valid UUID")
|
|
|
|
|
return apperrors.NewVectorStoreBindingInvalidError("vector store not found")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
switch err := retriever.VerifyBinding(
|
|
|
|
|
ctx, s.retrieveEngine, s.ownership, tenantID, storeID,
|
|
|
|
|
); {
|
|
|
|
|
case err == nil:
|
|
|
|
|
return nil
|
|
|
|
|
case errors.Is(err, retriever.ErrVectorStoreForbidden):
|
|
|
|
|
logger.WarnWithFields(ctx, logger.Fields{
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
"store_id": sanitized,
|
|
|
|
|
"reason": "cross-tenant or unknown store",
|
|
|
|
|
}, "[kb.create] vector store not owned by tenant")
|
|
|
|
|
return apperrors.NewVectorStoreBindingInvalidError("vector store not found")
|
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
|
|
|
case errors.Is(err, retriever.ErrVectorStoreNotFound),
|
|
|
|
|
errors.Is(err, retriever.ErrVectorStoreUnavailable):
|
2026-05-18 01:10:01 +00:00
|
|
|
logger.WarnWithFields(ctx, logger.Fields{
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
"store_id": sanitized,
|
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
|
|
|
"reason": "store recorded in DB but no engine could be resolved",
|
2026-05-18 01:10:01 +00:00
|
|
|
}, "[kb.create] vector store currently unavailable")
|
|
|
|
|
return apperrors.NewVectorStoreUnavailableError(
|
|
|
|
|
"vector store is currently unavailable; check its connection configuration")
|
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
|
|
|
case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
|
|
|
|
|
// The caller went away or ran out of time while the binding was being
|
|
|
|
|
// verified, which can now include rebuilding the store's engine. That
|
|
|
|
|
// is not a server fault, so it must not be logged and answered as one.
|
|
|
|
|
return err
|
2026-05-18 01:10:01 +00:00
|
|
|
default:
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
"store_id": sanitized,
|
|
|
|
|
"reason": "binding verification failed",
|
|
|
|
|
})
|
|
|
|
|
return apperrors.NewInternalServerError("failed to verify vector store binding")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
// GetKnowledgeBaseByID retrieves a knowledge base by its ID
|
|
|
|
|
func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
|
|
|
|
|
if id == "" {
|
|
|
|
|
logger.Error(ctx, "Knowledge base ID is empty")
|
|
|
|
|
return nil, errors.New("knowledge base ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-14 17:30:17 +00:00
|
|
|
kb.EnsureDefaults()
|
2025-08-05 07:08:07 +00:00
|
|
|
return kb, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-30 08:28:01 +00:00
|
|
|
// GetKnowledgeBaseByIDOnly retrieves knowledge base by ID without tenant filter
|
|
|
|
|
// Used for cross-tenant shared KB access where permission is checked elsewhere
|
|
|
|
|
func (s *knowledgeBaseService) GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error) {
|
|
|
|
|
if id == "" {
|
|
|
|
|
logger.Error(ctx, "Knowledge base ID is empty")
|
|
|
|
|
return nil, errors.New("knowledge base ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
kb.EnsureDefaults()
|
|
|
|
|
return kb, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-04 12:12:29 +00:00
|
|
|
// GetKnowledgeBasesByIDsOnly retrieves knowledge bases by IDs without tenant filter (batch).
|
|
|
|
|
func (s *knowledgeBaseService) GetKnowledgeBasesByIDsOnly(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error) {
|
|
|
|
|
if len(ids) == 0 {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
kbs, err := s.repo.GetKnowledgeBaseByIDs(ctx, ids)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
for _, kb := range kbs {
|
|
|
|
|
if kb != nil {
|
|
|
|
|
kb.EnsureDefaults()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return kbs, nil
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
// ListKnowledgeBases returns all knowledge bases for a tenant
|
|
|
|
|
func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
|
2026-02-28 10:11:37 +00:00
|
|
|
tenantID := types.MustTenantIDFromContext(ctx)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
|
|
|
|
if err != nil {
|
2025-11-14 17:30:17 +00:00
|
|
|
for _, kb := range kbs {
|
|
|
|
|
kb.EnsureDefaults()
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-20 17:39:43 +00:00
|
|
|
// Query knowledge count and chunk count for each knowledge base
|
|
|
|
|
for _, kb := range kbs {
|
|
|
|
|
kb.EnsureDefaults()
|
2025-11-23 09:32:50 +00:00
|
|
|
|
2025-11-20 17:39:43 +00:00
|
|
|
// Get knowledge count
|
2025-11-28 08:10:37 +00:00
|
|
|
switch kb.Type {
|
|
|
|
|
case types.KnowledgeBaseTypeDocument:
|
2025-11-20 17:39:43 +00:00
|
|
|
knowledgeCount, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, tenantID, kb.ID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to get knowledge count for knowledge base %s: %v", kb.ID, err)
|
|
|
|
|
} else {
|
|
|
|
|
kb.KnowledgeCount = knowledgeCount
|
|
|
|
|
}
|
2025-11-28 08:10:37 +00:00
|
|
|
case types.KnowledgeBaseTypeFAQ:
|
2025-11-20 17:39:43 +00:00
|
|
|
// Get chunk count
|
|
|
|
|
chunkCount, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, tenantID, kb.ID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to get chunk count for knowledge base %s: %v", kb.ID, err)
|
|
|
|
|
} else {
|
|
|
|
|
kb.ChunkCount = chunkCount
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-23 09:32:50 +00:00
|
|
|
// Check if there is a processing import task
|
|
|
|
|
processingCount, err := s.kgRepo.CountKnowledgeByStatus(
|
|
|
|
|
ctx,
|
|
|
|
|
tenantID,
|
|
|
|
|
kb.ID,
|
|
|
|
|
[]string{"pending", "processing"},
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to check processing status for knowledge base %s: %v", kb.ID, err)
|
|
|
|
|
} else {
|
|
|
|
|
kb.IsProcessing = processingCount > 0
|
|
|
|
|
kb.ProcessingCount = processingCount
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-05-18 03:58:46 +00:00
|
|
|
|
|
|
|
|
// Per-user pin stamping + ordering. The "main" list view is the
|
|
|
|
|
// only path that needs to honour the caller's personal pin set;
|
|
|
|
|
// agent/share/IM callers go through ListKnowledgeBasesByTenantID
|
|
|
|
|
// which also enriches but keys off the user in their own context.
|
|
|
|
|
if userID, ok := types.UserIDFromContext(ctx); ok && userID != "" {
|
|
|
|
|
s.applyUserKBPins(ctx, tenantID, userID, kbs)
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
return kbs, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-04 12:12:29 +00:00
|
|
|
// ListKnowledgeBasesByTenantID returns all knowledge bases for the given tenant (e.g. for shared agent context).
|
|
|
|
|
func (s *knowledgeBaseService) ListKnowledgeBasesByTenantID(ctx context.Context, tenantID uint64) ([]*types.KnowledgeBase, error) {
|
|
|
|
|
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
for _, kb := range kbs {
|
|
|
|
|
kb.EnsureDefaults()
|
|
|
|
|
switch kb.Type {
|
|
|
|
|
case types.KnowledgeBaseTypeDocument:
|
|
|
|
|
if cnt, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
|
|
|
|
|
kb.KnowledgeCount = cnt
|
|
|
|
|
}
|
|
|
|
|
case types.KnowledgeBaseTypeFAQ:
|
|
|
|
|
if cnt, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
|
|
|
|
|
kb.ChunkCount = cnt
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if processingCount, err := s.kgRepo.CountKnowledgeByStatus(ctx, tenantID, kb.ID, []string{"pending", "processing"}); err == nil {
|
|
|
|
|
kb.IsProcessing = processingCount > 0
|
|
|
|
|
kb.ProcessingCount = processingCount
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-05-18 03:58:46 +00:00
|
|
|
|
|
|
|
|
// Stamp pin state from the caller's perspective. The tenantID
|
|
|
|
|
// argument may not match the caller's own tenant (this method is
|
|
|
|
|
// also used to list a shared-agent's source-tenant KBs); we still
|
|
|
|
|
// scope user_kb_pins by `tenantID` since a pin tied to one tenant
|
|
|
|
|
// shouldn't surface when browsing another tenant's KBs.
|
|
|
|
|
if userID, ok := types.UserIDFromContext(ctx); ok && userID != "" {
|
|
|
|
|
s.applyUserKBPins(ctx, tenantID, userID, kbs)
|
|
|
|
|
}
|
2026-02-04 12:12:29 +00:00
|
|
|
return kbs, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FillKnowledgeBaseCounts fills KnowledgeCount, ChunkCount, IsProcessing, ProcessingCount for the given KB using kb.TenantID.
|
|
|
|
|
func (s *knowledgeBaseService) FillKnowledgeBaseCounts(ctx context.Context, kb *types.KnowledgeBase) error {
|
|
|
|
|
if kb == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
tenantID := kb.TenantID
|
|
|
|
|
kb.EnsureDefaults()
|
|
|
|
|
switch kb.Type {
|
|
|
|
|
case types.KnowledgeBaseTypeDocument:
|
|
|
|
|
if cnt, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
|
|
|
|
|
kb.KnowledgeCount = cnt
|
|
|
|
|
}
|
|
|
|
|
case types.KnowledgeBaseTypeFAQ:
|
|
|
|
|
if cnt, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, tenantID, kb.ID); err == nil {
|
|
|
|
|
kb.ChunkCount = cnt
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if processingCount, err := s.kgRepo.CountKnowledgeByStatus(ctx, tenantID, kb.ID, []string{"pending", "processing"}); err == nil {
|
|
|
|
|
kb.IsProcessing = processingCount > 0
|
|
|
|
|
kb.ProcessingCount = processingCount
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
fix(kb): let the update API set vlm_config (#3704)
* fix(kb): let update API set vlm_config
UpdateKnowledgeBaseRequest only carried name/description/config, so the
PUT /knowledge-bases/:id endpoint could never change a knowledge base's
multimodal (VLM) config, even though CreateKnowledgeBase accepts a
top-level vlm_config. Thread an optional vlm_config through the handler
and service so the update path mirrors create (nil = no change).
Fixes #1723
* test(kb): pass the vlm_config argument in tests added on main
* fix(kb): accept only model-managed vlm_config fields on update
The update API copied the request's VLMConfig wholesale, so a caller
could set the legacy ModelName/BaseURL/APIKey/InterfaceType fields and
have the VLM client call BaseURL directly, outside model management and
its SSRF checks. Only Enabled/ModelID/DescriptionLanguage/
CustomInstructions are taken now; legacy fields keep their stored value.
A referenced model must exist and be a VLLM model (400 otherwise), and
disabling clears ModelID, matching the initialization config endpoint.
* fix(kb): validate and gate vlm_config on the update API
- Enforce the 4000-character custom_instructions cap
(types.ValidateKnowledgeBasePromptInstructions), as create and
/initialization/config already do.
- vlm_config is a KB setting: require kbSettingsAccess (owner workspace
or admin share) like /initialization/config, so share editors get 403.
- Stored legacy model_name/base_url keep IsEnabled() true on their own,
so disabling returned 200 but left VLM on, and managed -> disabled fell
back to the old endpoint. Clear them when the request enables a managed
model_id, or disables VLM without echoing back the stored
model_name+base_url (GET-then-PUT keeps legacy on). Request legacy
fields are only compared, never written. Enabling without model_id on a
non-legacy KB is now a 400 instead of a silent no-op.
- Document the vlm_config semantics in the KB API reference.
* fix(kb): keep the legacy VLM endpoint only for pure legacy knowledge bases
CreateKnowledgeBase stores vlm_config as sent, so a managed model_id can
sit next to legacy model_name/base_url; resolveVLM then uses the managed
model. The update's keep-legacy paths (disable echoing the stored legacy
fields, enabled=true without model_id) cleared model_id but kept the
legacy fields, so IsEnabled() stayed true and image calls moved to the
stored base_url.
Those paths now apply only when no model_id is stored. On a mixed config
a disable clears everything, and enabled=true without model_id is a 400,
the same as on any managed knowledge base.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 06:37:23 +00:00
|
|
|
// resolveUpdatedVLMConfig builds the VLM config an update request asks for.
|
|
|
|
|
// Only the model-managed fields are taken from the request: the legacy
|
|
|
|
|
// ModelName/BaseURL/APIKey/InterfaceType fields make the VLM client call
|
|
|
|
|
// BaseURL directly, bypassing model management and its SSRF checks, so they
|
|
|
|
|
// are never written from the request. A referenced model must exist and be a
|
|
|
|
|
// VLM model.
|
|
|
|
|
//
|
|
|
|
|
// Stored legacy fields keep VLMConfig.IsEnabled() true on their own, so they
|
|
|
|
|
// are cleared when the request enables a managed model, or when it disables
|
|
|
|
|
// VLM without echoing back the stored model_name and base_url (the shape a
|
|
|
|
|
// GET-then-PUT round trip sends). Request legacy fields are only compared.
|
|
|
|
|
//
|
|
|
|
|
// Only a pure legacy KB (no stored ModelID) keeps its legacy endpoint on an
|
|
|
|
|
// echo or on enabled=true without a model_id. A config that carries a managed
|
|
|
|
|
// ModelID next to legacy fields (CreateKnowledgeBase stores the request as
|
|
|
|
|
// is) is treated as managed: clearing ModelID while keeping the legacy
|
|
|
|
|
// fields would silently move image calls to the stored BaseURL.
|
|
|
|
|
func (s *knowledgeBaseService) resolveUpdatedVLMConfig(
|
|
|
|
|
ctx context.Context, current, requested types.VLMConfig,
|
|
|
|
|
) (types.VLMConfig, error) {
|
|
|
|
|
next := current
|
|
|
|
|
next.Enabled = requested.Enabled
|
|
|
|
|
next.ModelID = strings.TrimSpace(requested.ModelID)
|
|
|
|
|
next.DescriptionLanguage = strings.TrimSpace(requested.DescriptionLanguage)
|
|
|
|
|
next.CustomInstructions = strings.TrimSpace(requested.CustomInstructions)
|
|
|
|
|
if err := types.ValidateKnowledgeBasePromptInstructions(&types.KnowledgeBase{VLMConfig: next}); err != nil {
|
|
|
|
|
return types.VLMConfig{}, apperrors.NewBadRequestError("vlm_config: " + err.Error())
|
|
|
|
|
}
|
|
|
|
|
pureLegacy := current.ModelID == "" && current.ModelName != "" && current.BaseURL != ""
|
|
|
|
|
if !next.Enabled {
|
|
|
|
|
next.ModelID = ""
|
|
|
|
|
legacyEcho := pureLegacy &&
|
|
|
|
|
requested.ModelName == current.ModelName && requested.BaseURL == current.BaseURL
|
|
|
|
|
if !legacyEcho {
|
|
|
|
|
clearLegacyVLMFields(&next)
|
|
|
|
|
}
|
|
|
|
|
return next, nil
|
|
|
|
|
}
|
|
|
|
|
if next.ModelID == "" {
|
|
|
|
|
if !pureLegacy {
|
|
|
|
|
return types.VLMConfig{}, apperrors.NewBadRequestError(
|
|
|
|
|
"vlm_config.model_id is required when enabled")
|
|
|
|
|
}
|
|
|
|
|
return next, nil
|
|
|
|
|
}
|
|
|
|
|
model, err := s.modelService.GetModelByID(ctx, next.ModelID)
|
|
|
|
|
if errors.Is(err, ErrModelNotFound) {
|
|
|
|
|
return types.VLMConfig{}, apperrors.NewBadRequestError("vlm_config.model_id: model not found")
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return types.VLMConfig{}, fmt.Errorf("get vlm model %s: %w", next.ModelID, err)
|
|
|
|
|
}
|
|
|
|
|
if model.Type != types.ModelTypeVLLM {
|
|
|
|
|
return types.VLMConfig{}, apperrors.NewBadRequestError(
|
|
|
|
|
fmt.Sprintf("vlm_config.model_id: model type is %s, want %s", model.Type, types.ModelTypeVLLM))
|
|
|
|
|
}
|
|
|
|
|
clearLegacyVLMFields(&next)
|
|
|
|
|
return next, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// clearLegacyVLMFields drops the pre-model-management inline VLM endpoint.
|
|
|
|
|
func clearLegacyVLMFields(cfg *types.VLMConfig) {
|
|
|
|
|
cfg.ModelName = ""
|
|
|
|
|
cfg.BaseURL = ""
|
|
|
|
|
cfg.APIKey = ""
|
|
|
|
|
cfg.InterfaceType = ""
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 01:10:01 +00:00
|
|
|
// UpdateKnowledgeBase updates a knowledge base's mutable properties.
|
|
|
|
|
//
|
|
|
|
|
// IMPORTANT — vector_store_id immutability contract:
|
|
|
|
|
// The vector_store_id binding is deliberately not accepted by this method.
|
|
|
|
|
// Two layers enforce immutability:
|
|
|
|
|
//
|
|
|
|
|
// 1. ORM layer: the GORM tag `<-:create` on KnowledgeBase.VectorStoreID
|
|
|
|
|
// makes every UPDATE path (Save / Updates / Select-Updates) a no-op for
|
|
|
|
|
// that column. Verified by repository/knowledgebase_sqlite_test.go.
|
|
|
|
|
// 2. Service layer: this method intentionally omits VectorStoreID from its
|
|
|
|
|
// parameter list, and the matching handler DTO UpdateKnowledgeBaseRequest
|
|
|
|
|
// omits the field as well. A reflection-based regression test
|
|
|
|
|
// (handler/knowledgebase_request_test.go) fails if either DTO field
|
|
|
|
|
// is added back, alerting future maintainers.
|
|
|
|
|
//
|
|
|
|
|
// Any future cross-store rebind workflow must use raw SQL through a
|
|
|
|
|
// dedicated repository method — the only sanctioned write path post-creation.
|
2025-08-05 07:08:07 +00:00
|
|
|
func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
|
|
|
|
id string,
|
|
|
|
|
name string,
|
|
|
|
|
description string,
|
|
|
|
|
config *types.KnowledgeBaseConfig,
|
fix(kb): let the update API set vlm_config (#3704)
* fix(kb): let update API set vlm_config
UpdateKnowledgeBaseRequest only carried name/description/config, so the
PUT /knowledge-bases/:id endpoint could never change a knowledge base's
multimodal (VLM) config, even though CreateKnowledgeBase accepts a
top-level vlm_config. Thread an optional vlm_config through the handler
and service so the update path mirrors create (nil = no change).
Fixes #1723
* test(kb): pass the vlm_config argument in tests added on main
* fix(kb): accept only model-managed vlm_config fields on update
The update API copied the request's VLMConfig wholesale, so a caller
could set the legacy ModelName/BaseURL/APIKey/InterfaceType fields and
have the VLM client call BaseURL directly, outside model management and
its SSRF checks. Only Enabled/ModelID/DescriptionLanguage/
CustomInstructions are taken now; legacy fields keep their stored value.
A referenced model must exist and be a VLLM model (400 otherwise), and
disabling clears ModelID, matching the initialization config endpoint.
* fix(kb): validate and gate vlm_config on the update API
- Enforce the 4000-character custom_instructions cap
(types.ValidateKnowledgeBasePromptInstructions), as create and
/initialization/config already do.
- vlm_config is a KB setting: require kbSettingsAccess (owner workspace
or admin share) like /initialization/config, so share editors get 403.
- Stored legacy model_name/base_url keep IsEnabled() true on their own,
so disabling returned 200 but left VLM on, and managed -> disabled fell
back to the old endpoint. Clear them when the request enables a managed
model_id, or disables VLM without echoing back the stored
model_name+base_url (GET-then-PUT keeps legacy on). Request legacy
fields are only compared, never written. Enabling without model_id on a
non-legacy KB is now a 400 instead of a silent no-op.
- Document the vlm_config semantics in the KB API reference.
* fix(kb): keep the legacy VLM endpoint only for pure legacy knowledge bases
CreateKnowledgeBase stores vlm_config as sent, so a managed model_id can
sit next to legacy model_name/base_url; resolveVLM then uses the managed
model. The update's keep-legacy paths (disable echoing the stored legacy
fields, enabled=true without model_id) cleared model_id but kept the
legacy fields, so IsEnabled() stayed true and image calls moved to the
stored base_url.
Those paths now apply only when no model_id is stored. On a mixed config
a disable clears everything, and enabled=true without model_id is a 400,
the same as on any managed knowledge base.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 06:37:23 +00:00
|
|
|
vlmConfig *types.VLMConfig,
|
2025-08-05 07:08:07 +00:00
|
|
|
) (*types.KnowledgeBase, error) {
|
|
|
|
|
if id == "" {
|
|
|
|
|
logger.Error(ctx, "Knowledge base ID is empty")
|
|
|
|
|
return nil, errors.New("knowledge base ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Updating knowledge base, ID: %s, name: %s", id, name)
|
|
|
|
|
|
|
|
|
|
// Get existing knowledge base
|
|
|
|
|
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 11:15:27 +00:00
|
|
|
changedFields := make([]string, 0, 3)
|
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
|
|
|
profileWasEnabled := kb.ProfileConfig.IsEnabled()
|
2026-07-22 11:15:27 +00:00
|
|
|
if kb.Name != name {
|
|
|
|
|
changedFields = append(changedFields, "name")
|
|
|
|
|
}
|
|
|
|
|
if kb.Description != description {
|
|
|
|
|
changedFields = append(changedFields, "description")
|
|
|
|
|
}
|
|
|
|
|
if config != nil {
|
|
|
|
|
changedFields = append(changedFields, "config")
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
// Update the knowledge base properties
|
|
|
|
|
kb.Name = name
|
|
|
|
|
kb.Description = description
|
2026-03-12 06:47:56 +00:00
|
|
|
if config != nil {
|
|
|
|
|
kb.ChunkingConfig = config.ChunkingConfig
|
feat(gallery): add an image gallery tab with schema-driven filters (#3694)
* feat(image): observe image attributes and let the policy decide OCR
Describe each image with the VLM as before, but ask it to also observe two
attributes about the image in the same round — how much body text it carries
(contain.text) and whether it presents data visually (contain.data_visual) —
then let a small pure function decide whether that image is worth a second,
separate OCR round.
Per-class OCR was the first shape of this idea; a class (chart / photo / logo)
is only an indirect proxy for 'is there text worth reading here', and the class
table has to grow whenever a new kind of image shows up. The decision actually
needs the observed attributes, so it reads them directly, and the attribute set
is a backend registry row rather than a new class.
The observation and the caption share one VLM call; OCR stays a separate call
(prompt isolation, see #3291). An attribute the model does not answer for is
left absent rather than filled with a conservative default, so the trace never
claims an observation that did not happen, and an incomplete observation falls
back to the on_unobserved policy (OCR still runs). The registry also carries the
panel's display text, so a new attribute needs no frontend change.
Off by default: image_attrs_enabled=false keeps today's behaviour (one caption
and one OCR per image). KB config: image_processing_config.image_attrs_enabled /
image_actions; per-upload override via process_config. Registry:
GET /api/v1/image-attrs/schema.
* feat(gallery): add image gallery tab with schema-driven filters
Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that
browses every image asset in a KB.
Backend:
- GET /api/v1/knowledge-bases/:id/images lists image assets projected
from chunks.image_info, with keyword (caption/OCR), multi-value
attribute (attr_<name>=<value>), is_enabled and sort filters applied
in memory, plus pagination.
- Resolves the source knowledge item title (SourceName) via a batched
GetKnowledgeBatch so the viewer can show a human-readable source.
Frontend:
- ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter
panel (from GET /image-attrs/schema) + single-image viewer with
prev/next, attributes/caption/OCR/source.
- Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales.
* feat(gallery): drive filters/search/sort from a configurable attribute contract
The gallery UI is no longer hardcoded: it renders from a self-describing
contract served by GET /knowledge-bases/:id/gallery-config (live attribute
sources, every attribute's definition with usage flags merged across the
config tiers, and the caller's search activation state).
- Attribute sources form an open registry (types.RegisterGalleryAttrSource);
a builtin source models caption/ocr_text/timestamps/enabled so the gallery
has zero special cases.
- Usage resolution: user > KB > system > source, field by field; the system
tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB
tier slot is wired in the engine but not stored yet.
- Search activation is the user's own record: mode (all|custom) plus
per-field on/off in users.preferences.gallery; source declarations never
set defaults (unrecorded = off in custom mode).
- image_info is read through a gallery-local struct, removing the compile
dependency on the attribute-pipeline types; the gallery builds and runs
with or without that feature deployed.
- ListImages validates search_in / sort_by / attr_filters against the
contract; ineligible fields are dropped, not served.
* fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>)
plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file
path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing
components/css/wiki-graph-drawer.less — overwrite each other during the
build and the second one crashes with "reading 'scoped'". Adding the
gallery changed the module order enough to make the collision hit every
time. Inlining the same stylesheet keeps the emitted CSS identical and
removes the shared descriptor key.
* feat(gallery): render attributes from short labels with descriptions in tooltips
A source could only say one thing about a value, so the filter panel had to put
a full sentence inside a checkbox. Attributes and their values now carry two
pieces of text: a short label for the space-constrained controls (checkbox,
search field, sort option) and a description for wherever there is room
(tooltip, detail panel).
The contract's value list becomes an array of {value, label, description}, and
the display helpers resolve each field separately: the gallery stamps the short
name on a control and moves the sentence into a tooltip. Translation overlays
are looked up per field, so a source that ships no gallery-specific text still
picks up the attribute pipeline's own wording.
* fix(gallery): let locale text win over the contract's wording
The filter panel read the backend's own label before asking the locale,
so a translated value never got a chance: the contract ships its own
default-language wording, and it shadowed the overlay for every locale.
Built keys were also off by a segment — imageAttr.<name> has to be
imageAttr.<name>.label, and the gallery's own keys live under
knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system
attributes fell through to English on a Chinese UI.
* feat(gallery): top bar layout, pinned panels and per-value verdicts
The toolbar moves onto its own row above the grid, so the controls no
longer eat into the space the images are there for: search box, the two
scope switches, sort field and direction, and the result count all sit in
one flex row. The settings behind them are no longer inline either — each
opens as a popover under its control and can be pinned to a right-hand
rail, where the two panels take turns as tabs instead of both claiming
width at once.
Filtering gains a third state per attribute value. Where a value could
only be picked or not picked, it can now be "off" (hide those images),
"on" (show them whatever else says) or neutral (leave them alone), which
is what lets one attribute's rules talk about an image another attribute
tried to hide without the pair of them cancelling each other out: a
forced display outranks a forced hide, and anything no rule speaks about
stays visible.
The switch that used to only exist inside the panel now has a toolbar
home as well. "筛选:全显示" genuinely drops the attribute constraint
instead of imposing it against a panel the user cannot see.
Filtering used to empty the list the moment it was switched on. Any
image whose attribute was never observed — every image ingested before
the attribute pipeline existed — read as a mismatch for every filter,
which is not narrowing a list but losing it. Absence now stays silence:
an attribute no image carries places no constraint on it, until the
pipeline catches up and fills the value in.
Co-authored-by: WorkBuddy
* feat(gallery): expose the image attribute pipeline as a gallery source
The gallery's contract resolved to a single source, so the filter panel
could only offer "Enabled" while the attributes the observe-and-describe
pipeline fills in — contain.text, contain.data_visual — never reached the
UI. The registry is a gallery attribute source like any other: every
attribute it declares is offered to the gallery, filterable by default,
with the config tiers able to override the usage flags at runtime.
The registration lives in the attribute pipeline's own commit; this branch
carried an earlier, squapshot of that work which predated the split of an
attribute value into a short label and a description, so the registry's
value shape and this file have been brought in line with it. Both PRs now
hold byte-identical copies of the source hook, which is what lets either
one land first and the other merge cleanly afterwards.
Co-authored-by: WorkBuddy
* fix(gallery): viewer race, pin icon, panel anchoring and scope wording
Opening the viewer rendered the img element with the previous or empty
source while the proxy fetch was still producing a blob, and the error
that empty source fired locked the viewer in its failure state even
after the real image arrived. The resolved source now lands before the
flag is consulted, and a token keeps a slow fetch of one image from
overwriting a faster one that navigated past it.
The pin button drew nothing: TDesign has no "pushpin" glyph, so the
button rendered as an empty shell. It now uses pin / pin-filled, keeps
its place beside the tab bar, and a pinned rail assigns its columns
explicitly — the panel precedes the main section in the DOM, so leaving
the grid to source order handed the wide column to the panel and
squeezed the images into the rail.
The floating panel no longer appears at a hardcoded offset: it anchors
just below the arrow that summoned it, the arrow flips up while its
panel is out, a second press retracts, and any click elsewhere in the
toolbar closes it. When a rail is pinned the arrows turn to the
requested tab instead of spawning a second surface.
The scope words (全部 / 全显示 / 自定义) become plain status text rather
than a second dropdown — they name the current mode, and only the arrow
beside them opens the panel that changes it.
Co-authored-by: WorkBuddy
* fix(web): align the OCR-on-unobserved switch with the other setting rows
The switch sat bare inside its setting-row while every other switch on
the page is wrapped in setting-control, which is what reserves the right
column and centers the control vertically. With the row laid out from
the top, the bare switch hugged the row's upper edge and crowded the
description text — visibly out of place next to its neighbors. Wrapping
it in setting-control gives it the same right-aligned, centered slot as
the rest.
Co-authored-by: WorkBuddy
* fix(web): move the OCR-on-unobserved row out of the vertical schema row
The row lived inside setting-row-vertical, whose descendant rule stretches
every setting-info and setting-control beneath it to 100% width. Two
full-width flex children side by side cannot fit, so the control overflowed
the container and the switch landed past the right edge — visibly further
out than the switch on the row above. The row and its note now sit beside
the vertical block instead of inside it, under their own condition, so the
switch shares the ordinary row layout and its right edge lines up with the
"image attribute observation" switch above.
Co-authored-by: WorkBuddy
* fix(gallery): applying a verdict now activates the filter scope
Setting an off/on verdict while the panel's master switch was off
silently ignored it: buildParams only attaches attr_rules in custom
scope, and setVerdict never flipped the scope. A verdict the user just
expressed now switches the scope to custom; clearing the last meaningful
verdict returns to all, since custom with no rules constrains nothing.
* fix(gallery): search checkboxes stay visible and idle panels read as dimmed
The search panel hid its field checkboxes while the master switch was
on, so the only way to reach them was to flip the switch first. They now
sit next to the switch like the filter panel's verdicts do: dimmed in
all-field mode (where they carry no weight) yet clickable, and touching
one drops the mode to custom. The filter panel's verdict rows dim the
same way while the filter switch is off.
* fix(gallery): bulk verdict row, neutral default mark, panel polish
The clear-filters button never matched what the panel is for, so it is
now a bulk verdict row: one set of -/off/on buttons that applies the
chosen position to every value of every value-typed attribute, with the
default mark turned into a language-neutral dash. The panel head drops
its second divider (the tab bar already draws one) and the tabs follow
the toolbar's order: search left, filter right.
* fix(gallery): drop the all-fields caption and center the order arrow
The caption above the search checkboxes showed and hid with the master
switch, shoving the checkboxes down on every flip; it said nothing the
dimmed state doesn't, so it is gone. The order button's arrow is an
inline svg, which sits on the text baseline and reads as riding high;
it now centers against the label.
* fix(gallery): center the order arrow for real
vertical-align never applied: the icon is a flex item inside the
button's inline-flex text wrapper, and the wrapper's default stretch
pins the explicitly-sized 16px icon to the top of the 22px line box.
align-items: center on the wrapper is what actually centers it.
* fix(gallery): shorten panel tab labels in en and ru
The two-word labels overflowed the 300px panel and forced the tab bar
into scroll arrows; single-word labels fit in every locale that was
affected.
* docs: drop the image pipeline rewrite from this branch
The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation
work (#3635), which this branch carries as a prerequisite and which already
documents the caption_ocr / observation_driven split. Keeping a competing
rewrite of the same paragraph on the gallery branch makes it collide with
upstream, which extended that paragraph with the custom_instructions and inline
HTML table notes. Restoring the shared wording keeps the gallery branch free of
this file so upstream's edits merge cleanly.
* style: gofmt the gallery attribute types
Struct field tags in the resolved gallery config were one column narrow, so
gofmt rebroke the alignment block. Whitespace only.
* style(gallery): use design tokens in the gallery styles
The style guard ratchet fails on any new violation. ImageGallery.vue shipped
with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a
0.15s transition; all of them now read the --app-* / --td-* tokens, which is
what the guard asks for and what dark mode depends on.
* lint(gallery): fix the golangci-lint findings in the gallery code
lll: the three over-long swagger @Param lines and one registry row were
shortened. ineffassign: ctx was assigned before the access check and then
reassigned, so the first value was dead; it is now declared once, after the
check. errcheck: the three unchecked c.Error calls in ListImages. revive: the
AttrSpec / AttrValue doc comment block was attached to the wrong type and split
into one block each. staticcheck S1016: the gallery registration converts the
registry value instead of restating its fields.
* lint(gallery): wrap the image query select and check the last c.Error
* style: reformat the wrapped image select in chunk.go
* fix(gallery): address review findings on ordering, KB switch and blob lifetime
- sortImageAssets: swap operands for desc instead of negating, keeping a
strict weak ordering so ties page stably
- ImageGallery: reload on knowledgeBaseId change, drop stale list
responses, fetch thumbnails in parallel with one cached blob per URL,
revoke blobs on unmount, default sort to builtin:created_at
- KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to
documents again
- handler: move ListImages godoc out of ListKnowledgeFolders' block and
document attr_filters / attr_rules
- DecideOCR: a payload with no OCR conditions uses the built-in policy
instead of silently skipping OCR
* docs(parsing): describe the caption_ocr and observation_driven image pipelines
Carried over from #3635, which this PR supersedes.
* fix(gallery): load local:// and other storage handles through the KB file proxy
The gallery's own scheme check only caught resource://, provider:// and
storage://, so local:// (the default storage), minio://, cos:// and s3://
images went straight into <img src> and never rendered. Resolve through
isProviderFileURL, the scheme list chat and wiki already use, and lock the
routing with a test.
* fix(kb-editor): keep API-customised OCR conditions on save and upload
The KB editor always wrote the registry default into image_actions.ocr.on,
so any unrelated edit replaced a knowledge base's custom OCR conditions
with the default table; the upload dialog did the same for the per-document
override. Keep a stored custom list and fall back to the registry default
only when there is none, and show the conditions actually in effect instead
of the default table in both panels.
* perf(gallery): de-duplicate, filter, sort and page images in SQL
Every gallery request used to read every image-bearing chunk of the KB,
OCR text included, decode it in Go and page in memory. A single query now
expands the image_info arrays, keeps one row per image URL, applies the
keyword / attribute / verdict / enabled filters and the sort, and returns
only the page with the filtered total.
The expansion carries narrow scalars only; filters and JSON sort keys are
evaluated on the winning entry of each image, and the page's JSON is read
back for its rows alone. Postgres runs the query with JIT off, since the
fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices
it ~100x high and compilation dominates.
On 20k images with 2 KB of OCR text each (40k chunks), a page drops from
~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search
over OCR text stays a full scan (~400-600 ms) until the text is indexed.
The filter semantics are pinned against both databases.
* perf(gallery): serve the gallery from a trigger-maintained chunk_images table
Reading images out of chunks.image_info meant parsing every image chunk of
the knowledge base on each request, so a page still cost time in
proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps
one row per image_info entry with caption, OCR text and attributes as
columns; triggers on chunks keep it in step with every write path, and the
migration backfills existing chunks.
Copies of one image stay separate rows and the query lists the copy on the
most recently updated chunk through an indexed anti-join, so writes decide
nothing and concurrent writers need no locking. On postgres, caption and
OCR text get pg_trgm indexes when the extension is available.
On 20k images with 2 KB of OCR text each (40k chunks):
postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms
sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms
down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead
of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram
indexes; status and enable-flag updates patch rows in place.
---------
Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
|
|
|
// Replaced only when the request carried one, so a caller that does not
|
|
|
|
|
// know about the image settings cannot wipe them.
|
|
|
|
|
if config.ImageProcessingConfig != nil {
|
|
|
|
|
kb.ImageProcessingConfig = *config.ImageProcessingConfig
|
|
|
|
|
}
|
2026-03-12 06:47:56 +00:00
|
|
|
if config.FAQConfig != nil {
|
|
|
|
|
kb.FAQConfig = config.FAQConfig
|
|
|
|
|
}
|
2026-04-07 07:19:53 +00:00
|
|
|
if config.WikiConfig != nil {
|
|
|
|
|
kb.WikiConfig = config.WikiConfig
|
|
|
|
|
}
|
2026-08-05 13:56:58 +00:00
|
|
|
if config.AutoTagConfig != nil {
|
|
|
|
|
config.AutoTagConfig.Normalize()
|
|
|
|
|
kb.AutoTagConfig = config.AutoTagConfig
|
|
|
|
|
}
|
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
|
|
|
if config.ProfileConfig != nil {
|
|
|
|
|
profileWasEnabled = kb.ProfileConfig.IsEnabled()
|
|
|
|
|
kb.ProfileConfig = config.ProfileConfig
|
|
|
|
|
}
|
2026-04-22 12:25:08 +00:00
|
|
|
// Update indexing strategy — syncs to ExtractConfig for backward compat
|
2026-04-20 11:16:46 +00:00
|
|
|
if config.IndexingStrategy != nil {
|
|
|
|
|
if !config.IndexingStrategy.HasAnyIndexing() {
|
|
|
|
|
return nil, errors.New("at least one indexing strategy must be enabled")
|
|
|
|
|
}
|
|
|
|
|
kb.IndexingStrategy = *config.IndexingStrategy
|
2026-04-22 12:25:08 +00:00
|
|
|
// Ensure WikiConfig exists when wiki indexing is enabled so that
|
|
|
|
|
// wiki-specific tunables (synthesis model, granularity, …) have a home.
|
|
|
|
|
if kb.WikiConfig == nil && config.IndexingStrategy.WikiEnabled {
|
|
|
|
|
kb.WikiConfig = &types.WikiConfig{}
|
2026-04-20 11:16:46 +00:00
|
|
|
}
|
|
|
|
|
// Sync GraphEnabled → ExtractConfig
|
|
|
|
|
if kb.ExtractConfig != nil {
|
|
|
|
|
kb.ExtractConfig.Enabled = config.IndexingStrategy.GraphEnabled
|
|
|
|
|
} else if config.IndexingStrategy.GraphEnabled {
|
|
|
|
|
kb.ExtractConfig = &types.ExtractConfig{Enabled: true}
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-11-14 17:30:17 +00:00
|
|
|
}
|
fix(kb): let the update API set vlm_config (#3704)
* fix(kb): let update API set vlm_config
UpdateKnowledgeBaseRequest only carried name/description/config, so the
PUT /knowledge-bases/:id endpoint could never change a knowledge base's
multimodal (VLM) config, even though CreateKnowledgeBase accepts a
top-level vlm_config. Thread an optional vlm_config through the handler
and service so the update path mirrors create (nil = no change).
Fixes #1723
* test(kb): pass the vlm_config argument in tests added on main
* fix(kb): accept only model-managed vlm_config fields on update
The update API copied the request's VLMConfig wholesale, so a caller
could set the legacy ModelName/BaseURL/APIKey/InterfaceType fields and
have the VLM client call BaseURL directly, outside model management and
its SSRF checks. Only Enabled/ModelID/DescriptionLanguage/
CustomInstructions are taken now; legacy fields keep their stored value.
A referenced model must exist and be a VLLM model (400 otherwise), and
disabling clears ModelID, matching the initialization config endpoint.
* fix(kb): validate and gate vlm_config on the update API
- Enforce the 4000-character custom_instructions cap
(types.ValidateKnowledgeBasePromptInstructions), as create and
/initialization/config already do.
- vlm_config is a KB setting: require kbSettingsAccess (owner workspace
or admin share) like /initialization/config, so share editors get 403.
- Stored legacy model_name/base_url keep IsEnabled() true on their own,
so disabling returned 200 but left VLM on, and managed -> disabled fell
back to the old endpoint. Clear them when the request enables a managed
model_id, or disables VLM without echoing back the stored
model_name+base_url (GET-then-PUT keeps legacy on). Request legacy
fields are only compared, never written. Enabling without model_id on a
non-legacy KB is now a 400 instead of a silent no-op.
- Document the vlm_config semantics in the KB API reference.
* fix(kb): keep the legacy VLM endpoint only for pure legacy knowledge bases
CreateKnowledgeBase stores vlm_config as sent, so a managed model_id can
sit next to legacy model_name/base_url; resolveVLM then uses the managed
model. The update's keep-legacy paths (disable echoing the stored legacy
fields, enabled=true without model_id) cleared model_id but kept the
legacy fields, so IsEnabled() stayed true and image calls moved to the
stored base_url.
Those paths now apply only when no model_id is stored. On a mixed config
a disable clears everything, and enabled=true without model_id is a 400,
the same as on any managed knowledge base.
---------
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 06:37:23 +00:00
|
|
|
// Apply multimodal (vision) config only when the caller provided it,
|
|
|
|
|
// mirroring the nil-means-no-change semantics used above.
|
|
|
|
|
if vlmConfig != nil {
|
|
|
|
|
next, err := s.resolveUpdatedVLMConfig(ctx, kb.VLMConfig, *vlmConfig)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
if kb.VLMConfig != next {
|
|
|
|
|
changedFields = append(changedFields, "vlm_config")
|
|
|
|
|
}
|
|
|
|
|
kb.VLMConfig = next
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
kb.UpdatedAt = time.Now()
|
2025-11-14 17:30:17 +00:00
|
|
|
kb.EnsureDefaults()
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
logger.Info(ctx, "Saving knowledge base update")
|
|
|
|
|
if err := s.repo.UpdateKnowledgeBase(ctx, kb); err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, kb.TenantID, kb.ID, types.AuditActionKBUpdated,
|
|
|
|
|
"knowledge_base", kb.ID, types.AuditOutcomeSuccess, map[string]any{
|
|
|
|
|
"name": kb.Name, "changed_fields": changedFields,
|
|
|
|
|
})
|
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
|
|
|
// Turning automatic description generation on should produce a
|
|
|
|
|
// description now, not after the next upload.
|
|
|
|
|
if !profileWasEnabled && kb.ProfileConfig.IsEnabled() {
|
|
|
|
|
_ = requestKnowledgeBaseProfileRefresh(ctx, s.asynqClient, kb, false)
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Knowledge base updated successfully, ID: %s, name: %s", kb.ID, kb.Name)
|
|
|
|
|
return kb, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 03:58:46 +00:00
|
|
|
// TogglePinKnowledgeBase toggles whether the calling user has pinned
|
|
|
|
|
// this knowledge base. Pin state is per-(user, kb) as of migration
|
|
|
|
|
// 000050; previously this method flipped a tenant-wide column on the
|
|
|
|
|
// KB row which broke down under RBAC (only Admin/creator could pin,
|
|
|
|
|
// and the pin reordered the list for everyone in the tenant). The
|
|
|
|
|
// public signature is unchanged so the HTTP handler / CLI / SDK don't
|
|
|
|
|
// move.
|
|
|
|
|
//
|
|
|
|
|
// The KB still has to belong to the caller's tenant — the route is
|
|
|
|
|
// already gated behind KBAccessRead, but we re-check via
|
|
|
|
|
// GetKnowledgeBaseByIDAndTenant so a stale param survives a tenant
|
|
|
|
|
// switch cleanly.
|
|
|
|
|
func (s *knowledgeBaseService) TogglePinKnowledgeBase(
|
|
|
|
|
ctx context.Context, id string,
|
|
|
|
|
) (*types.KnowledgeBase, error) {
|
2026-03-05 04:02:22 +00:00
|
|
|
if id == "" {
|
|
|
|
|
return nil, errors.New("knowledge base ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
tenantID := types.MustTenantIDFromContext(ctx)
|
2026-05-18 03:58:46 +00:00
|
|
|
userID, ok := types.UserIDFromContext(ctx)
|
|
|
|
|
if !ok || userID == "" {
|
|
|
|
|
// API-key callers without a user identity can't have a personal
|
|
|
|
|
// pin set. We surface this rather than silently flipping a
|
|
|
|
|
// shared-tenant flag like the old behaviour.
|
|
|
|
|
return nil, errors.New("pin requires an authenticated user")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Look the KB up without a tenant filter: the route's KBAccessRead
|
|
|
|
|
// guard already validated that this caller can see this KB (own,
|
|
|
|
|
// org-shared, or agent-shared). Filtering by the caller's tenant
|
|
|
|
|
// here would 404 every legitimate pin against a shared KB whose
|
|
|
|
|
// owning tenant differs from the caller's active tenant.
|
|
|
|
|
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
2026-03-05 04:02:22 +00:00
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
2026-05-18 03:58:46 +00:00
|
|
|
"tenant_id": tenantID,
|
2026-03-05 04:02:22 +00:00
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-05-18 03:58:46 +00:00
|
|
|
|
|
|
|
|
// Read current pin state to decide direction. ListUserKBPinIDs is
|
|
|
|
|
// already optimised for the "many KBs at once" path; for a single-id
|
|
|
|
|
// check the round-trip is acceptable and avoids leaking a second
|
|
|
|
|
// repository method just for this.
|
|
|
|
|
pins, err := s.repo.ListUserKBPinIDs(ctx, tenantID, userID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
"user_id": userID,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
_, currentlyPinned := pins[id]
|
|
|
|
|
|
|
|
|
|
pinnedAt, err := s.repo.SetUserKBPin(ctx, tenantID, userID, id, !currentlyPinned)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
"tenant_id": tenantID,
|
|
|
|
|
"user_id": userID,
|
|
|
|
|
"target_pinned": !currentlyPinned,
|
|
|
|
|
})
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
kb.EnsureDefaults()
|
|
|
|
|
kb.IsPinned = !currentlyPinned
|
|
|
|
|
kb.PinnedAt = pinnedAt
|
|
|
|
|
logger.Infof(ctx, "Knowledge base pin toggled, ID: %s, user: %s, is_pinned: %v",
|
|
|
|
|
id, userID, kb.IsPinned)
|
2026-03-05 04:02:22 +00:00
|
|
|
return kb, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 03:58:46 +00:00
|
|
|
// applyUserKBPins stamps IsPinned / PinnedAt onto each KB in the slice
|
|
|
|
|
// from the caller's perspective and sorts the slice so pinned rows
|
|
|
|
|
// float to the top (newest pin first, ties broken by created_at desc).
|
|
|
|
|
// Safe to call with an empty userID (no-op stamp; default sort by
|
|
|
|
|
// created_at preserved).
|
|
|
|
|
func (s *knowledgeBaseService) applyUserKBPins(
|
|
|
|
|
ctx context.Context, tenantID uint64, userID string, kbs []*types.KnowledgeBase,
|
|
|
|
|
) {
|
|
|
|
|
if len(kbs) == 0 || userID == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
pins, err := s.repo.ListUserKBPinIDs(ctx, tenantID, userID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
// Pin enrichment is best-effort: a transient DB blip here
|
|
|
|
|
// should not break listing KBs. Log and bail without altering
|
|
|
|
|
// the slice — caller still gets a valid list, just unsorted by
|
|
|
|
|
// pin.
|
|
|
|
|
logger.Warnf(ctx, "applyUserKBPins: failed to load pins for tenant=%d user=%s: %v",
|
|
|
|
|
tenantID, userID, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if len(pins) == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
for _, kb := range kbs {
|
|
|
|
|
if ts, ok := pins[kb.ID]; ok {
|
|
|
|
|
kb.IsPinned = true
|
|
|
|
|
t := ts
|
|
|
|
|
kb.PinnedAt = &t
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
sort.SliceStable(kbs, func(i, j int) bool {
|
|
|
|
|
a, b := kbs[i], kbs[j]
|
|
|
|
|
if a.IsPinned != b.IsPinned {
|
|
|
|
|
return a.IsPinned
|
|
|
|
|
}
|
|
|
|
|
if a.IsPinned && b.IsPinned {
|
|
|
|
|
at, bt := a.PinnedAt, b.PinnedAt
|
|
|
|
|
if at != nil && bt != nil && !at.Equal(*bt) {
|
|
|
|
|
return at.After(*bt)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return a.CreatedAt.After(b.CreatedAt)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
// DeleteKnowledgeBase deletes a knowledge base by its ID
|
2025-12-25 11:33:58 +00:00
|
|
|
// This method marks the knowledge base as deleted and enqueues an async task
|
|
|
|
|
// to handle the heavy cleanup operations (embeddings, chunks, files, graph data)
|
2025-08-05 07:08:07 +00:00
|
|
|
func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id string) error {
|
|
|
|
|
if id == "" {
|
|
|
|
|
logger.Error(ctx, "Knowledge base ID is empty")
|
|
|
|
|
return errors.New("knowledge base ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Deleting knowledge base, ID: %s", id)
|
|
|
|
|
|
2025-11-23 09:27:30 +00:00
|
|
|
// Get tenant ID from context
|
2026-02-28 10:11:37 +00:00
|
|
|
tenantID := types.MustTenantIDFromContext(ctx)
|
|
|
|
|
tenantInfo, _ := types.TenantInfoFromContext(ctx)
|
2025-11-23 09:27:30 +00:00
|
|
|
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
// Load the KB before soft-delete so we can snapshot its VectorStoreID
|
|
|
|
|
// into the async cleanup payload. GORM's soft-delete filter hides the
|
|
|
|
|
// row from subsequent reads, so this read must happen first.
|
|
|
|
|
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
})
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
var vectorStoreIDSnapshot *string
|
|
|
|
|
if kb != nil {
|
|
|
|
|
vectorStoreIDSnapshot = kb.VectorStoreID
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-25 11:33:58 +00:00
|
|
|
// Step 1: Delete the knowledge base record first (mark as deleted)
|
|
|
|
|
logger.Infof(ctx, "Deleting knowledge base from database")
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
err = s.repo.DeleteKnowledgeBase(ctx, id)
|
2025-11-23 09:27:30 +00:00
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
})
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-07-22 11:15:27 +00:00
|
|
|
deletedName := ""
|
|
|
|
|
if kb != nil {
|
|
|
|
|
deletedName = kb.Name
|
|
|
|
|
}
|
|
|
|
|
recordKBActivity(ctx, s.audit, tenantID, id, types.AuditActionKBDeleted,
|
|
|
|
|
"knowledge_base", id, types.AuditOutcomeSuccess, map[string]any{"name": deletedName})
|
2025-12-25 11:33:58 +00:00
|
|
|
|
2026-07-22 20:51:40 +00:00
|
|
|
// Stop both ephemeral queue work and durable wiki operations that target
|
|
|
|
|
// the now-deleted KB. ProcessKBDelete repeats this with document IDs and
|
|
|
|
|
// performs one final scrub after heavy cleanup to close enqueue races.
|
2026-07-23 04:19:21 +00:00
|
|
|
//
|
|
|
|
|
// Run detached with a bounded timeout so a disconnecting API client cannot
|
|
|
|
|
// truncate this best-effort scrub mid-scan, matching ProcessKBDelete's
|
|
|
|
|
// cleanup semantics. The KB row is already soft-deleted, so the async
|
|
|
|
|
// delete task remains the durable backstop even if this pass is cut short.
|
|
|
|
|
kbCleanupCtx, cancelKBCleanup := context.WithTimeout(
|
|
|
|
|
context.WithoutCancel(ctx), kbTaskCleanupTimeout,
|
|
|
|
|
)
|
|
|
|
|
s.cleanupTasksForKnowledgeBase(kbCleanupCtx, id, nil, nil)
|
|
|
|
|
cancelKBCleanup()
|
2026-07-22 20:51:40 +00:00
|
|
|
|
2026-01-30 08:28:01 +00:00
|
|
|
// Step 1b: Remove all organization shares for this KB so org settings no longer show them
|
2026-06-23 07:45:52 +00:00
|
|
|
if s.shareRepo != nil {
|
|
|
|
|
if delErr := s.shareRepo.DeleteByKnowledgeBaseID(ctx, id); delErr != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete KB shares for knowledge base %s: %v", id, delErr)
|
|
|
|
|
}
|
2026-01-30 08:28:01 +00:00
|
|
|
}
|
|
|
|
|
|
2026-06-23 07:45:52 +00:00
|
|
|
// Step 1c: Stop and soft-delete all data sources bound to this KB so cron
|
|
|
|
|
// schedules and in-flight sync logs do not keep running against a deleted KB.
|
2026-07-22 20:51:40 +00:00
|
|
|
dataSourceIDs := s.deleteDataSourcesForKnowledgeBase(ctx, id)
|
|
|
|
|
if len(dataSourceIDs) > 0 {
|
2026-07-23 04:19:21 +00:00
|
|
|
dsCancelCtx, cancelDSCancel := context.WithTimeout(
|
|
|
|
|
context.WithoutCancel(ctx), kbTaskCleanupTimeout,
|
|
|
|
|
)
|
|
|
|
|
s.cancelTasksForKnowledgeBase(dsCancelCtx, id, nil, dataSourceIDs)
|
|
|
|
|
cancelDSCancel()
|
2026-07-22 20:51:40 +00:00
|
|
|
}
|
2026-06-23 07:45:52 +00:00
|
|
|
|
2025-12-25 11:33:58 +00:00
|
|
|
// Step 2: Enqueue async task for heavy cleanup operations
|
|
|
|
|
payload := types.KBDeletePayload{
|
|
|
|
|
TenantID: tenantID,
|
|
|
|
|
KnowledgeBaseID: id,
|
2026-07-22 20:51:40 +00:00
|
|
|
DataSourceIDs: dataSourceIDs,
|
2025-12-25 11:33:58 +00:00
|
|
|
EffectiveEngines: tenantInfo.GetEffectiveEngines(),
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
VectorStoreID: vectorStoreIDSnapshot, // snapshot taken before soft-delete
|
2025-12-25 11:33:58 +00:00
|
|
|
}
|
feat(observability): extend Langfuse tracing across asynq pipeline
Previously the Langfuse integration only traced in-process HTTP requests
(chat / search / eval), so file uploads and every downstream asynq task
(document parse, chunk embedding, OCR/VLM, summary / question gen, wiki
ingest, datasource sync, etc.) produced either disconnected shallow
traces or no observation at all.
This change threads one trace end-to-end:
- tracer: add SPAN observation type and StartSpan; add ResumeTrace so a
worker can attach to an upstream trace without emitting a duplicate
trace-create; StartGeneration now auto-picks parentObservationId from
ctx so nested trace -> span -> generation trees render correctly.
- types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq
payloads so trace_id / parent_obs_id / user_id / session_id serialise
into every job.
- langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal
so the HTTP-layer trace survives the Redis hop.
- langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either
resumes the upstream trace or opens a standalone asynq.<type> trace
for scheduled jobs, and wraps the handler in a SPAN with task metadata
(id / queue / retry / payload_bytes) plus ERROR level on failure.
- GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation /
FAQ / wiki / datasource endpoints so the root trace actually starts.
- Tests: tracer_test.go covers span nesting, error status, and
ResumeTrace no-trace-create guarantee; asynq_test.go covers
InjectTracing round-trip, middleware resume path, and standalone
trace fallback.
- Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types
and documents the cross-process propagation model.
No behavioural change when Langfuse is disabled (all new code paths are
no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
|
|
|
langfuse.InjectTracing(ctx, &payload)
|
2025-12-25 11:33:58 +00:00
|
|
|
|
|
|
|
|
payloadBytes, err := json.Marshal(payload)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to marshal KB delete payload: %v", err)
|
|
|
|
|
// Don't fail the request, the KB record is already deleted
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-10 15:19:41 +00:00
|
|
|
task := asynq.NewTask(types.TypeKBDelete, payloadBytes,
|
|
|
|
|
asynq.Queue(types.QueueMaintenance), asynq.MaxRetry(3), asynq.Timeout(2*time.Hour))
|
2025-12-25 11:33:58 +00:00
|
|
|
info, err := s.asynqClient.Enqueue(task)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to enqueue KB delete task: %v", err)
|
|
|
|
|
// Don't fail the request, the KB record is already deleted
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "KB delete task enqueued: %s, knowledge base ID: %s", info.ID, id)
|
|
|
|
|
logger.Infof(ctx, "Knowledge base deleted successfully, ID: %s", id)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ProcessKBDelete handles async knowledge base deletion task
|
|
|
|
|
// This method performs heavy cleanup operations: deleting embeddings, chunks, files, and graph data
|
2026-09-14 13:02:31 +00:00
|
|
|
func (s *knowledgeBaseService) ProcessKBDelete(ctx context.Context, t *asynq.Task) (err error) {
|
2025-12-25 11:33:58 +00:00
|
|
|
var payload types.KBDeletePayload
|
2026-09-14 13:02:31 +00:00
|
|
|
if unmarshalErr := json.Unmarshal(t.Payload(), &payload); unmarshalErr != nil {
|
|
|
|
|
logger.Errorf(ctx, "Failed to unmarshal KB delete payload: %v", unmarshalErr)
|
|
|
|
|
return unmarshalErr
|
2025-12-25 11:33:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
tenantID := payload.TenantID
|
|
|
|
|
kbID := payload.KnowledgeBaseID
|
2026-07-22 20:51:40 +00:00
|
|
|
var knowledgeIDs []string
|
2025-12-25 11:33:58 +00:00
|
|
|
|
|
|
|
|
// Set tenant context for downstream services
|
|
|
|
|
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
|
2026-07-22 20:51:40 +00:00
|
|
|
defer func() {
|
2026-09-14 13:02:31 +00:00
|
|
|
// Wiki rows are independent of the vector engine. Run this on every
|
|
|
|
|
// return path — including SkipRetry — with its own timeout so a slow
|
|
|
|
|
// Redis queue scan cannot starve the SQL deletes.
|
|
|
|
|
wikiCtx, cancelWiki := context.WithTimeout(context.WithoutCancel(ctx), kbTaskCleanupTimeout)
|
|
|
|
|
wikiErr := s.cleanupWikiForKnowledgeBase(wikiCtx, tenantID, kbID)
|
|
|
|
|
cancelWiki()
|
|
|
|
|
if wikiErr != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to clean wiki data for KB %s: %v", kbID, wikiErr)
|
|
|
|
|
// SkipRetry would otherwise drop the task while wiki orphans
|
|
|
|
|
// remain. Promote the wiki error so asynq retries; a later
|
|
|
|
|
// attempt that succeeds at wiki cleanup can still SkipRetry.
|
|
|
|
|
if err == nil || errors.Is(err, asynq.SkipRetry) {
|
|
|
|
|
err = wikiErr
|
|
|
|
|
}
|
|
|
|
|
} else if err == nil {
|
|
|
|
|
logger.Infof(ctx, "KB delete task completed successfully, knowledge base ID: %s", kbID)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 20:51:40 +00:00
|
|
|
// Workers may enqueue downstream work while the delete task performs
|
|
|
|
|
// heavy storage cleanup. A detached, bounded final scrub runs on every
|
|
|
|
|
// return path, including retryable failures and cancellation.
|
|
|
|
|
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), kbTaskCleanupTimeout)
|
|
|
|
|
defer cancel()
|
|
|
|
|
s.cleanupTasksForKnowledgeBase(cleanupCtx, kbID, knowledgeIDs, payload.DataSourceIDs)
|
|
|
|
|
}()
|
2025-12-25 11:33:58 +00:00
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Processing KB delete task for knowledge base: %s", kbID)
|
|
|
|
|
|
|
|
|
|
// Step 1: Get all knowledge entries in this knowledge base
|
|
|
|
|
logger.Infof(ctx, "Fetching all knowledge entries in knowledge base, ID: %s", kbID)
|
|
|
|
|
knowledgeList, err := s.kgRepo.ListKnowledgeByKnowledgeBaseID(ctx, tenantID, kbID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": kbID,
|
|
|
|
|
})
|
|
|
|
|
return err
|
|
|
|
|
}
|
2025-11-23 09:27:30 +00:00
|
|
|
logger.Infof(ctx, "Found %d knowledge entries to delete", len(knowledgeList))
|
2026-07-22 20:51:40 +00:00
|
|
|
knowledgeIDs = make([]string, 0, len(knowledgeList))
|
|
|
|
|
for _, knowledge := range knowledgeList {
|
|
|
|
|
knowledgeIDs = append(knowledgeIDs, knowledge.ID)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Repeat the best-effort queue scrub with document IDs. Some batch tasks
|
|
|
|
|
// only carry knowledge_id(s), and active work from the first pass may have
|
|
|
|
|
// enqueued another downstream task before cancellation reached it.
|
|
|
|
|
s.cleanupTasksForKnowledgeBase(ctx, kbID, knowledgeIDs, payload.DataSourceIDs)
|
2025-11-23 09:27:30 +00:00
|
|
|
|
|
|
|
|
// Step 2: Delete all knowledge entries and their resources
|
|
|
|
|
if len(knowledgeList) > 0 {
|
|
|
|
|
logger.Infof(ctx, "Deleting all knowledge entries and their resources")
|
2025-11-23 09:32:50 +00:00
|
|
|
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
// Delete embeddings from vector store.
|
|
|
|
|
// Resolve the engine via the factory, using the VectorStoreID captured
|
|
|
|
|
// at enqueue time (may be nil → falls back to payload.EffectiveEngines).
|
|
|
|
|
// If the payload references a store no longer owned/registered
|
|
|
|
|
// (e.g. tampered queue entry or a store that was deleted while the
|
|
|
|
|
// task sat in the queue), the factory returns a sentinel and we
|
|
|
|
|
// SkipRetry to avoid burning retries on an unrecoverable situation.
|
2025-11-23 09:27:30 +00:00
|
|
|
logger.Infof(ctx, "Deleting embeddings from vector store")
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
retrieveEngine, err := retriever.CreateRetrieveEngineFromPayload(
|
|
|
|
|
ctx,
|
2025-11-28 08:17:52 +00:00
|
|
|
s.retrieveEngine,
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
s.ownership,
|
|
|
|
|
payload.TenantID,
|
2025-12-25 11:33:58 +00:00
|
|
|
payload.EffectiveEngines,
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
payload.VectorStoreID,
|
2025-11-28 08:17:52 +00:00
|
|
|
)
|
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.
2026-05-13 08:24:17 +00:00
|
|
|
if errors.Is(err, retriever.ErrVectorStoreForbidden) ||
|
|
|
|
|
errors.Is(err, retriever.ErrVectorStoreNotFound) {
|
|
|
|
|
logger.Errorf(ctx, "KB delete task aborted: %v (tenant=%d, kb=%s)", err, payload.TenantID, payload.KnowledgeBaseID)
|
|
|
|
|
return asynq.SkipRetry
|
|
|
|
|
}
|
2026-07-29 04:22:09 +00:00
|
|
|
if err != nil {
|
|
|
|
|
// Transient failures — store temporarily unavailable, request
|
|
|
|
|
// cancellation during resolution, or other retryable errors —
|
|
|
|
|
// must not fall through and report success while embeddings remain.
|
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
|
|
|
logger.Errorf(ctx, "KB delete task deferred: %v (tenant=%d, kb=%s)", err, payload.TenantID, payload.KnowledgeBaseID)
|
|
|
|
|
return err
|
2025-11-23 09:27:30 +00:00
|
|
|
} else {
|
2025-12-16 13:17:55 +00:00
|
|
|
// Group knowledge by embedding model and type
|
|
|
|
|
type groupKey struct {
|
|
|
|
|
EmbeddingModelID string
|
|
|
|
|
Type string
|
|
|
|
|
}
|
|
|
|
|
embeddingGroups := make(map[groupKey][]string)
|
2025-11-23 09:27:30 +00:00
|
|
|
for _, knowledge := range knowledgeList {
|
2025-12-16 13:17:55 +00:00
|
|
|
key := groupKey{EmbeddingModelID: knowledge.EmbeddingModelID, Type: knowledge.Type}
|
|
|
|
|
embeddingGroups[key] = append(embeddingGroups[key], knowledge.ID)
|
2025-11-23 09:27:30 +00:00
|
|
|
}
|
|
|
|
|
|
2025-12-16 13:17:55 +00:00
|
|
|
for key, knowledgeGroup := range embeddingGroups {
|
|
|
|
|
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, key.EmbeddingModelID)
|
2025-11-23 09:27:30 +00:00
|
|
|
if err != nil {
|
2025-12-16 13:17:55 +00:00
|
|
|
logger.Warnf(ctx, "Failed to get embedding model %s: %v", key.EmbeddingModelID, err)
|
2025-11-23 09:27:30 +00:00
|
|
|
continue
|
|
|
|
|
}
|
2025-12-16 13:17:55 +00:00
|
|
|
if err := retrieveEngine.DeleteByKnowledgeIDList(ctx, knowledgeGroup, embeddingModel.GetDimensions(), key.Type); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete embeddings for model %s: %v", key.EmbeddingModelID, err)
|
2025-11-23 09:27:30 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-01 13:45:23 +00:00
|
|
|
// Collect image URLs before chunks are deleted
|
|
|
|
|
chunkImageInfos, imgErr := s.chunkRepo.ListImageInfoByKnowledgeIDs(ctx, tenantID, knowledgeIDs)
|
|
|
|
|
if imgErr != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to collect image URLs for KB delete: %v", imgErr)
|
|
|
|
|
}
|
|
|
|
|
var imageInfoStrs []string
|
|
|
|
|
for _, ci := range chunkImageInfos {
|
|
|
|
|
imageInfoStrs = append(imageInfoStrs, ci.ImageInfo)
|
|
|
|
|
}
|
fix(knowledge): claim cloned and released document images in the resource catalog (#3752)
* fix(knowledge): claim cloned and released document images in the catalog
#3493 binds images at parse time (bindStoredImages), which covers ingestion
but not the two paths that move image ownership:
Clone. A copied image is written as a new object, yet nothing claimed it for
the destination knowledge, so the KB file proxy answered 403 and cloned
documents rendered without images. The copy now goes through SaveBytes into
the servable exports/ namespace (CopyFile wrote to the knowledge-scoped
upload layout the proxy rejects), is claimed by the destination knowledge,
and CloneChunk / FAQ clone bind the handles left in chunk content and
image_info.
Delete. Release only looked at multimodal ImageInfo, which stays empty for
documents whose images live in markdown alone, so those objects outlived the
knowledge that owned them. The release set is now the union of ImageInfo URLs
and the bindings recorded for the knowledge being removed, with source_file
excluded so reparse and cleanup keep the original document.
The parse-path claim from the earlier attempt is dropped: ProcessDocument
already gets it from bindStoredImages, and the removed test only string
matched that call in the source. Every claim path stays best-effort,
including the clone path, which used to fail the whole clone and delete the
fresh copy when a single Bind errored.
* fix(knowledge): keep markdown-only images out of the pre-reindex cleanup
cleanupKnowledgeResources runs before a knowledge is re-indexed -- a manual
update, a reparse, a move with reparse -- not before it is removed. Unioning
in the catalog bindings there released a solely owned markdown-only
attachment, deleteExtractedImages deleted the file, and the catalog file
service marked the resource deleted. The re-claim that runs after the cleanup
resolves through a state=active lookup, so it could never bind that handle
again: the republished body was left pointing at a deleted image.
Cleanup collects ImageInfo URLs alone again. The paths that do remove a
knowledge entry (executeKnowledgeDelete, ProcessKBDelete) keep the union, which
is what lets markdown-only images be released when the knowledge actually goes
away.
Reported by @lyingbug in review on #3752.
---------
Co-authored-by: tayadwx <tayadwx@users.noreply.github.com>
2026-10-09 05:01:26 +00:00
|
|
|
imageURLs := mergeKnowledgeReleaseURLs(
|
|
|
|
|
ctx, s.resourceCatalog, knowledgeIDs, collectImageURLs(ctx, imageInfoStrs))
|
2026-04-01 13:45:23 +00:00
|
|
|
|
2025-11-23 09:27:30 +00:00
|
|
|
// Delete all chunks
|
|
|
|
|
logger.Infof(ctx, "Deleting all chunks in knowledge base")
|
|
|
|
|
for _, knowledgeID := range knowledgeIDs {
|
|
|
|
|
if err := s.chunkRepo.DeleteChunksByKnowledgeID(ctx, tenantID, knowledgeID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete chunks for knowledge %s: %v", knowledgeID, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-01 13:45:23 +00:00
|
|
|
// Delete physical files, extracted images, and adjust storage
|
|
|
|
|
logger.Infof(ctx, "Deleting physical files and extracted images")
|
2025-11-23 09:27:30 +00:00
|
|
|
storageAdjust := int64(0)
|
|
|
|
|
for _, knowledge := range knowledgeList {
|
|
|
|
|
if knowledge.FilePath != "" {
|
|
|
|
|
if err := s.fileSvc.DeleteFile(ctx, knowledge.FilePath); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete file %s: %v", knowledge.FilePath, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
storageAdjust -= knowledge.StorageSize
|
|
|
|
|
}
|
2026-08-27 02:30:32 +00:00
|
|
|
deleteExtractedImages(ctx, s.fileSvc, knowledgeResourceOwners(s.resourceCatalog, knowledgeIDs...), imageURLs)
|
2025-11-23 09:27:30 +00:00
|
|
|
if storageAdjust != 0 {
|
|
|
|
|
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantID, storageAdjust); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to adjust tenant storage: %v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Delete knowledge graph data
|
|
|
|
|
logger.Infof(ctx, "Deleting knowledge graph data")
|
|
|
|
|
namespaces := make([]types.NameSpace, 0, len(knowledgeList))
|
|
|
|
|
for _, knowledge := range knowledgeList {
|
|
|
|
|
namespaces = append(namespaces, types.NameSpace{
|
|
|
|
|
KnowledgeBase: knowledge.KnowledgeBaseID,
|
|
|
|
|
Knowledge: knowledge.ID,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
if s.graphEngine != nil && len(namespaces) > 0 {
|
|
|
|
|
if err := s.graphEngine.DelGraph(ctx, namespaces); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete knowledge graph: %v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Delete all knowledge entries from database
|
|
|
|
|
logger.Infof(ctx, "Deleting knowledge entries from database")
|
|
|
|
|
if err := s.kgRepo.DeleteKnowledgeList(ctx, tenantID, knowledgeIDs); err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
2025-12-25 11:33:58 +00:00
|
|
|
"knowledge_base_id": kbID,
|
2025-11-23 09:27:30 +00:00
|
|
|
})
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-14 13:02:31 +00:00
|
|
|
logger.Infof(ctx, "KB resource cleanup finished, knowledge base ID: %s", kbID)
|
2025-08-05 07:08:07 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-14 13:02:31 +00:00
|
|
|
// cleanupWikiForKnowledgeBase removes wiki pages, folders, revisions, and
|
|
|
|
|
// issues for a deleted knowledge base. Pages, folders, and issues are
|
|
|
|
|
// soft-deleted (they carry DeletedAt); revisions are hard-deleted (no
|
|
|
|
|
// deleted_at column — they are immutable snapshots).
|
|
|
|
|
//
|
|
|
|
|
// nil-safe for tests that construct knowledgeBaseService without wikiRepo.
|
|
|
|
|
// Failures are returned so the KB delete task can retry; the caller logs.
|
|
|
|
|
func (s *knowledgeBaseService) cleanupWikiForKnowledgeBase(
|
|
|
|
|
ctx context.Context, tenantID uint64, kbID string,
|
|
|
|
|
) error {
|
|
|
|
|
if s.wikiRepo == nil || kbID == "" {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
logger.Infof(ctx, "Cleaning up wiki data for knowledge base")
|
|
|
|
|
var errs error
|
|
|
|
|
if err := s.wikiRepo.DeleteByKnowledgeBaseID(ctx, tenantID, kbID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete wiki pages for KB %s: %v", kbID, err)
|
|
|
|
|
errs = errors.Join(errs, err)
|
|
|
|
|
}
|
|
|
|
|
if err := s.wikiRepo.DeleteFoldersByKnowledgeBaseID(ctx, tenantID, kbID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete wiki folders for KB %s: %v", kbID, err)
|
|
|
|
|
errs = errors.Join(errs, err)
|
|
|
|
|
}
|
|
|
|
|
if err := s.wikiRepo.DeleteRevisionsByKnowledgeBaseID(ctx, tenantID, kbID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete wiki revisions for KB %s: %v", kbID, err)
|
|
|
|
|
errs = errors.Join(errs, err)
|
|
|
|
|
}
|
|
|
|
|
if err := s.wikiRepo.DeleteIssuesByKnowledgeBaseID(ctx, tenantID, kbID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete wiki issues for KB %s: %v", kbID, err)
|
|
|
|
|
errs = errors.Join(errs, err)
|
|
|
|
|
}
|
|
|
|
|
return errs
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 20:51:40 +00:00
|
|
|
// cancelTasksForKnowledgeBase removes queue work for a deleted KB when the
|
|
|
|
|
// configured task backend supports knowledge-base-wide inspection. Queue
|
|
|
|
|
// cleanup is an optimization: the soft-deleted database row remains the
|
|
|
|
|
// durable source of truth, so backend failures must not fail KB deletion.
|
|
|
|
|
func (s *knowledgeBaseService) cancelTasksForKnowledgeBase(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
kbID string,
|
|
|
|
|
knowledgeIDs []string,
|
|
|
|
|
dataSourceIDs []string,
|
|
|
|
|
) {
|
|
|
|
|
canceller, ok := s.taskInspector.(interfaces.KnowledgeBaseTaskCanceller)
|
|
|
|
|
if !ok || kbID == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if _, _, err := canceller.CancelTasksForKnowledgeBase(ctx, kbID, knowledgeIDs, dataSourceIDs); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to cancel queued tasks for deleted KB %s: %v", kbID, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// cleanupTasksForKnowledgeBase removes both asynq records and durable wiki
|
|
|
|
|
// operations. The latter must be cleared as well or startup recovery can
|
|
|
|
|
// recreate Redis triggers for a KB that no longer exists.
|
|
|
|
|
func (s *knowledgeBaseService) cleanupTasksForKnowledgeBase(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
kbID string,
|
|
|
|
|
knowledgeIDs []string,
|
|
|
|
|
dataSourceIDs []string,
|
|
|
|
|
) {
|
|
|
|
|
if kbID == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
cleaner, ok := s.taskPendingRepo.(interfaces.TaskPendingOpsScopeCleaner)
|
|
|
|
|
if ok {
|
|
|
|
|
// Clear durable work before scanning Redis. A large or degraded queue
|
|
|
|
|
// must not consume the caller's entire deadline and starve the database
|
|
|
|
|
// fence that prevents startup recovery from reviving this KB.
|
|
|
|
|
if err := cleaner.DeleteByScope(ctx, types.TaskScopeKnowledgeBase, kbID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to clear durable tasks for deleted KB %s: %v", kbID, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
s.cancelTasksForKnowledgeBase(ctx, kbID, knowledgeIDs, dataSourceIDs)
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-23 07:45:52 +00:00
|
|
|
// deleteDataSourcesForKnowledgeBase mirrors DataSourceService.DeleteDataSource for
|
|
|
|
|
// every data source attached to the KB. Errors on individual sources are logged
|
|
|
|
|
// but do not fail KB deletion — the KB record is already soft-deleted.
|
2026-07-22 20:51:40 +00:00
|
|
|
func (s *knowledgeBaseService) deleteDataSourcesForKnowledgeBase(ctx context.Context, kbID string) []string {
|
2026-06-23 07:45:52 +00:00
|
|
|
if s.dsRepo == nil {
|
2026-07-22 20:51:40 +00:00
|
|
|
return nil
|
2026-06-23 07:45:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
dataSources, err := s.dsRepo.FindByKnowledgeBase(ctx, kbID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to list data sources for deleted KB %s: %v", kbID, err)
|
2026-07-22 20:51:40 +00:00
|
|
|
return nil
|
2026-06-23 07:45:52 +00:00
|
|
|
}
|
2026-07-22 20:51:40 +00:00
|
|
|
dataSourceIDs := make([]string, 0, len(dataSources))
|
2026-06-23 07:45:52 +00:00
|
|
|
for _, ds := range dataSources {
|
|
|
|
|
if ds == nil || ds.ID == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
2026-07-22 20:51:40 +00:00
|
|
|
dataSourceIDs = append(dataSourceIDs, ds.ID)
|
2026-06-23 07:45:52 +00:00
|
|
|
if err := s.dsRepo.Delete(ctx, ds.ID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to delete data source %s for KB %s: %v", ds.ID, kbID, err)
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if s.dsScheduler != nil {
|
|
|
|
|
s.dsScheduler.Remove(ds.ID)
|
|
|
|
|
}
|
|
|
|
|
if s.syncLogRepo != nil {
|
|
|
|
|
if err := s.syncLogRepo.CancelPendingByDataSource(ctx, ds.ID); err != nil {
|
|
|
|
|
logger.Warnf(ctx, "Failed to cancel pending sync logs for ds=%s (kb=%s): %v", ds.ID, kbID, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
logger.Infof(ctx, "Data source deleted with knowledge base: ds=%s kb=%s", ds.ID, kbID)
|
|
|
|
|
}
|
2026-07-22 20:51:40 +00:00
|
|
|
return dataSourceIDs
|
2026-06-23 07:45:52 +00:00
|
|
|
}
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
// SetEmbeddingModel sets the embedding model for a knowledge base
|
|
|
|
|
func (s *knowledgeBaseService) SetEmbeddingModel(ctx context.Context, id string, modelID string) error {
|
|
|
|
|
if id == "" {
|
|
|
|
|
logger.Error(ctx, "Knowledge base ID is empty")
|
|
|
|
|
return errors.New("knowledge base ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if modelID == "" {
|
|
|
|
|
logger.Error(ctx, "Model ID is empty")
|
|
|
|
|
return errors.New("model ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Setting embedding model for knowledge base, knowledge base ID: %s, model ID: %s", id, modelID)
|
|
|
|
|
|
|
|
|
|
// Get the knowledge base
|
|
|
|
|
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
})
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update the knowledge base's embedding model
|
|
|
|
|
kb.EmbeddingModelID = modelID
|
|
|
|
|
kb.UpdatedAt = time.Now()
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Saving knowledge base embedding model update")
|
|
|
|
|
err = s.repo.UpdateKnowledgeBase(ctx, kb)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
|
|
|
|
"knowledge_base_id": id,
|
|
|
|
|
"embedding_model_id": modelID,
|
|
|
|
|
})
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.Infof(
|
|
|
|
|
ctx,
|
|
|
|
|
"Knowledge base embedding model set successfully, knowledge base ID: %s, model ID: %s",
|
|
|
|
|
id,
|
|
|
|
|
modelID,
|
|
|
|
|
)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-06 06:45:37 +00:00
|
|
|
// CopyKnowledgeBase copies a knowledge base to a new knowledge base (shallow copy).
|
|
|
|
|
// Source and target must belong to the tenant in context; cross-tenant access is rejected.
|
2026-05-18 01:10:01 +00:00
|
|
|
//
|
2026-09-08 07:36:33 +00:00
|
|
|
// The transfer grant fixes both resource IDs and whether a new destination
|
|
|
|
|
// may be created. Existing targets must be compatible with the source. A
|
|
|
|
|
// worker retry reloads the reserved target instead of creating another KB.
|
2025-08-05 07:08:07 +00:00
|
|
|
func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
|
|
|
|
|
srcKB string, dstKB string,
|
|
|
|
|
) (*types.KnowledgeBase, *types.KnowledgeBase, error) {
|
2026-09-08 07:36:33 +00:00
|
|
|
destinationID, create, creatorID, err := access.CloneDestination(ctx, srcKB)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, nil, err
|
|
|
|
|
}
|
|
|
|
|
if dstKB != "" && dstKB != destinationID {
|
|
|
|
|
return nil, nil, access.ErrForbidden
|
|
|
|
|
}
|
2026-02-28 10:11:37 +00:00
|
|
|
tenantID := types.MustTenantIDFromContext(ctx)
|
2026-02-06 06:45:37 +00:00
|
|
|
sourceKB, err := s.repo.GetKnowledgeBaseByIDAndTenant(ctx, srcKB, tenantID)
|
2025-08-05 07:08:07 +00:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, nil, err
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
if sourceKB == nil || sourceKB.ID != srcKB || sourceKB.TenantID != tenantID {
|
|
|
|
|
return nil, nil, access.ErrForbidden
|
|
|
|
|
}
|
|
|
|
|
sourceCopy := *sourceKB
|
|
|
|
|
sourceKB = &sourceCopy
|
2025-11-14 17:30:17 +00:00
|
|
|
sourceKB.EnsureDefaults()
|
2026-09-08 07:36:33 +00:00
|
|
|
targetKB, err := s.repo.GetKnowledgeBaseByIDAndTenant(ctx, destinationID, tenantID)
|
|
|
|
|
if err != nil && (!create || !errors.Is(err, repository.ErrKnowledgeBaseNotFound)) {
|
|
|
|
|
return nil, nil, err
|
|
|
|
|
}
|
|
|
|
|
if targetKB != nil {
|
|
|
|
|
targetCopy := *targetKB
|
|
|
|
|
targetKB = &targetCopy
|
|
|
|
|
targetKB.EnsureDefaults()
|
|
|
|
|
if err := access.RequireKBTransfer(ctx, sourceKB, targetKB, access.KBTransferClone); err != nil {
|
2025-08-05 07:08:07 +00:00
|
|
|
return nil, nil, err
|
|
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
|
|
|
|
if err := access.ValidateKBTransferCompatibility(sourceKB,
|
|
|
|
|
targetKB,
|
|
|
|
|
access.KBTransferClone,
|
|
|
|
|
"",
|
|
|
|
|
tenant); err != nil {
|
|
|
|
|
return nil, nil, apperrors.NewBadRequestError(err.Error())
|
2026-05-18 01:10:01 +00:00
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
} else {
|
|
|
|
|
reserved := &types.KnowledgeBase{ID: destinationID, TenantID: tenantID}
|
|
|
|
|
if !create {
|
|
|
|
|
return nil, nil, access.ErrNotFound
|
2026-05-18 01:10:01 +00:00
|
|
|
}
|
2026-09-08 07:36:33 +00:00
|
|
|
if err := access.RequireKBTransfer(ctx, sourceKB, reserved, access.KBTransferClone); err != nil {
|
|
|
|
|
return nil, nil, err
|
2026-06-02 11:25:38 +00:00
|
|
|
}
|
2025-11-14 17:30:17 +00:00
|
|
|
var faqConfig *types.FAQConfig
|
|
|
|
|
if sourceKB.FAQConfig != nil {
|
|
|
|
|
cfg := *sourceKB.FAQConfig
|
|
|
|
|
faqConfig = &cfg
|
|
|
|
|
}
|
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
|
|
|
var profileConfig *types.KnowledgeBaseProfileConfig
|
|
|
|
|
if sourceKB.ProfileConfig != nil {
|
|
|
|
|
cfg := *sourceKB.ProfileConfig
|
|
|
|
|
profileConfig = &cfg
|
|
|
|
|
}
|
2026-05-18 01:10:01 +00:00
|
|
|
// Preserve VectorStoreID so the cloned KB lands on the same
|
|
|
|
|
// physical index. GORM `<-:create` permits the value at INSERT.
|
2025-08-05 07:08:07 +00:00
|
|
|
targetKB = &types.KnowledgeBase{
|
2026-09-08 07:36:33 +00:00
|
|
|
ID: destinationID,
|
|
|
|
|
CreatorID: creatorID,
|
2025-08-05 07:08:07 +00:00
|
|
|
Name: sourceKB.Name,
|
2025-11-20 12:08:24 +00:00
|
|
|
Type: sourceKB.Type,
|
|
|
|
|
Description: sourceKB.Description,
|
|
|
|
|
TenantID: tenantID,
|
|
|
|
|
ChunkingConfig: sourceKB.ChunkingConfig,
|
|
|
|
|
ImageProcessingConfig: sourceKB.ImageProcessingConfig,
|
|
|
|
|
EmbeddingModelID: sourceKB.EmbeddingModelID,
|
|
|
|
|
SummaryModelID: sourceKB.SummaryModelID,
|
|
|
|
|
VLMConfig: sourceKB.VLMConfig,
|
2026-03-02 03:02:19 +00:00
|
|
|
StorageProviderConfig: sourceKB.StorageProviderConfig,
|
2026-07-15 05:26:29 +00:00
|
|
|
StorageBackendID: sourceKB.StorageBackendID,
|
2025-11-20 12:08:24 +00:00
|
|
|
StorageConfig: sourceKB.StorageConfig,
|
|
|
|
|
FAQConfig: faqConfig,
|
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
|
|
|
ProfileConfig: profileConfig,
|
2026-05-18 01:10:01 +00:00
|
|
|
VectorStoreID: sourceKB.VectorStoreID,
|
2025-11-20 12:08:24 +00:00
|
|
|
}
|
feat(rbac): enforce tenant role matrix on routes (PR 2 of 3, #1303)
Build on PR 1's tenant_members schema by enforcing the role matrix on
every authenticated route and at agent run time. Enforcement is gated
behind cfg.Tenant.EnableRBAC so the change ships dormant — the same
code paths log the would-be rejection during the rollout window and
start blocking once operators flip the flag.
Middleware (internal/middleware/rbac.go):
- RequireRole(min, cfg): role-only gate using TenantRole.HasPermission.
- RequireOwnershipOrRole(min, lookup, cfg): allows the original creator
through even when their role is below min, otherwise falls back to
the role check. Lookup errors fail closed; an empty creator_id is
treated as tenant-owned and requires the role.
- Both honour cfg.Tenant.EnableRBAC for the rollout window.
Creator lookups (internal/handler/rbac_lookups.go):
- KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID.
- AgentCreatorLookup resolves :id -> CustomAgent.CreatedBy; built-in
agents (IsBuiltin=true) return ("", nil) so they remain Admin+ only.
- Compile-time guards keep the methods aligned with CreatorLookup.
Route guards (internal/router/rbac.go + router.go):
- rbacGuards bundles the matrix into Viewer/Contributor/Admin/Owner
helpers plus OwnedKBOrAdmin / OwnedAgentOrAdmin. Each Register*
function takes *rbacGuards so route lines remain readable.
- KB / Agent / Knowledge / Chunk / Tenant / Model / MCPService /
VectorStore / DataSource / IMChannel routes annotated per the PR 1
design doc matrix. Tenant-wide infra (models, vector stores, MCP,
data sources, IM channels) reads as Viewer+ and writes as Admin+;
per-resource mutations on KB / Agent route through the
ownership-or-Admin guard.
Resource ownership (services):
- CreateKnowledgeBase / CopyKnowledgeBase populate CreatorID from the
authenticated user, so the OwnedKBOrAdmin guard has a creator to
match.
- CreateAgent / CopyAgent populate CreatedBy similarly. Built-in
agents stay tenant-owned.
Agent run-time gate (internal/handler/session/qa.go):
- AgentQA refuses to launch the agent engine for Viewers when the
target agent has RunnableByViewer=false. Same EnableRBAC gating as
the middleware so it's a no-op until enforcement is turned on.
Tests:
- 12 unit tests cover RequireRole / RequireOwnershipOrRole, including
the fail-open and fail-closed branches and the lookup-error path.
2026-05-13 13:16:54 +00:00
|
|
|
// The clone is owned by the caller, not the original creator —
|
|
|
|
|
// otherwise a Contributor copying someone else's KB would still
|
fix(rbac): address PR 2 review feedback
Middleware
- RequireOwnershipOrRole now skips the creator lookup entirely when
EnableRBAC is off, eliminating a hidden per-request DB roundtrip in
the rollout window.
- New ErrResourceNotFound sentinel lets lookups signal "not visible to
this tenant"; the middleware passes the request through so handlers
can return a real 404 instead of a misleading 403.
- Transient lookup failures now surface as 503 (was 403) so monitoring
can tell denied-by-policy from cannot-verify-right-now.
- Cross-tenant superusers (CanAccessAllTenants) bypass tenant role gates,
restoring DELETE /tenants/:id and ResetAPIKey for org operators that
resolve to Admin in foreign tenants.
- Construction-time warning fires once when cfg is nil/incomplete, so a
wiring bug that disables enforcement globally is visible at boot.
Route coverage
- Add role guards to FAQ, KnowledgeTag, WikiPage, Skill, WebSearch,
WebSearchProvider, WeKnoraCloud, Session, Chat, and Message route
groups so the matrix actually matches the PR description.
Service layer
- KB and agent creators are no longer recorded as the synthetic
system-<tenantID> user used by the X-API-Key path; resources stay
tenant-owned. New types.IsSyntheticUserID helper centralises the
prefix check.
- KBCreatorLookup and AgentCreatorLookup re-check tenant scope so a
same-ID resource in another tenant cannot piggyback through the
ownership shortcut.
Docs
- CustomAgent.RunnableByViewer comment now matches enforcement: it only
blocks Viewer-driven agent-mode runs, not plain RAG/Wiki QA.
Tests
- New cases for the 503/404 paths, lookup-skip behaviour, cross-tenant
superuser bypass, the lookup helpers (not-found, cross-tenant,
built-in agent, missing tenant context), and IsSyntheticUserID.
2026-05-13 13:37:47 +00:00
|
|
|
// not be able to edit the result. Skip synthetic API-key users
|
|
|
|
|
// (see CreateKnowledgeBase for the same reasoning).
|
|
|
|
|
if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) {
|
feat(rbac): enforce tenant role matrix on routes (PR 2 of 3, #1303)
Build on PR 1's tenant_members schema by enforcing the role matrix on
every authenticated route and at agent run time. Enforcement is gated
behind cfg.Tenant.EnableRBAC so the change ships dormant — the same
code paths log the would-be rejection during the rollout window and
start blocking once operators flip the flag.
Middleware (internal/middleware/rbac.go):
- RequireRole(min, cfg): role-only gate using TenantRole.HasPermission.
- RequireOwnershipOrRole(min, lookup, cfg): allows the original creator
through even when their role is below min, otherwise falls back to
the role check. Lookup errors fail closed; an empty creator_id is
treated as tenant-owned and requires the role.
- Both honour cfg.Tenant.EnableRBAC for the rollout window.
Creator lookups (internal/handler/rbac_lookups.go):
- KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID.
- AgentCreatorLookup resolves :id -> CustomAgent.CreatedBy; built-in
agents (IsBuiltin=true) return ("", nil) so they remain Admin+ only.
- Compile-time guards keep the methods aligned with CreatorLookup.
Route guards (internal/router/rbac.go + router.go):
- rbacGuards bundles the matrix into Viewer/Contributor/Admin/Owner
helpers plus OwnedKBOrAdmin / OwnedAgentOrAdmin. Each Register*
function takes *rbacGuards so route lines remain readable.
- KB / Agent / Knowledge / Chunk / Tenant / Model / MCPService /
VectorStore / DataSource / IMChannel routes annotated per the PR 1
design doc matrix. Tenant-wide infra (models, vector stores, MCP,
data sources, IM channels) reads as Viewer+ and writes as Admin+;
per-resource mutations on KB / Agent route through the
ownership-or-Admin guard.
Resource ownership (services):
- CreateKnowledgeBase / CopyKnowledgeBase populate CreatorID from the
authenticated user, so the OwnedKBOrAdmin guard has a creator to
match.
- CreateAgent / CopyAgent populate CreatedBy similarly. Built-in
agents stay tenant-owned.
Agent run-time gate (internal/handler/session/qa.go):
- AgentQA refuses to launch the agent engine for Viewers when the
target agent has RunnableByViewer=false. Same EnableRBAC gating as
the middleware so it's a no-op until enforcement is turned on.
Tests:
- 12 unit tests cover RequireRole / RequireOwnershipOrRole, including
the fail-open and fail-closed branches and the lookup-error path.
2026-05-13 13:16:54 +00:00
|
|
|
targetKB.CreatorID = uid
|
|
|
|
|
}
|
2025-11-14 17:30:17 +00:00
|
|
|
targetKB.EnsureDefaults()
|
2025-08-05 07:08:07 +00:00
|
|
|
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
|
|
|
|
|
return nil, nil, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return sourceKB, targetKB, nil
|
|
|
|
|
}
|
2026-07-08 12:43:12 +00:00
|
|
|
|
|
|
|
|
// DuplicateKnowledgeBase creates a new KB from the source KB's settings only.
|
|
|
|
|
// Runtime/content state is deliberately reset so this path never copies
|
|
|
|
|
// knowledge entries, chunks, FAQ content, wiki pages, indexes, shares or pins.
|
|
|
|
|
func (s *knowledgeBaseService) DuplicateKnowledgeBase(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
srcKB string,
|
|
|
|
|
) (*types.KnowledgeBase, error) {
|
|
|
|
|
srcKB = strings.TrimSpace(srcKB)
|
|
|
|
|
if srcKB == "" {
|
|
|
|
|
return nil, apperrors.NewBadRequestError("source knowledge base ID cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
tenantID := types.MustTenantIDFromContext(ctx)
|
|
|
|
|
sourceKB, err := s.repo.GetKnowledgeBaseByIDAndTenant(ctx, srcKB, tenantID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Errorf(ctx, "Get source knowledge base failed: %v", err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
sourceKB.EnsureDefaults()
|
|
|
|
|
|
|
|
|
|
targetKB, err := cloneKnowledgeBaseConfiguration(sourceKB)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
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
|
|
|
// A duplicate copies settings, not content. The generated description is
|
|
|
|
|
// derived from the source's documents, so carrying it over would describe
|
|
|
|
|
// documents the copy does not have; ProfileConfig is kept so the copy
|
|
|
|
|
// produces its own once documents arrive.
|
|
|
|
|
targetKB.GeneratedProfile = nil
|
2026-07-08 12:53:59 +00:00
|
|
|
targetKB.ID = uuid.New().String()
|
2026-07-08 12:43:12 +00:00
|
|
|
targetKB.TenantID = tenantID
|
|
|
|
|
targetKB.Name = s.buildDuplicateKnowledgeBaseName(ctx, tenantID, sourceKB.Name)
|
|
|
|
|
targetKB.CreatorID = ""
|
|
|
|
|
if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) {
|
|
|
|
|
targetKB.CreatorID = uid
|
|
|
|
|
}
|
|
|
|
|
now := time.Now()
|
|
|
|
|
targetKB.CreatedAt = now
|
|
|
|
|
targetKB.UpdatedAt = now
|
|
|
|
|
targetKB.DeletedAt.Valid = false
|
|
|
|
|
targetKB.DeletedAt.Time = time.Time{}
|
|
|
|
|
targetKB.IsTemporary = false
|
|
|
|
|
targetKB.IsPinned = false
|
|
|
|
|
targetKB.PinnedAt = nil
|
|
|
|
|
targetKB.KnowledgeCount = 0
|
|
|
|
|
targetKB.ChunkCount = 0
|
|
|
|
|
targetKB.IsProcessing = false
|
|
|
|
|
targetKB.ProcessingCount = 0
|
|
|
|
|
targetKB.ShareCount = 0
|
|
|
|
|
targetKB.CreatorName = ""
|
|
|
|
|
targetKB.EnsureDefaults()
|
|
|
|
|
targetKB.Normalize()
|
|
|
|
|
|
|
|
|
|
if targetKB.HasVectorStore() {
|
|
|
|
|
if err := s.validateVectorStoreBinding(ctx, tenantID, *targetKB.VectorStoreID); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-07-22 11:15:27 +00:00
|
|
|
recordKBActivity(ctx, s.audit, tenantID, targetKB.ID, types.AuditActionKBDuplicated,
|
|
|
|
|
"knowledge_base", targetKB.ID, types.AuditOutcomeSuccess, map[string]any{
|
|
|
|
|
"source_kb_id": sourceKB.ID, "name": targetKB.Name,
|
|
|
|
|
})
|
2026-07-08 12:43:12 +00:00
|
|
|
return targetKB, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-08 12:53:59 +00:00
|
|
|
func duplicateKBCopySuffix(locale string) string {
|
|
|
|
|
locale = strings.ToLower(locale)
|
|
|
|
|
switch {
|
|
|
|
|
case strings.HasPrefix(locale, "zh"):
|
|
|
|
|
return " 副本"
|
|
|
|
|
case strings.HasPrefix(locale, "ko"):
|
|
|
|
|
return " 사본"
|
|
|
|
|
case strings.HasPrefix(locale, "ru"):
|
|
|
|
|
return " копия"
|
|
|
|
|
default:
|
|
|
|
|
return " Copy"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func duplicateKBDefaultName(locale string) string {
|
|
|
|
|
locale = strings.ToLower(locale)
|
|
|
|
|
switch {
|
|
|
|
|
case strings.HasPrefix(locale, "zh"):
|
|
|
|
|
return "知识库"
|
|
|
|
|
case strings.HasPrefix(locale, "ko"):
|
|
|
|
|
return "지식베이스"
|
|
|
|
|
case strings.HasPrefix(locale, "ru"):
|
|
|
|
|
return "База знаний"
|
|
|
|
|
default:
|
|
|
|
|
return "Knowledge Base"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-08 12:43:12 +00:00
|
|
|
func (s *knowledgeBaseService) buildDuplicateKnowledgeBaseName(
|
|
|
|
|
ctx context.Context,
|
|
|
|
|
tenantID uint64,
|
|
|
|
|
sourceName string,
|
|
|
|
|
) string {
|
2026-08-05 07:24:10 +00:00
|
|
|
locale := types.LanguageFromContextOrDefault(ctx)
|
2026-07-08 12:53:59 +00:00
|
|
|
suffix := duplicateKBCopySuffix(locale)
|
|
|
|
|
|
2026-07-08 12:43:12 +00:00
|
|
|
baseName := strings.TrimSpace(sourceName)
|
|
|
|
|
if baseName == "" {
|
2026-07-08 12:53:59 +00:00
|
|
|
baseName = duplicateKBDefaultName(locale)
|
2026-07-08 12:43:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warnf(ctx, "List tenant knowledge bases failed while building duplicate name: %v", err)
|
2026-07-08 12:53:59 +00:00
|
|
|
return baseName + suffix
|
2026-07-08 12:43:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
existing := make(map[string]struct{}, len(kbs))
|
|
|
|
|
for _, kb := range kbs {
|
|
|
|
|
if kb == nil {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
existing[kb.Name] = struct{}{}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-08 12:53:59 +00:00
|
|
|
candidate := baseName + suffix
|
2026-07-08 12:43:12 +00:00
|
|
|
if _, ok := existing[candidate]; !ok {
|
|
|
|
|
return candidate
|
|
|
|
|
}
|
|
|
|
|
for i := 2; ; i++ {
|
2026-07-08 12:53:59 +00:00
|
|
|
candidate = fmt.Sprintf("%s%s %d", baseName, suffix, i)
|
2026-07-08 12:43:12 +00:00
|
|
|
if _, ok := existing[candidate]; !ok {
|
|
|
|
|
return candidate
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func cloneKnowledgeBaseConfiguration(sourceKB *types.KnowledgeBase) (*types.KnowledgeBase, error) {
|
|
|
|
|
if sourceKB == nil {
|
|
|
|
|
return nil, apperrors.NewBadRequestError("source knowledge base cannot be empty")
|
|
|
|
|
}
|
|
|
|
|
data, err := json.Marshal(sourceKB)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
var targetKB types.KnowledgeBase
|
|
|
|
|
if err := json.Unmarshal(data, &targetKB); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return &targetKB, nil
|
|
|
|
|
}
|