WeKnora/internal/application/service/knowledge_transfer_test.go

544 lines
19 KiB
Go
Raw Normal View History

package service
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/Tencent/WeKnora/internal/application/access"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/alicebob/miniredis/v2"
"github.com/hibiken/asynq"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
func transferFixture(t *testing.T, operation access.KBTransferOperation) *documentWriteFixture {
t.Helper()
f := newDocumentWriteFixture(t)
require.NoError(t, f.db.AutoMigrate(&types.Tenant{}))
require.NoError(t, f.db.Create(&types.Tenant{ID: 7, Name: "tenant", StorageUsed: 5}).Error)
require.NoError(
t,
f.db.Model(&types.Knowledge{}).Where("id = ?", "doc").Update("parse_status", types.ParseStatusCompleted).Error,
)
ctx, err := access.WithKBTransferTask(
context.Background(),
f.kbs.values["kb"],
f.kbs.values["other"],
7,
operation,
"transfer-task",
false,
)
require.NoError(t, err)
f.ctx = context.WithValue(ctx, types.TenantInfoContextKey, &types.Tenant{ID: 7, StorageUsed: 5})
mr := miniredis.RunT(t)
f.svc.redisClient = redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { require.NoError(t, f.svc.redisClient.Close()) })
return f
}
func moveTask(t *testing.T, ids []string, mode string) *asynq.Task {
t.Helper()
raw, err := json.Marshal(
types.KnowledgeMovePayload{
TenantID: 7,
TaskID: "transfer-task",
SourceKBID: "kb",
TargetKBID: "other",
KnowledgeIDs: ids,
Mode: mode,
},
)
require.NoError(t, err)
return asynq.NewTask(types.TypeKnowledgeMove, raw)
}
func TestMoveBatchPreflightHasNoPartialMutations(t *testing.T) {
for _, ids := range [][]string{{"doc", "missing"}, {"doc", "other-doc"}, {"doc", ""}} {
t.Run(ids[1], func(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
err := f.svc.ProcessKnowledgeMove(context.Background(), moveTask(t, ids, "reuse_vectors"))
require.Error(t, err)
row, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.Equal(t, types.ParseStatusCompleted, row.ParseStatus)
require.Equal(t, "kb", row.KnowledgeBaseID)
require.Empty(t, row.Metadata)
require.Zero(t, f.chunkRepo.writes)
require.Zero(t, f.graph.calls)
})
}
}
func TestMoveRejectsInvalidPairAndModeBeforeWrites(t *testing.T) {
for _, change := range []string{"tenant", "same KB", "mode", "chunk", "tag"} {
t.Run(change, func(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
mode := "reuse_vectors"
switch change {
case "tenant":
f.kbs.values["other"].TenantID = 8
case "same KB":
f.kbs.values["other"].ID = "kb"
case "mode":
mode = "bogus"
case "chunk":
require.NoError(
t,
f.db.Model(&types.Chunk{}).Where("id = ?", "chunk").Update("knowledge_base_id", "third").Error,
)
case "tag":
require.NoError(t, f.db.Model(&types.Chunk{}).Where("id = ?", "chunk").Update("tag_id", "tag").Error)
require.NoError(
t,
f.db.Model(&types.KnowledgeTag{}).Where("id = ?", "tag").Update("knowledge_base_id", "other").Error,
)
}
require.Error(t, f.svc.ProcessKnowledgeMove(context.Background(), moveTask(t, []string{"doc"}, mode)))
row, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.Equal(t, types.ParseStatusCompleted, row.ParseStatus)
require.Empty(t, row.Metadata)
})
}
}
type transferFaultRepo struct {
interfaces.KnowledgeRepository
failID string
claims int
}
func (r *transferFaultRepo) DeleteKnowledgeTagRelations(ctx context.Context, id string) error {
if id == r.failID {
return errors.New("temporary tag cleanup failure")
}
return r.KnowledgeRepository.DeleteKnowledgeTagRelations(ctx, id)
}
func (r *transferFaultRepo) UpdateKnowledgeForTransfer(ctx context.Context, before, after *types.Knowledge) error {
r.claims++
return r.KnowledgeRepository.UpdateKnowledgeForTransfer(ctx, before, after)
}
func TestMovePartialFailureResumesAndSkipsCompletedDocuments(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
require.NoError(
t,
f.db.Create(
&types.Knowledge{ID: "second", TenantID: 7, KnowledgeBaseID: "kb", ParseStatus: types.ParseStatusCompleted},
).Error,
)
require.NoError(
t,
f.db.Create(
&types.Chunk{
ID: "second-chunk",
TenantID: 7,
KnowledgeID: "second",
KnowledgeBaseID: "kb",
ChunkType: types.ChunkTypeImageOCR,
},
).Error,
)
fault := &transferFaultRepo{KnowledgeRepository: f.repo, failID: "second"}
f.svc.repo = fault
task := moveTask(t, []string{"doc", "doc", "second"}, "reuse_vectors")
require.ErrorContains(t, f.svc.ProcessKnowledgeMove(context.Background(), task), "temporary tag cleanup failure")
first, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.Equal(t, "other", first.KnowledgeBaseID)
firstUpdated := first.UpdatedAt
second, err := f.repo.GetKnowledgeByID(f.ctx, 7, "second")
require.NoError(t, err)
require.Equal(t, "kb", second.KnowledgeBaseID)
state, err := transferState(second)
require.NoError(t, err)
require.Equal(t, "moving", state.Phase)
fault.failID = ""
require.NoError(t, f.svc.ProcessKnowledgeMove(context.Background(), task))
first, err = f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.Equal(t, firstUpdated, first.UpdatedAt, "completed item must not be moved again")
second, err = f.repo.GetKnowledgeByID(f.ctx, 7, "second")
require.NoError(t, err)
require.Equal(t, "other", second.KnowledgeBaseID)
require.Equal(t, types.ParseStatusCompleted, second.ParseStatus)
progress, err := f.svc.GetKnowledgeMoveProgress(f.ctx, "transfer-task")
require.NoError(t, err)
require.Equal(t, 2, progress.Total)
require.Zero(t, progress.Failed)
require.Equal(t, types.KBCloneStatusCompleted, progress.Status)
}
type transferQueue struct {
fail bool
ids []string
}
func (q *transferQueue) Enqueue(_ *asynq.Task, options ...asynq.Option) (*asynq.TaskInfo, error) {
for _, option := range options {
if option.Type() == asynq.TaskIDOpt {
q.ids = append(q.ids, option.Value().(string))
}
}
if q.fail {
return nil, errors.New("queue unavailable")
}
return &asynq.TaskInfo{ID: "processing-task"}, nil
}
func TestMoveReparseRetryOnlyReenqueuesAndAccountsOnce(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
row, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.NoError(
t,
row.SetManualMetadata(types.NewManualKnowledgeMetadata("# content", types.ManualKnowledgeStatusPublish, 1)),
)
require.NoError(t, f.repo.UpdateKnowledge(f.ctx, row))
queue := &transferQueue{fail: true}
f.svc.task = queue
task := moveTask(t, []string{"doc"}, "reparse")
require.ErrorContains(t, f.svc.ProcessKnowledgeMove(context.Background(), task), "queue unavailable")
row, err = f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.Equal(t, "other", row.KnowledgeBaseID)
require.Zero(t, row.StorageSize)
cleanupCalls := f.graph.calls
var tenant types.Tenant
require.NoError(t, f.db.First(&tenant, 7).Error)
require.Zero(t, tenant.StorageUsed)
// A parser may already have written manual metadata before the move's ack.
meta, err := row.ManualMetadata()
require.NoError(t, err)
require.NoError(t, row.SetManualMetadata(meta))
require.NoError(t, f.repo.UpdateKnowledge(f.ctx, row))
queue.fail = false
require.NoError(t, f.svc.ProcessKnowledgeMove(context.Background(), task))
require.Equal(t, cleanupCalls, f.graph.calls)
require.Len(t, queue.ids, 2)
require.Equal(t, queue.ids[0], queue.ids[1])
require.NoError(t, f.db.First(&tenant, 7).Error)
require.Zero(t, tenant.StorageUsed)
row, err = f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
state, err := transferState(row)
require.NoError(t, err)
require.Equal(t, "done", state.Phase)
}
type cloneFaultChunks struct {
interfaces.ChunkRepository
fail bool
}
func (r *cloneFaultChunks) CreateChunks(ctx context.Context, chunks []*types.Chunk) error {
if err := r.ChunkRepository.CreateChunks(ctx, chunks); err != nil {
return err
}
if r.fail {
return errors.New("lost clone acknowledgement")
}
return nil
}
func TestCloneRetryReplacesIncompleteCopyWithoutDuplicatingEmptyHashes(t *testing.T) {
f := transferFixture(t, access.KBTransferClone)
fault := &cloneFaultChunks{ChunkRepository: f.chunkRepo, fail: true}
f.svc.chunkRepo = fault
require.ErrorContains(
t,
f.svc.executeKnowledgeClone(f.ctx, f.kbs.values["kb"], f.kbs.values["other"], nil),
"lost clone acknowledgement",
)
rows, err := f.repo.ListKnowledgeByKnowledgeBaseID(f.ctx, 7, "other")
require.NoError(t, err)
require.Len(t, rows, 1)
require.Equal(t, types.ParseStatusFailed, rows[0].ParseStatus)
failedChunks, chunkErr := f.chunkRepo.ListAllChunksByKnowledgeID(f.ctx, 7, rows[0].ID)
require.NoError(t, chunkErr)
require.Empty(t, failedChunks, "a lost create acknowledgement must also be rolled back")
fault.fail = false
require.NoError(t, f.svc.executeKnowledgeClone(f.ctx, f.kbs.values["kb"], f.kbs.values["other"], nil))
rows, err = f.repo.ListKnowledgeByKnowledgeBaseID(f.ctx, 7, "other")
require.NoError(t, err)
require.Len(t, rows, 1)
require.Equal(t, types.ParseStatusCompleted, rows[0].ParseStatus)
id := rows[0].ID
require.NoError(t, f.svc.executeKnowledgeClone(f.ctx, f.kbs.values["kb"], f.kbs.values["other"], nil))
rows, err = f.repo.ListKnowledgeByKnowledgeBaseID(f.ctx, 7, "other")
require.NoError(t, err)
require.Len(t, rows, 1)
require.Equal(t, id, rows[0].ID)
var tenant types.Tenant
require.NoError(t, f.db.First(&tenant, 7).Error)
require.EqualValues(t, 10, tenant.StorageUsed)
}
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
func TestCloneCopiesDocumentProfile(t *testing.T) {
f := transferFixture(t, access.KBTransferClone)
profile := types.KnowledgeProfile{
Gist: "Cluster setup guide", Topics: []string{"Kubernetes", "Networking"},
DocType: "user manual", TypicalQuestion: "How do I set up a cluster?",
}
require.NoError(t, f.db.Model(&types.Knowledge{}).Where("id = ?", "doc").Update("profile", profile).Error)
require.NoError(t, f.svc.executeKnowledgeClone(f.ctx, f.kbs.values["kb"], f.kbs.values["other"], nil))
rows, err := f.repo.ListKnowledgeByKnowledgeBaseID(f.ctx, 7, "other")
require.NoError(t, err)
require.Len(t, rows, 1)
require.NotNil(t, rows[0].Profile,
"the clone must carry the document profile so the target's description can be derived")
require.Equal(t, profile, *rows[0].Profile)
}
func TestClonePreflightDoesNotDeleteTargetForUnreadySource(t *testing.T) {
f := transferFixture(t, access.KBTransferClone)
require.NoError(
t,
f.db.Model(&types.Knowledge{}).Where("id = ?", "doc").Update("parse_status", types.ParseStatusProcessing).Error,
)
require.Error(t, f.svc.executeKnowledgeClone(f.ctx, f.kbs.values["kb"], f.kbs.values["other"], nil))
_, err := f.repo.GetKnowledgeByID(f.ctx, 7, "other-doc")
require.NoError(t, err)
require.Zero(t, f.repo.writes)
require.Zero(t, f.chunkRepo.writes)
}
func TestTransferCheckpointCannotResurrectOrOverwriteChangedDocument(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
before, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
after := *before
after.StorageSize = 0
after.KnowledgeBaseID = "other"
require.NoError(t, f.db.Model(&types.Knowledge{}).Where("id = ?", "doc").Update("knowledge_base_id", "third").Error)
require.Error(t, f.repo.UpdateKnowledgeForTransfer(f.ctx, before, &after))
var tenant types.Tenant
require.NoError(t, f.db.First(&tenant, 7).Error)
require.EqualValues(t, 5, tenant.StorageUsed)
require.NoError(t, f.db.Where("id = ?", "doc").Delete(&types.Knowledge{}).Error)
require.Error(t, f.repo.UpdateKnowledgeForTransfer(f.ctx, before, &after))
_, err = f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.Error(t, err)
}
func TestProcessingTasksRejectOldKnowledgeBaseAfterMove(t *testing.T) {
for _, taskType := range []string{types.TypeDocumentProcess, types.TypeManualProcess} {
t.Run(taskType, func(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
require.NoError(
t,
f.db.Model(&types.Knowledge{}).
Where("id = ?", "doc").
Updates(map[string]any{"knowledge_base_id": "other", "parse_status": types.ParseStatusPending}).
Error,
)
payload, err := json.Marshal(
types.DocumentProcessPayload{TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb"},
)
require.NoError(t, err)
task := asynq.NewTask(taskType, payload)
if taskType == types.TypeDocumentProcess {
err = f.svc.ProcessDocument(context.Background(), task)
} else {
err = f.svc.ProcessManualUpdate(context.Background(), task)
}
require.ErrorIs(t, err, asynq.SkipRetry)
require.Zero(t, f.repo.writes)
require.Zero(t, f.graph.calls)
})
}
}
func TestCopyServiceResumesReservedTargetAndRequiresTransferGrant(t *testing.T) {
repo := newFakeKBRepo()
repo.rows["src"] = &types.KnowledgeBase{ID: "src", TenantID: 1}
svc := newPR3KBService(repo, &fakeRegistry{}, &fakeOwnership{})
_, _, err := svc.CopyKnowledgeBase(ctxWithTenant(1), "src", "")
require.ErrorIs(t, err, access.ErrForbidden)
require.Len(t, repo.rows, 1)
ctx, err := access.WithKBTransferTask(
context.Background(),
repo.rows["src"],
&types.KnowledgeBase{ID: "reserved", TenantID: 1, CreatorID: "creator"},
1,
access.KBTransferClone,
"task",
true,
)
require.NoError(t, err)
for range 2 {
_, target, err := svc.CopyKnowledgeBase(ctx, "src", "reserved")
require.NoError(t, err)
require.Equal(t, "reserved", target.ID)
require.Equal(t, "creator", target.CreatorID)
}
require.Len(t, repo.rows, 2)
_, _, err = svc.CopyKnowledgeBase(ctx, "src", "other")
require.ErrorIs(t, err, access.ErrForbidden)
}
func TestProcessingCannotEnterClaimedMoveBeforeKBBindingChanges(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
row, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.NoError(
t,
setTransferState(
row,
knowledgeTransferState{
TaskID: "transfer-task",
Operation: access.KBTransferMove,
SourceKB: "kb",
TargetKB: "other",
SourceID: "doc",
Mode: "reuse_vectors",
Phase: "moving",
},
),
)
row.ParseStatus = types.ParseStatusProcessing
require.NoError(t, f.repo.UpdateKnowledge(f.ctx, row))
f.repo.writes = 0
payload, err := json.Marshal(types.DocumentProcessPayload{TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb"})
require.NoError(t, err)
require.ErrorIs(
t,
f.svc.ProcessDocument(context.Background(), asynq.NewTask(types.TypeDocumentProcess, payload)),
asynq.SkipRetry,
)
require.Zero(t, f.repo.writes)
require.Zero(t, f.graph.calls)
}
func TestAdmissionProgressCannotOverwriteFinishedWorker(t *testing.T) {
f := transferFixture(t, access.KBTransferMove)
require.NoError(
t,
f.svc.saveKnowledgeMoveProgress(
f.ctx,
&types.KnowledgeMoveProgress{TaskID: "task", Status: types.KBCloneStatusCompleted, Progress: 100},
),
)
require.NoError(
t,
f.svc.SaveKnowledgeMoveProgress(
f.ctx,
&types.KnowledgeMoveProgress{TaskID: "task", Status: types.KBCloneStatusPending},
),
)
progress, err := f.svc.GetKnowledgeMoveProgress(f.ctx, "task")
require.NoError(t, err)
require.Equal(t, types.KBCloneStatusCompleted, progress.Status)
require.Equal(t, 100, progress.Progress)
}
func TestClonePreservesFailedChunkIndexStatus(t *testing.T) {
f := transferFixture(t, access.KBTransferClone)
require.NoError(t, f.db.Exec(`CREATE TRIGGER truncate_clone_created_time AFTER INSERT ON knowledges
BEGIN UPDATE knowledges SET updated_at = strftime('%Y-%m-%d %H:%M:%S', NEW.updated_at) || '+00:00'
WHERE id = NEW.id; END`).Error)
require.NoError(t, f.db.Model(&types.Chunk{}).Where("id = ?", "chunk").Update("index_status", "failed").Error)
require.NoError(t, f.svc.executeKnowledgeClone(f.ctx, f.kbs.values["kb"], f.kbs.values["other"], nil))
rows, err := f.repo.ListKnowledgeByKnowledgeBaseID(f.ctx, 7, "other")
require.NoError(t, err)
require.Len(t, rows, 1)
chunks, err := f.chunkRepo.ListAllChunksByKnowledgeID(f.ctx, 7, rows[0].ID)
require.NoError(t, err)
require.Len(t, chunks, 1)
require.Equal(t, "failed", chunks[0].IndexStatus)
}
func TestTableSummaryCleanupDoesNotFollowMovedDocument(t *testing.T) {
f := newDocumentWriteFixture(t)
row, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
chunk, err := f.chunkRepo.GetChunkByID(f.ctx, 7, "chunk")
require.NoError(t, err)
require.NoError(t, f.db.Model(&types.Knowledge{}).Where("id = ?", "doc").Update("knowledge_base_id", "other").Error)
worker := &DataTableSummaryService{knowledgeService: f.svc, chunkService: f.chunks}
worker.cleanupOnFailure(
f.ctx, &extractionResources{knowledge: row}, []*types.Chunk{chunk}, errors.New("index failed"),
)
f.requireNoWrites(t)
current, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.Equal(t, "other", current.KnowledgeBaseID)
require.Equal(t, row.ParseStatus, current.ParseStatus)
}
feat: index and recall images with multimodal embedding models (#3683) * feat(models): expose embedding input modalities Whether an embedding model maps images into the same space as text is what will decide if a knowledge base can store image vectors. The catalog already had the field, but most multimodal embedding models were missing it and embedding rows never reported it. - Catalog: declare input modalities for the Doubao and Tongyi vision embeddings, the Aliyun multimodal / qwen-vl embedding families and jina-embeddings-v4, as listed in each vendor's documentation. The migration baseline changes for exactly these nine entries. - Model responses resolve capabilities for embedding rows too, so capabilities.input reflects the catalog merged with spec.input. - Model editor: an "Image input" switch for embedding models. It follows the catalog and writes spec.input only when the row differs from it; picking another catalog model or switching vendor drops the declaration. Model cards show the image badge for such models. * feat(embedding): embed images with multimodal embedding models Adds the image side of an embedder, for models that map images into the same space as their text vectors so a text query can find an image. - api: EmbedImage (bytes + MIME type, sent inline as base64 because the object store is usually unreachable from the vendor) and an ImageEmbedder implemented by all four protocols, each in the image shape its reference documents: Ark image_url, DashScope contents[].image, Gemini inlineData parts, and on the OpenAI shape an object keyed by the vendor's image_field (Jina: "image"). A plain OpenAI-compatible endpoint names no image field and takes no images. - Settings: image_field, max_image_batch_size (default one per request), max_image_bytes and image_mime_types, filled from vendor docs for the DashScope multimodal models, gemini-embedding-2 and Jina. - embedding: an optional ImageEmbedder interface reached through AsImageEmbedder, so existing Embedder implementations and fakes are untouched. An embedder takes images only when the catalog (or the row's spec.input) lists image AND the endpoint can carry one. Images are checked against the documented limits before any request, then split at the documented images per request. The concurrency, debug and Langfuse decorators forward it; logs and traces carry the MIME type and size, never the bytes. The migration baseline changes only for the entries whose resolved embedding settings now carry image limits. * feat(knowledge): index images by their own vector and recall them When the knowledge base's embedding model embeds images, each image now gets a vector of its own next to its caption and OCR chunks, so a query can find an image by what it shows even where the caption left it out. Ingestion - After the caption/OCR chunks are indexed, the multimodal task embeds the image (embedding.PrepareImage converts and shrinks it to the vendor's documented limits) and stores it as a new image_vector chunk: Content is the caption (OCR text when there is none) for reranking and the answer context; its index row carries the image's vector with SourceType ImageSourceType. Scanned PDF pages are skipped, their OCR text serves better. A failure here is logged and never fails the task. - The image vector gets its own chunk rather than a second index row on the caption chunk: OpenSearch and Weaviate key documents by ChunkID, so a second row would overwrite the caption's text vector, and copy, move and enable/disable all follow chunk IDs. - CompositeRetrieveEngine.BatchIndexVectors writes precomputed vectors through each engine's normal BatchIndex, keeping row order (the composite's de-duplication does not). - Paths that rebuild vectors from text leave image_vector alone: syncChunkIndex only syncs its enabled flag, updateChunkVector skips it, and a caption edit updates its Content only. - The multimodal task's caption/OCR index rows now set IsEnabled; only backends with a column default were storing them as enabled. Retrieval - A text query scores lower against an image than against text, so when the model embeds images the document vector search is widened by half (capped at 500) and run at min(VectorThreshold, 0.1); each store group's hits are then held to their own threshold before score normalization: text at VectorThreshold, images at min(VectorThreshold, 0.1). Keyword hits on image rows are dropped, their Content being the already-indexed caption. - image_vector hits are searchable and merge like caption hits: parent context is attached, and the caption is not repeated from ImageInfo. Adds golang.org/x/image for scaling and WebP/BMP decoding. * fix(models): report no thinking levels for embedding, rerank and ASR models Embedding rows now carry capabilities, and the end-to-end run showed them listing off/auto/minimal/low/medium/high: these references resolve no chat protocol, and an empty level map reads as "every level supported". A model without a chat protocol does not think, so its capabilities say so. * fix(compaction): never read a cancelled turn's stream as a summary streamSummary selects on the turn's context and the provider stream at once. When the turn is already cancelled both are ready (providers close the stream once their context ends), and select picks at random, so a stopped turn could come back as a completed, partial summary with a nil error. TestSummarizationIsNotRetriedOnceTheTurnIsCancelled caught it intermittently in CI and reproduces under -race with several -cpu values. Check the context before each receive and again when the stream closes. * feat(knowledge): put image vectors behind a knowledge-base switch, off by default Image vector indexing and recall used to turn on whenever the knowledge base's embedding model declared image input. A model that takes images is often chosen for text alone, so an upgrade would have added an embedding call per image, widened vector recall 1.5x and lowered the image threshold to 0.1 for those knowledge bases without anyone asking. ImageProcessingConfig gains image_vector_enabled (default false; stored JSON without the key reads as off, so existing knowledge bases stay off with no migration). Both sides now need the switch and the model: - indexImageVector returns before touching the model unless the KB opted in (KnowledgeBase.IsImageVectorEnabled, which also needs vector indexing). - applyImageRecall resolves the embedding model only when some KB in the search opted in, and records the opted-in KBs per store group (storeGroup.ImageKBIDs). Only those groups widen the pool and lower the threshold; image hits of any other KB, including ones indexed before the switch was turned off, are dropped. The KB editor shows the switch in the image processing section, with a warning when the selected embedding model does not declare image input; docs describe the switch, its cost and what turning it off does. * fix(knowledge): leave image vectors behind when cloning into a KB that is off CloneChunk copied every chunk of the source document and then CopyIndices for all of them, so copying a document from a knowledge base with image vectors on into one with the switch off (same model and store) still created image_vector chunks and their index rows, bypassing the switch that indexImageVector honours. Image vector chunks are now dropped from the copy when the target has not opted in. Every engine's CopyIndices copies only the rows of chunks in the mapping, so their index rows stay behind too. * fix(search): refill the vector pool past stale image vectors Image hits of a knowledge base whose switch is off were dropped only after the engine had ranked and cut its results at TopK. Image vectors indexed before the switch was turned off could fill that pool and push out valid text hits: with MatchCount 5 the pool is 50, and 50 stale image rows ranked above the text left the search empty. No engine can filter rows by source type (Postgres and SQLite do not even take ExcludeChunkIDs), so the exclusion cannot move into the query. When the document vector pool comes back full and holds stale image rows, that search alone runs again on a pool twice as large, until it holds TopK rows that are not stale, the index runs out, or the pool reaches maxRetrievalPoolSize (at most four extra calls from a pool of 50). The pool is then cut back to TopK such rows, matching an engine-side exclusion unless more than maxRetrievalPoolSize-TopK stale rows rank above the text. * feat(i18n): translate the image vector switch and image input keys into zh-TW The zh-TW locale arrived from main after this branch added five keys: the knowledge base's image vector switch (label, description, unsupported-model warning) and the embedding model's image input flag (label, description). * fix(knowledge): leave image vectors behind when moving into a KB that is off A reuse_vectors move relocates a document's chunks and index rows in place: MoveKnowledgeIndices rebinds the rows by document ID and MoveChunksByKnowledgeID rebinds the chunks. Moving a document from a knowledge base with image vectors on into one with the switch off therefore carried its image_vector chunks and their vectors along, the same bypass the clone path had. When the target has not opted in, the image_vector chunks are now deleted during the move, their index rows first and then the chunks, so a retry finds the chunks again rather than leaving orphaned rows. A target that opted in still receives them unchanged. * fix(retriever): keep image vectors out of keyword-only engines BatchIndexVectors handed image rows to every engine of the composite, including one that serves keyword retrieval alone (Elasticsearch v7 next to a vector store). There the row holds nothing but the image's caption, which the caption's own chunk already indexes, and retrieval discards every keyword hit on it. Image rows now go only to engines that serve vector retrieval. An engine that serves both keeps one row for both kinds, so its keyword search still meets them; the search side handles that. * fix(search): refill the keyword pool past image rows Every engine that serves both kinds of retrieval stores one row per index entry and runs its keyword search over that row's content, so an image vector row, whose content is its caption, is a keyword hit wherever the caption's own chunk is. filterImageHits drops all of them, but only after the engine has cut its ranking at TopK, so they crowded out text and caption hits; a keyword ranking that put the image rows first came back empty. The keyword pool is now refilled the way the vector pool is refilled past stale image vectors: when it came back full and held image rows, the keyword search runs again on a pool twice as large, up to maxRetrievalPoolSize, and is cut back to TopK hits that are kept. Leaving the rows out of the keyword index instead would mean writing them without searchable content (Milvus and Tencent VectorDB derive a BM25 sparse vector from it, and how they take an empty one is unverified) or a source-type filter in every engine's keyword query (ten engines, and filterable fields that existing collections lack). * revert: let image vectors move with the document into a KB that is off This reverts commit e259977fe915f7d0bc30c4b02bc7af04da1c8dd4. Deleting the image vector index rows by chunk ID before the move is not reliable: the Weaviate and Elasticsearch v8 delete wrappers ignore partial failures, and OpenSearch rejects more than 1000 IDs with ErrBatchTooLarge. A partial delete followed by the chunk delete leaves index rows whose chunks are gone, which nothing ever cleans up. Without it, the image_vector chunks and their index rows move together with the document. While the target's switch is off they are filtered at query time (the pool refill keeps them from crowding out text), they are removed with the document on delete, reparse or knowledge base delete, both chunks and index rows by knowledge ID, and they become active again if the target turns the switch on. The clone path keeps dropping them, since there the rows are copied rather than moved. * fix(search): keep the image row refill from losing hits it already had refillPool replaced a pool with the answer to each larger search. A refill that answered only in part (RetrieveResult.Error, swallowed into a warning by retainPartialResults, as when some collections of the store did not answer) could hold fewer text rows than the complete smaller pool, or none: 40 stale image rows above 10 text came back from a partial refill as the 40 image rows alone, and the search lost all 10 text hits. A refill that failed outright failed the whole store group, discarding a first round that had succeeded. A refill is now best effort. A failed or incomplete refill search stops the refill and leaves the last complete pool in place, cut back to TopK kept rows as before, so a refill can no longer leave a search worse off than it was without it. Merging the partial answer into the pool was not done: its rows would need deduplicating and its ranking is cut at a different TopK over a different set of collections, while keeping the previous pool is exact. * docs(knowledge): say what happens to image vectors in a KB that is off and what the refill costs The image vector section now says that with the switch off, image vectors that were indexed before it was turned off, or that came along when the document was moved in from a KB that has it on, are kept but filtered at query time, are removed when the document is deleted or reparsed or the KB is deleted, and are recalled again once the switch is turned on; a copy into such a KB leaves them behind. It also states the cost of keeping dropped image rows from crowding text out of the pools: the vector and keyword pools are searched again with TopK doubled up to the 500 candidate cap, which adds queries for store groups that hold such rows, and text can still be missed when more than about 500 candidates are image rows. A failed or partial refill keeps the previous complete pool. * fix(search): log unexpected refill result sets, and describe the refill stop condition precisely
2026-10-08 10:19:53 +00:00
// cloneCopyEngine records the chunk mapping CloneChunk hands to CopyIndices.
type cloneCopyEngine struct {
parentChildRetrieveEngine
copied map[string]string
}
func (e *cloneCopyEngine) Support() []types.RetrieverType {
return []types.RetrieverType{types.VectorRetrieverType, types.KeywordsRetrieverType}
}
func (e *cloneCopyEngine) CopyIndices(
_ context.Context, _ string, _, chunks map[string]string, _ string, _ int, _ string,
) error {
e.copied = chunks
return nil
}
func TestCloneCopiesImageVectorsOnlyIntoKBsThatTakeThem(t *testing.T) {
for _, targetOn := range []bool{false, true} {
t.Run(map[bool]string{false: "target off", true: "target on"}[targetOn], func(t *testing.T) {
t.Setenv("RETRIEVE_DRIVER", "postgres")
f := transferFixture(t, access.KBTransferClone)
require.NoError(t, f.db.Create(&types.Chunk{
ID: "image-vector", TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb",
ChunkType: types.ChunkTypeImageVector, ParentChunkID: "chunk", Content: "caption",
}).Error)
engine := &cloneCopyEngine{}
f.svc.retrieveEngine = parentChildRetrieveRegistry{engine: engine}
f.svc.modelService = parentChildModelService{embedder: parentChildEmbedder{}}
for _, kb := range []*types.KnowledgeBase{f.kbs.values["kb"], f.kbs.values["other"]} {
kb.EmbeddingModelID = "model"
kb.IndexingStrategy.VectorEnabled = true
}
f.kbs.values["kb"].ImageProcessingConfig.ImageVectorEnabled = true
f.kbs.values["other"].ImageProcessingConfig.ImageVectorEnabled = targetOn
src, err := f.repo.GetKnowledgeByID(f.ctx, 7, "doc")
require.NoError(t, err)
require.NoError(t, f.svc.cloneKnowledge(f.ctx, src, f.kbs.values["other"]))
rows, err := f.repo.ListKnowledgeByKnowledgeBaseID(f.ctx, 7, "other")
require.NoError(t, err)
var dst *types.Knowledge
for _, row := range rows {
if row.ID != "other-doc" {
dst = row
}
}
require.NotNil(t, dst)
chunks, err := f.chunkRepo.ListAllChunksByKnowledgeID(f.ctx, 7, dst.ID)
require.NoError(t, err)
var kinds []types.ChunkType
for _, c := range chunks {
kinds = append(kinds, c.ChunkType)
}
require.Contains(t, engine.copied, "chunk")
if targetOn {
require.ElementsMatch(t, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeImageVector}, kinds)
require.Contains(t, engine.copied, "image-vector")
return
}
require.Equal(t, []types.ChunkType{types.ChunkTypeText}, kinds,
"a knowledge base that did not opt in gets no image vector chunk")
require.NotContains(t, engine.copied, "image-vector",
"nor its index row: CopyIndices copies only the rows of mapped chunks")
})
}
}