chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,135 @@
// Package milvus implements the Milvus retrieve engine, including multilingual BM25.
package milvus
import (
"strings"
"unicode"
"github.com/milvus-io/milvus/client/v2/entity"
)
const (
fieldContent = "content"
fieldLanguage = "language"
milvusAnalyzerEnglish = "english"
milvusAnalyzerChinese = "chinese"
milvusAnalyzerDefault = "default"
)
type collectionAnalyzerMode uint8
const (
collectionAnalyzerLegacy collectionAnalyzerMode = iota
collectionAnalyzerMulti
)
func analyzerModeFromSchema(schema *entity.Schema) collectionAnalyzerMode {
if schema == nil {
return collectionAnalyzerLegacy
}
hasLanguageField := false
hasMultiAnalyzer := false
for _, field := range schema.Fields {
if field == nil {
continue
}
if field.Name == fieldLanguage {
hasLanguageField = true
}
if field.Name == fieldContent && field.TypeParams != nil &&
field.TypeParams["multi_analyzer_params"] != "" {
hasMultiAnalyzer = true
}
}
if hasLanguageField && hasMultiAnalyzer {
return collectionAnalyzerMulti
}
return collectionAnalyzerLegacy
}
// multiAnalyzerParams returns the analyzer configuration used by new Milvus
// collections. The language field on each row selects the analyzer used for
// that row.
func multiAnalyzerParams() map[string]any {
return map[string]any{
"analyzers": map[string]any{
milvusAnalyzerEnglish: map[string]string{
"type": milvusAnalyzerEnglish,
},
milvusAnalyzerChinese: map[string]string{
"type": milvusAnalyzerChinese,
},
milvusAnalyzerDefault: map[string]string{
"tokenizer": "icu",
},
},
"by_field": fieldLanguage,
"alias": map[string]string{
"en": milvusAnalyzerEnglish,
"zh": milvusAnalyzerChinese,
},
}
}
// detectAnalyzerName selects an analyzer for a document or query. Mixed or
// unsupported-language text uses ICU as a safe fallback because Milvus uses
// one analyzer name per document and per query.
func detectAnalyzerName(text string) string {
var hanCount, latinCount int
hasJapaneseKana := false
hasHangul := false
for _, r := range text {
switch {
case unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r):
hasJapaneseKana = true
case unicode.Is(unicode.Hangul, r):
hasHangul = true
case unicode.Is(unicode.Han, r):
hanCount++
case r <= unicode.MaxASCII && ((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')):
latinCount++
}
}
// Jieba does not preserve Japanese or Korean word boundaries. Route those
// scripts to ICU instead of treating shared Han characters as Chinese.
if hasJapaneseKana || hasHangul {
return milvusAnalyzerDefault
}
// Any remaining Han character makes the text Chinese-oriented. This is
// important for technical queries such as "AI 注意力": choosing English just
// because ASCII characters are more numerous would drop the Chinese terms.
if hanCount > 0 {
return milvusAnalyzerChinese
}
if latinCount > 0 {
return milvusAnalyzerEnglish
}
return milvusAnalyzerDefault
}
func analyzerNameForUpsert(embedding *MilvusVectorEmbedding) string {
if embedding == nil {
return milvusAnalyzerDefault
}
if strings.TrimSpace(embedding.Language) == "" {
return detectAnalyzerName(embedding.Content)
}
return normalizeAnalyzerName(embedding.Language)
}
// normalizeAnalyzerName keeps externally supplied values within the analyzer
// names defined by multiAnalyzerParams.
func normalizeAnalyzerName(name string) string {
switch strings.ToLower(strings.TrimSpace(name)) {
case milvusAnalyzerEnglish, "en":
return milvusAnalyzerEnglish
case milvusAnalyzerChinese, "zh":
return milvusAnalyzerChinese
default:
return milvusAnalyzerDefault
}
}
@@ -0,0 +1,86 @@
package milvus
import (
"testing"
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/stretchr/testify/require"
)
func TestDetectAnalyzerName(t *testing.T) {
tests := []struct {
name string
text string
want string
}{
{
name: "Chinese",
text: "Transformer中多头注意力的三种使用方式及解码器自注意力掩码原因",
want: milvusAnalyzerChinese,
},
{name: "English", text: "How does multi-head attention work", want: milvusAnalyzerEnglish},
{name: "ChineseWithTechnicalTerm", text: "AI 注意力", want: milvusAnalyzerChinese},
{name: "JapaneseKanjiWithKana", text: "東京都の設定", want: milvusAnalyzerDefault},
{name: "KoreanHangul", text: "서울 설정", want: milvusAnalyzerDefault},
{name: "Symbols", text: "12345 --", want: milvusAnalyzerDefault},
{name: "Empty", text: "", want: milvusAnalyzerDefault},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, detectAnalyzerName(tt.text))
})
}
}
func TestMultiAnalyzerParams(t *testing.T) {
params := multiAnalyzerParams()
require.Equal(t, fieldLanguage, params["by_field"])
require.Equal(t, map[string]string{
"type": milvusAnalyzerEnglish,
}, params["analyzers"].(map[string]any)[milvusAnalyzerEnglish])
require.Equal(t, map[string]string{
"type": milvusAnalyzerChinese,
}, params["analyzers"].(map[string]any)[milvusAnalyzerChinese])
require.Equal(t, map[string]string{
"tokenizer": "icu",
}, params["analyzers"].(map[string]any)[milvusAnalyzerDefault])
}
func TestNormalizeAnalyzerName(t *testing.T) {
require.Equal(t, milvusAnalyzerEnglish, normalizeAnalyzerName(" EN "))
require.Equal(t, milvusAnalyzerChinese, normalizeAnalyzerName("zh"))
require.Equal(t, milvusAnalyzerDefault, normalizeAnalyzerName("unknown"))
}
func TestAnalyzerNameForUpsert(t *testing.T) {
require.Equal(t, milvusAnalyzerDefault, analyzerNameForUpsert(nil))
require.Equal(t, milvusAnalyzerChinese, analyzerNameForUpsert(&MilvusVectorEmbedding{
Content: "AI 注意力",
}))
require.Equal(t, milvusAnalyzerEnglish, analyzerNameForUpsert(&MilvusVectorEmbedding{
Content: "AI 注意力",
Language: "en",
}))
require.Equal(t, milvusAnalyzerEnglish, analyzerNameForUpsert(&MilvusVectorEmbedding{
Content: "hello",
Language: " ",
}))
}
func TestAnalyzerModeFromSchema(t *testing.T) {
legacySchema := entity.NewSchema().WithField(
entity.NewField().WithName(fieldContent).WithDataType(entity.FieldTypeVarChar),
)
require.Equal(t, collectionAnalyzerLegacy, analyzerModeFromSchema(legacySchema))
multilingualSchema := entity.NewSchema().WithField(
entity.NewField().WithName(fieldContent).
WithDataType(entity.FieldTypeVarChar).
WithMultiAnalyzerParams(multiAnalyzerParams()),
).WithField(
entity.NewField().WithName(fieldLanguage).WithDataType(entity.FieldTypeVarChar),
)
require.Equal(t, collectionAnalyzerMulti, analyzerModeFromSchema(multilingualSchema))
}
@@ -0,0 +1,425 @@
package milvus
import (
"context"
"fmt"
"net"
"slices"
"strconv"
"strings"
"sync"
"testing"
"github.com/milvus-io/milvus-proto/go-api/v2/commonpb"
"github.com/milvus-io/milvus-proto/go-api/v2/milvuspb"
"github.com/milvus-io/milvus-proto/go-api/v2/schemapb"
"github.com/milvus-io/milvus/client/v2/entity"
client "github.com/milvus-io/milvus/client/v2/milvusclient"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
const (
copyTestDim = 3
copyTestSourceKB = "kb-source"
copyTestTargetKB = "kb-target"
copyTestKnowledge = "doc-1"
copyTestTargetDoc = "doc-2"
)
// copyTestRow is one source point. The tests keep a single row per chunk, so
// "the chunk is missing from the target" and "its vector is missing" are the
// same event and can be asserted on the upserted chunk IDs.
type copyTestRow struct {
id string
chunkID string
knowledgeBaseID string
}
// copyTestRead records one Query the copy issued, so a test can see whether the
// traversal depended on an offset cursor.
type copyTestRead struct {
expr string
offset int
limit int
}
// fakeMilvusCopyService is an in-process Milvus endpoint for CopyIndices. The
// repository holds a concrete *client.Client, so a gRPC server is the only seam
// that exercises the real query and upsert path instead of a hand-written stub.
//
// It answers the handful of RPCs CopyIndices needs (describe/load/query/upsert)
// and evaluates the predicates this repository emits: an equality on
// knowledge_base_id and an optional "in" list on chunk_id.
type fakeMilvusCopyService struct {
milvuspb.UnimplementedMilvusServiceServer
mu sync.Mutex
// rows is the stored collection content.
rows []copyTestRow
// drift rotates the reported result order, see matchingRows.
drift int
// reads and upserted are the observations the tests assert on.
reads []copyTestRead
upserted []MilvusVectorEmbedding
}
func (s *fakeMilvusCopyService) DescribeCollection(
_ context.Context, request *milvuspb.DescribeCollectionRequest,
) (*milvuspb.DescribeCollectionResponse, error) {
return &milvuspb.DescribeCollectionResponse{
Status: &commonpb.Status{},
CollectionID: 1,
ShardsNum: 1,
Schema: &schemapb.CollectionSchema{
Name: request.GetCollectionName(),
Fields: []*schemapb.FieldSchema{
{FieldID: 100, Name: fieldID, DataType: schemapb.DataType_VarChar, IsPrimaryKey: true},
{
FieldID: 101,
Name: fieldEmbedding,
DataType: schemapb.DataType_FloatVector,
TypeParams: []*commonpb.KeyValuePair{
{Key: "dim", Value: strconv.Itoa(copyTestDim)},
},
},
{FieldID: 102, Name: fieldContent, DataType: schemapb.DataType_VarChar},
{FieldID: 103, Name: fieldSourceID, DataType: schemapb.DataType_VarChar},
{FieldID: 104, Name: fieldSourceType, DataType: schemapb.DataType_Int64},
{FieldID: 105, Name: fieldChunkID, DataType: schemapb.DataType_VarChar},
{FieldID: 106, Name: fieldKnowledgeID, DataType: schemapb.DataType_VarChar},
{FieldID: 107, Name: fieldKnowledgeBaseID, DataType: schemapb.DataType_VarChar},
{FieldID: 108, Name: fieldTagID, DataType: schemapb.DataType_VarChar},
{FieldID: 109, Name: fieldIsEnabled, DataType: schemapb.DataType_Bool},
},
},
}, nil
}
func (s *fakeMilvusCopyService) LoadCollection(
_ context.Context, _ *milvuspb.LoadCollectionRequest,
) (*commonpb.Status, error) {
return &commonpb.Status{}, nil
}
func (s *fakeMilvusCopyService) GetLoadingProgress(
_ context.Context, _ *milvuspb.GetLoadingProgressRequest,
) (*milvuspb.GetLoadingProgressResponse, error) {
return &milvuspb.GetLoadingProgressResponse{
Status: &commonpb.Status{},
Progress: 100,
RefreshProgress: 100,
}, nil
}
func (s *fakeMilvusCopyService) Query(
_ context.Context, request *milvuspb.QueryRequest,
) (*milvuspb.QueryResults, error) {
s.mu.Lock()
defer s.mu.Unlock()
offset, limit := 0, -1
for _, param := range request.GetQueryParams() {
switch param.GetKey() {
case "offset":
offset, _ = strconv.Atoi(param.GetValue())
case "limit":
limit, _ = strconv.Atoi(param.GetValue())
}
}
s.reads = append(s.reads, copyTestRead{expr: request.GetExpr(), offset: offset, limit: limit})
matched := s.matchingRowsLocked(request)
if offset >= len(matched) {
matched = nil
} else {
matched = matched[offset:]
}
if limit >= 0 && limit < len(matched) {
matched = matched[:limit]
}
return copyTestQueryResponse(matched), nil
}
// matchingRowsLocked evaluates the request predicate over the collection and
// returns the matching rows in the order this backend reports them: a rotation
// of the stored order that advances by one on every acknowledged write.
//
// Milvus does not make the order of a scalar query result part of its API
// contract — results are merged segment by segment, and the segment set changes
// while data is written — and CopyIndices writes into the collection it reads
// from on every page. A client that addresses pages by offset therefore gets a
// moving window even though every single request succeeds: rows can be skipped
// (the page after the cursor starts past them) or repeated. The row set below
// never changes; only the reported order does.
func (s *fakeMilvusCopyService) matchingRowsLocked(request *milvuspb.QueryRequest) []copyTestRow {
if len(s.rows) == 0 {
return nil
}
ordered := make([]copyTestRow, 0, len(s.rows))
for i := range s.rows {
ordered = append(ordered, s.rows[(i+s.drift)%len(s.rows)])
}
var knowledgeBaseID string
var chunkIDs []string
for name, value := range request.GetExprTemplateValues() {
if kb := value.GetStringVal(); kb != "" && strings.HasPrefix(name, fieldKnowledgeBaseID) {
knowledgeBaseID = kb
}
if array := value.GetArrayVal(); array != nil && strings.HasPrefix(name, fieldChunkID) {
chunkIDs = array.GetStringData().GetData()
}
}
matched := make([]copyTestRow, 0, len(ordered))
for _, row := range ordered {
if knowledgeBaseID != "" && row.knowledgeBaseID != knowledgeBaseID {
continue
}
if len(chunkIDs) > 0 && !slices.Contains(chunkIDs, row.chunkID) {
continue
}
matched = append(matched, row)
}
return matched
}
func (s *fakeMilvusCopyService) Upsert(
_ context.Context, request *milvuspb.UpsertRequest,
) (*milvuspb.MutationResult, error) {
s.mu.Lock()
defer s.mu.Unlock()
ids := copyTestStringColumn(request, fieldID)
chunks := copyTestStringColumn(request, fieldChunkID)
knowledgeIDs := copyTestStringColumn(request, fieldKnowledgeID)
knowledgeBaseIDs := copyTestStringColumn(request, fieldKnowledgeBaseID)
for i, id := range ids {
s.upserted = append(s.upserted, MilvusVectorEmbedding{
ID: id,
ChunkID: chunks[i],
KnowledgeID: knowledgeIDs[i],
KnowledgeBaseID: knowledgeBaseIDs[i],
})
}
// The write is what moves the reported result order: it is acknowledged
// here, and the collection is re-read on the next page.
s.drift++
return &milvuspb.MutationResult{
Status: &commonpb.Status{},
UpsertCnt: int64(len(ids)),
IDs: &schemapb.IDs{IdField: &schemapb.IDs_StrId{
StrId: &schemapb.StringArray{Data: ids},
}},
}, nil
}
// copiedChunks returns the sorted chunk IDs of every row written to the target.
func (s *fakeMilvusCopyService) copiedChunks() []string {
s.mu.Lock()
defer s.mu.Unlock()
chunks := make([]string, 0, len(s.upserted))
for _, row := range s.upserted {
chunks = append(chunks, row.ChunkID)
}
slices.Sort(chunks)
return chunks
}
// readOffsets returns the offset of every read, for diagnostics.
func (s *fakeMilvusCopyService) readOffsets() []int {
s.mu.Lock()
defer s.mu.Unlock()
offsets := make([]int, 0, len(s.reads))
for _, read := range s.reads {
offsets = append(offsets, read.offset)
}
return offsets
}
func copyTestStringColumn(request *milvuspb.UpsertRequest, name string) []string {
for _, field := range request.GetFieldsData() {
if field.GetFieldName() != name {
continue
}
return field.GetScalars().GetStringData().GetData()
}
return nil
}
func copyTestQueryResponse(rows []copyTestRow) *milvuspb.QueryResults {
// A real server echoes the requested output fields; the client uses the
// echo to expand the "*" wildcard.
response := &milvuspb.QueryResults{Status: &commonpb.Status{}, OutputFields: []string{"*"}}
if len(rows) == 0 {
return response
}
ids := make([]string, 0, len(rows))
chunks := make([]string, 0, len(rows))
knowledgeIDs := make([]string, 0, len(rows))
knowledgeBases := make([]string, 0, len(rows))
embeddings := make([]float32, 0, len(rows)*copyTestDim)
for i, row := range rows {
ids = append(ids, row.id)
chunks = append(chunks, row.chunkID)
knowledgeIDs = append(knowledgeIDs, copyTestKnowledge)
knowledgeBases = append(knowledgeBases, row.knowledgeBaseID)
embeddings = append(embeddings, float32(i+1), 0, 0)
}
response.FieldsData = []*schemapb.FieldData{
copyTestStringField(fieldID, ids),
copyTestStringField(fieldChunkID, chunks),
copyTestStringField(fieldKnowledgeID, knowledgeIDs),
copyTestStringField(fieldKnowledgeBaseID, knowledgeBases),
copyTestFloatVectorField(embeddings),
}
return response
}
func copyTestStringField(name string, values []string) *schemapb.FieldData {
return &schemapb.FieldData{
Type: schemapb.DataType_VarChar,
FieldName: name,
Field: &schemapb.FieldData_Scalars{Scalars: &schemapb.ScalarField{
Data: &schemapb.ScalarField_StringData{
StringData: &schemapb.StringArray{Data: values},
},
}},
}
}
func copyTestFloatVectorField(values []float32) *schemapb.FieldData {
return &schemapb.FieldData{
Type: schemapb.DataType_FloatVector,
FieldName: fieldEmbedding,
Field: &schemapb.FieldData_Vectors{Vectors: &schemapb.VectorField{
Dim: copyTestDim,
Data: &schemapb.VectorField_FloatVector{
FloatVector: &schemapb.FloatArray{Data: values},
},
}},
}
}
type copyMilvusHarness struct {
repo *milvusRepository
fake *fakeMilvusCopyService
}
func newCopyMilvusHarness(t *testing.T, rows []copyTestRow) *copyMilvusHarness {
t.Helper()
fake := &fakeMilvusCopyService{rows: rows}
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
grpcServer := grpc.NewServer()
milvuspb.RegisterMilvusServiceServer(grpcServer, fake)
go func() { _ = grpcServer.Serve(listener) }()
t.Cleanup(grpcServer.Stop)
// DisableConn skips the Connect handshake, which this fake does not serve.
c, err := client.New(context.Background(), &client.ClientConfig{
Address: listener.Addr().String(),
DisableConn: true,
})
require.NoError(t, err)
t.Cleanup(func() { _ = c.Close(context.Background()) })
return &copyMilvusHarness{
repo: &milvusRepository{
client: c,
collectionBaseName: "academy_embeddings",
metricType: entity.IP,
},
fake: fake,
}
}
func (h *copyMilvusHarness) copy(t *testing.T, sourceToTargetChunkIDMap map[string]string) error {
t.Helper()
return h.repo.CopyIndices(context.Background(), copyTestSourceKB,
map[string]string{copyTestKnowledge: copyTestTargetDoc},
sourceToTargetChunkIDMap, copyTestTargetKB, copyTestDim, "manual",
)
}
// CopyIndices must put every mapped source chunk into the target exactly once,
// no matter how the backend orders the rows of the queries it serves. A page
// cursor that is an offset into that order can slide between requests while
// every request still succeeds, which drops the vectors the cursor skipped and
// re-copies the ones it slid back over — the copy still reports success, so the
// loss is only visible as worse recall in the cloned knowledge base.
func TestCopyIndicesCopiesEveryMappedChunkWhenResultOrderDrifts(t *testing.T) {
const rowCount = 200
rows := make([]copyTestRow, 0, rowCount)
mapping := make(map[string]string, rowCount)
expected := make([]string, 0, rowCount)
for i := range rowCount {
chunkID := fmt.Sprintf("chunk-%03d", i)
rows = append(rows, copyTestRow{
id: fmt.Sprintf("point-%03d", i),
chunkID: chunkID,
knowledgeBaseID: copyTestSourceKB,
})
mapping[chunkID] = "target-" + chunkID
expected = append(expected, mapping[chunkID])
}
slices.Sort(expected)
harness := newCopyMilvusHarness(t, rows)
err := harness.copy(t, mapping)
require.NoError(t, err, "the copy must not report success while dropping vectors")
copied := harness.fake.copiedChunks()
missing, repeated := copyTestDiff(expected, copied)
t.Logf("reads=%d offsets=%v copied=%d missing=%v repeated=%v",
len(harness.fake.reads), harness.fake.readOffsets(), len(copied), missing, repeated)
require.Len(t, copied, rowCount, "one target row per mapped source chunk")
require.Empty(t, missing, "source chunks whose vectors never reached the target")
require.Empty(t, repeated, "source chunks copied more than once")
}
// Source chunks outside the mapping are not part of the copy: the mapping names
// the chunks the caller cloned, and only those may appear in the target.
func TestCopyIndicesIgnoresSourceChunksOutsideTheMapping(t *testing.T) {
harness := newCopyMilvusHarness(t, []copyTestRow{
{id: "point-a", chunkID: "chunk-a", knowledgeBaseID: copyTestSourceKB},
{id: "point-b", chunkID: "chunk-b", knowledgeBaseID: copyTestSourceKB},
{id: "point-c", chunkID: "chunk-c", knowledgeBaseID: copyTestSourceKB},
})
err := harness.copy(t, map[string]string{"chunk-a": "target-a", "chunk-c": "target-c"})
require.NoError(t, err)
require.Equal(t, []string{"target-a", "target-c"}, harness.fake.copiedChunks())
}
// copyTestDiff returns the entries of want that are absent from got and the
// entries of got that appear more often than in want.
func copyTestDiff(want, got []string) (missing, repeated []string) {
remaining := make(map[string]int, len(want))
for _, value := range want {
remaining[value]++
}
for _, value := range got {
remaining[value]--
}
for value, count := range remaining {
switch {
case count > 0:
missing = append(missing, value)
case count < 0:
repeated = append(repeated, value)
}
}
slices.Sort(missing)
slices.Sort(repeated)
return missing, repeated
}
@@ -0,0 +1,276 @@
package milvus
import (
"encoding/json"
"fmt"
"maps"
"reflect"
"strings"
)
const (
// operatorAnd is the "and" operator.
operatorAnd = "and"
// operatorOr is the "or" operator.
operatorOr = "or"
// operatorEqual is the "equal" operator.
operatorEqual = "eq"
// operatorNotEqual is the "not equal" operator.
operatorNotEqual = "ne"
// operatorGreaterThan is the "greater than" operator.
operatorGreaterThan = "gt"
// operatorGreaterThanOrEqual is the "greater than or equal" operator.
operatorGreaterThanOrEqual = "gte"
// operatorLessThan is the "less than" operator.
operatorLessThan = "lt"
// operatorLessThanOrEqual is the "less than or equal" operator.
operatorLessThanOrEqual = "lte"
// operatorIn is the "in" operator.
operatorIn = "in"
// operatorNotIn is the "not in" operator.
operatorNotIn = "not in"
// operatorLike is the "contains" operator.
operatorLike = "like"
// operatorNotLike is the "not contains" operator.
operatorNotLike = "not like"
// operatorBetween is the "between" operator.
operatorBetween = "between"
)
var comparisonOperators = map[string]string{
operatorEqual: "==",
operatorNotEqual: "!=",
operatorGreaterThan: ">",
operatorGreaterThanOrEqual: ">=",
operatorLessThan: "<",
operatorLessThanOrEqual: "<=",
operatorLike: "like",
operatorNotLike: "not like",
}
type convertResult struct {
exprStr string
params map[string]any
}
type filter struct{}
func (c *filter) Convert(cond *universalFilterCondition) (*convertResult, error) {
var counter int
return c.convertCondition(cond, &counter)
}
func (c *filter) convertComparisonCondition(
cond *universalFilterCondition,
counter *int,
) (*convertResult, error) {
condField := cond.Field
if condField == "" || cond.Value == nil {
return nil, fmt.Errorf("milvus filter condition is nil")
}
operator, ok := comparisonOperators[cond.Operator]
if !ok {
return nil, fmt.Errorf("unsupported comparison operator: %s", cond.Operator)
}
paramName := c.convertParamName(cond.Field, counter)
return &convertResult{
exprStr: fmt.Sprintf("%s %s {%s}", condField, operator, paramName),
params: map[string]any{paramName: cond.Value},
}, nil
}
func (c *filter) convertLogicalCondition(
cond *universalFilterCondition,
counter *int,
) (*convertResult, error) {
if cond.Value == nil {
return nil, fmt.Errorf("milvus filter condition is nil")
}
conds, ok := cond.Value.([]*universalFilterCondition)
if !ok {
return nil, fmt.Errorf("invalid logical condition value type")
}
var condResult *convertResult
for _, childCond := range conds {
childRes, err := c.convertCondition(childCond, counter)
if err != nil {
return nil, err
}
if childRes == nil || childRes.exprStr == "" {
continue
}
if condResult == nil {
condResult = childRes
continue
}
condResult.exprStr = fmt.Sprintf(
"(%s) %s (%s)",
condResult.exprStr,
strings.ToLower(cond.Operator),
childRes.exprStr,
)
maps.Copy(condResult.params, childRes.params)
}
if condResult == nil {
return nil, fmt.Errorf("empty logical condition")
}
return condResult, nil
}
func (c *filter) convertCondition(
cond *universalFilterCondition,
counter *int,
) (*convertResult, error) {
if cond == nil {
return nil, fmt.Errorf("milvus filter condition is nil")
}
switch cond.Operator {
case operatorEqual, operatorNotEqual, operatorGreaterThan,
operatorGreaterThanOrEqual, operatorLessThan,
operatorLessThanOrEqual, operatorLike, operatorNotLike:
return c.convertComparisonCondition(cond, counter)
case operatorAnd, operatorOr:
return c.convertLogicalCondition(cond, counter)
case operatorIn, operatorNotIn:
return c.convertInCondition(cond, counter)
case operatorBetween:
return c.convertBetweenCondition(cond, counter)
default:
return nil, fmt.Errorf("unsupported operator: %v", cond.Operator)
}
}
func (c *filter) convertInCondition(
cond *universalFilterCondition,
counter *int,
) (*convertResult, error) {
condField := cond.Field
if condField == "" || cond.Value == nil {
return nil, fmt.Errorf("milvus filter condition is nil")
}
s := reflect.ValueOf(cond.Value)
if s.Kind() != reflect.Slice || s.Len() <= 0 {
return nil, fmt.Errorf("in operator value must be a slice with at least one value: %v", cond.Value)
}
paramName := c.convertParamName(cond.Field, counter)
return &convertResult{
exprStr: fmt.Sprintf("%s %s {%s}", condField, strings.ToLower(cond.Operator), paramName),
params: map[string]any{paramName: cond.Value},
}, nil
}
func (c *filter) convertBetweenCondition(
cond *universalFilterCondition,
counter *int,
) (*convertResult, error) {
condField := cond.Field
if condField == "" || cond.Value == nil {
return nil, fmt.Errorf("milvus filter condition is nil")
}
value := reflect.ValueOf(cond.Value)
if value.Kind() != reflect.Slice || value.Len() != 2 {
return nil, fmt.Errorf("between operator value must be a slice with two elements: %v", cond.Value)
}
paramBase := c.convertParamName(cond.Field, counter)
paramName1 := fmt.Sprintf("%s_%d", paramBase, 0)
paramName2 := fmt.Sprintf("%s_%d", paramBase, 1)
return &convertResult{
exprStr: fmt.Sprintf("%s >= {%s} and %s <= {%s}", condField, paramName1, condField, paramName2),
params: map[string]any{
paramName1: value.Index(0).Interface(),
paramName2: value.Index(1).Interface(),
},
}, nil
}
// convertParamName converts field name to a valid Milvus template parameter name.
// Milvus template parameters don't support '.' character, so we replace it with '_'.
func (c *filter) convertParamName(field string, counter *int) string {
*counter++
return fmt.Sprintf("%s_%d", strings.ReplaceAll(field, ".", "_"), *counter)
}
type universalFilterCondition struct {
Field string `json:"field,omitempty" jsonschema:"description=The metadata field to filter on (required for comparison operators)"`
Operator string `json:"operator" jsonschema:"description=The operator to use,enum=eq,enum=ne,enum=gt,enum=gte,enum=lt,enum=lte,enum=in,enum=not in,enum=like,enum=not like,enum=between,enum=and,enum=or"`
Value any `json:"value,omitempty" jsonschema:"description=The value to compare against (for comparison operators) or array of sub-conditions (for logical operators and/or)"`
}
func (c *universalFilterCondition) UnmarshalJSON(data []byte) error {
type Alias struct {
Field string `json:"field,omitempty"`
Operator string `json:"operator"`
Value any `json:"value,omitempty"`
}
var aux Alias
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
c.Field = aux.Field
c.Operator = strings.ToLower(aux.Operator)
// Handle logical operators (and/or) - Value should be []*UniversalFilterCondition
if c.Operator == operatorAnd || c.Operator == operatorOr {
// Value can be an array of conditions
valueSlice, ok := aux.Value.([]any)
if !ok {
return fmt.Errorf("logical operator %s requires an array of conditions", c.Operator)
}
conditions := make([]*universalFilterCondition, 0, len(valueSlice))
for i, v := range valueSlice {
condBytes, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("failed to marshal condition at index %d: %w", i, err)
}
var cond universalFilterCondition
if err := json.Unmarshal(condBytes, &cond); err != nil {
return fmt.Errorf("failed to unmarshal condition at index %d: %w", i, err)
}
conditions = append(conditions, &cond)
}
c.Value = conditions
} else {
c.Value = aux.Value
}
return nil
}
// MarshalJSON implements custom JSON marshaling for UniversalFilterCondition.
func (c *universalFilterCondition) MarshalJSON() ([]byte, error) {
type Alias struct {
Field string `json:"field,omitempty"`
Operator string `json:"operator"`
Value any `json:"value,omitempty"`
}
return json.Marshal(&Alias{
Field: c.Field,
Operator: c.Operator,
Value: c.Value,
})
}
@@ -0,0 +1,282 @@
package milvus
import (
"bytes"
"context"
"net"
"os"
"testing"
"academy/internal/logger"
"academy/internal/types"
"github.com/milvus-io/milvus-proto/go-api/v2/commonpb"
"github.com/milvus-io/milvus-proto/go-api/v2/milvuspb"
"github.com/milvus-io/milvus-proto/go-api/v2/schemapb"
client "github.com/milvus-io/milvus/client/v2/milvusclient"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
// fakeMilvusService answers the three RPCs KeywordsRetrieve needs. The
// repository holds a concrete *client.Client, so an in-process Milvus endpoint
// is the only seam that exercises the real search path instead of a stub.
type fakeMilvusService struct {
milvuspb.UnimplementedMilvusServiceServer
collections []string
search func(collectionName string) (*milvuspb.SearchResults, error)
searches []string
}
func (s *fakeMilvusService) ShowCollections(
_ context.Context, _ *milvuspb.ShowCollectionsRequest,
) (*milvuspb.ShowCollectionsResponse, error) {
return &milvuspb.ShowCollectionsResponse{
Status: &commonpb.Status{},
CollectionNames: s.collections,
}, nil
}
func (s *fakeMilvusService) DescribeCollection(
_ context.Context, request *milvuspb.DescribeCollectionRequest,
) (*milvuspb.DescribeCollectionResponse, error) {
return &milvuspb.DescribeCollectionResponse{
Status: &commonpb.Status{},
Schema: &schemapb.CollectionSchema{
Name: request.GetCollectionName(),
Fields: []*schemapb.FieldSchema{
{FieldID: 100, Name: fieldID, DataType: schemapb.DataType_VarChar, IsPrimaryKey: true},
{FieldID: 101, Name: fieldContent, DataType: schemapb.DataType_VarChar},
{FieldID: 102, Name: fieldContentSparse, DataType: schemapb.DataType_SparseFloatVector},
},
},
}, nil
}
func (s *fakeMilvusService) Search(
_ context.Context, request *milvuspb.SearchRequest,
) (*milvuspb.SearchResults, error) {
name := request.GetCollectionName()
s.searches = append(s.searches, name)
return s.search(name)
}
type keywordsMilvusHarness struct {
repo *milvusRepository
fake *fakeMilvusService
}
func newKeywordsMilvusHarness(t *testing.T, collections []string,
search func(collectionName string) (*milvuspb.SearchResults, error),
) *keywordsMilvusHarness {
t.Helper()
fake := &fakeMilvusService{collections: collections, search: search}
lis, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
grpcSrv := grpc.NewServer()
milvuspb.RegisterMilvusServiceServer(grpcSrv, fake)
go func() { _ = grpcSrv.Serve(lis) }()
t.Cleanup(grpcSrv.Stop)
// DisableConn skips the Connect handshake, which this fake does not serve.
c, err := client.New(context.Background(), &client.ClientConfig{
Address: lis.Addr().String(),
DisableConn: true,
})
require.NoError(t, err)
t.Cleanup(func() { _ = c.Close(context.Background()) })
return &keywordsMilvusHarness{
repo: &milvusRepository{client: c, collectionBaseName: "academy_embeddings"},
fake: fake,
}
}
func failedMilvusSearch() *milvuspb.SearchResults {
return &milvuspb.SearchResults{Status: &commonpb.Status{
ErrorCode: commonpb.ErrorCode_UnexpectedError,
Reason: "milvus keyword search unavailable",
}}
}
func emptyMilvusSearch() *milvuspb.SearchResults {
return &milvuspb.SearchResults{
Status: &commonpb.Status{},
Results: &schemapb.SearchResultData{
NumQueries: 1,
Topks: []int64{0},
Ids: &schemapb.IDs{IdField: &schemapb.IDs_StrId{StrId: &schemapb.StringArray{}}},
},
}
}
func milvusSearchHits(chunkID, content string) *milvuspb.SearchResults {
return &milvuspb.SearchResults{
Status: &commonpb.Status{},
Results: &schemapb.SearchResultData{
NumQueries: 1,
Topks: []int64{1},
Scores: []float32{0.75},
Ids: &schemapb.IDs{
IdField: &schemapb.IDs_StrId{StrId: &schemapb.StringArray{Data: []string{chunkID}}},
},
FieldsData: []*schemapb.FieldData{
milvusStringField(fieldContent, content),
milvusStringField(fieldChunkID, chunkID),
},
},
}
}
func milvusStringField(name, value string) *schemapb.FieldData {
return &schemapb.FieldData{
Type: schemapb.DataType_VarChar,
FieldName: name,
Field: &schemapb.FieldData_Scalars{Scalars: &schemapb.ScalarField{
Data: &schemapb.ScalarField_StringData{
StringData: &schemapb.StringArray{Data: []string{value}},
},
}},
}
}
func keywordsMilvusParams() types.RetrieveParams {
return types.RetrieveParams{
Query: "invoice total",
TopK: 10,
KnowledgeBaseIDs: []string{"kb-1"},
}
}
// captureMilvusLogs redirects the package logger for one test, so the
// "No keyword matches found" conclusion can be asserted on directly.
func captureMilvusLogs(t *testing.T) *bytes.Buffer {
t.Helper()
var buf bytes.Buffer
logger.SetOutput(&buf)
t.Cleanup(func() { logger.SetOutput(os.Stdout) })
return &buf
}
// A batch in which every matching collection fails must reach the caller as an
// error. Returning an empty result set with a nil error is indistinguishable
// from a genuine zero-hit search, and the QA pipeline answers "no relevant
// content" on top of it (#3835).
func TestMilvusKeywordsRetrieveFailsWhenEveryMatchedCollectionFails(t *testing.T) {
logs := captureMilvusLogs(t)
harness := newKeywordsMilvusHarness(t,
[]string{"academy_embeddings_1024", "academy_embeddings_1536", "other_collection"},
func(string) (*milvuspb.SearchResults, error) { return failedMilvusSearch(), nil },
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())
require.Error(t, err, "all-collections failure must surface as an error")
require.Contains(t, err.Error(), "all 2 matched collections")
require.Contains(t, err.Error(), "milvus keyword search unavailable")
require.Nil(t, results, "no result set may accompany the error")
require.Equal(t,
[]string{"academy_embeddings_1024", "academy_embeddings_1536"}, harness.fake.searches,
"only base-name collections are searched",
)
require.NotContains(t, logs.String(), "No keyword matches found",
"a failed batch must not be logged as a search that found no matches")
}
// One failing collection must not fail the batch as long as another one
// answered: partial results are still results. The failure must travel with
// them though (RetrieveResult.Error) — otherwise callers treat the incomplete
// answer as a complete one (#3835).
func TestMilvusKeywordsRetrieveKeepsResultsWhenOnlySomeCollectionsFail(t *testing.T) {
logs := captureMilvusLogs(t)
harness := newKeywordsMilvusHarness(t,
[]string{"academy_embeddings_1024", "academy_embeddings_1536"},
func(name string) (*milvuspb.SearchResults, error) {
if name == "academy_embeddings_1024" {
return failedMilvusSearch(), nil
}
return milvusSearchHits("chunk-1", "invoice total 42"), nil
},
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())
require.NoError(t, err, "a partially failed batch must not fail the caller")
require.Len(t, results, 1)
require.Error(t, results[0].Error,
"a partially failed batch must mark its result set with the failure")
require.Contains(t, results[0].Error.Error(), "1 of 2 matched collections")
require.Contains(t, results[0].Error.Error(), "milvus keyword search unavailable")
require.Len(t, results[0].Results, 1)
require.Equal(t, "chunk-1", results[0].Results[0].ChunkID)
require.Equal(t, "invoice total 42", results[0].Results[0].Content)
require.Equal(t, 0.75, results[0].Results[0].Score)
require.Equal(t, types.KeywordsRetrieverType, results[0].RetrieverType)
require.NotContains(t, logs.String(), "No keyword matches found",
"a partially failed batch must not be logged as a search that found no matches")
}
// The genuine zero-hit outcome keeps its old shape: every collection answered,
// no token matched, so an empty result with a nil error is correct and the
// conclusion log still fires.
func TestMilvusKeywordsRetrieveReportsNoMatchesWhenNothingFailed(t *testing.T) {
logs := captureMilvusLogs(t)
harness := newKeywordsMilvusHarness(t, []string{"academy_embeddings_1024"},
func(string) (*milvuspb.SearchResults, error) { return emptyMilvusSearch(), nil },
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())
require.NoError(t, err, "a successful search without matches must not error")
require.Len(t, results, 1)
require.Empty(t, results[0].Results)
require.NoError(t, results[0].Error, "a complete zero-hit search must not mark an error")
require.Contains(t, logs.String(), "No keyword matches found",
"a successful zero-hit search must still be logged as such")
}
// A partial failure with zero hits is still a partial failure: the result set
// stays empty but must carry the error, and the conclusion log must stay off.
func TestMilvusKeywordsRetrieveMarksPartialFailureWhenNothingHit(t *testing.T) {
logs := captureMilvusLogs(t)
harness := newKeywordsMilvusHarness(t,
[]string{"academy_embeddings_1024", "academy_embeddings_1536"},
func(name string) (*milvuspb.SearchResults, error) {
if name == "academy_embeddings_1024" {
return failedMilvusSearch(), nil
}
return emptyMilvusSearch(), nil
},
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())
require.NoError(t, err, "a partially failed batch must not fail the caller")
require.Len(t, results, 1)
require.Empty(t, results[0].Results)
require.Error(t, results[0].Error,
"partial failure with zero hits must still be marked")
require.NotContains(t, logs.String(), "No keyword matches found",
"a partially failed batch must not be logged as a search that found no matches")
}
// No collection carries the repository's base name: nothing was searched at
// all, which must be distinguishable from a search that ran and hit nothing.
func TestMilvusKeywordsRetrieveWarnsWhenNoCollectionMatchesBaseName(t *testing.T) {
logs := captureMilvusLogs(t)
harness := newKeywordsMilvusHarness(t, []string{"other_collection"},
func(string) (*milvuspb.SearchResults, error) { return emptyMilvusSearch(), nil },
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsMilvusParams())
require.NoError(t, err, "an empty collection list must not error")
require.Len(t, results, 1)
require.Empty(t, results[0].Results)
require.NoError(t, results[0].Error, "no matching collection is not a partial failure")
require.Empty(t, harness.fake.searches, "no Search may be issued without a matching collection")
require.Contains(t, logs.String(), "No collection matched base name",
"a search that never ran must be logged as such")
require.NotContains(t, logs.String(), "No keyword matches found",
"a search that never ran must not be logged as a search that found no matches")
}
@@ -0,0 +1,452 @@
package milvus
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"sort"
"strconv"
"strings"
"github.com/milvus-io/milvus/client/v2/column"
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/milvus-io/milvus/client/v2/index"
client "github.com/milvus-io/milvus/client/v2/milvusclient"
"academy/internal/logger"
)
const defaultMultilingualMigrationBatchSize = 64
// migrationOutputFields deliberately excludes the generated BM25 sparse
// vector. The migration only needs the source content, dense vector, and
// metadata required to rebuild the target row. Querying "*" can exceed
// Milvus's per-query result-size limit when a batch contains long chunks.
var migrationOutputFields = []string{
fieldID,
fieldContent,
fieldSourceID,
fieldSourceType,
fieldChunkID,
fieldKnowledgeID,
fieldKnowledgeBaseID,
fieldTagID,
fieldIsEnabled,
fieldEmbedding,
}
// MultilingualMigrationOptions describes a safe, copy-only migration from
// legacy Milvus collections to collections with multilingual BM25 analyzers.
// The source collections are never modified or deleted.
type MultilingualMigrationOptions struct {
SourceCollectionBaseName string
TargetCollectionBaseName string
MetricType entity.MetricType
ShardsNum int
ReplicaNumber int
BatchSize int
}
// MigrationSummary reports the result of a copy-only migration.
type MigrationSummary struct {
ExaminedCollections int
MigratedCollections int
MigratedRows int
}
// MigrateLegacyCollections copies all legacy Academy Milvus collections to a
// new multilingual collection base. Existing dense vectors are reused; only
// Milvus's BM25 sparse vectors are regenerated from content and language.
//
// The target collection base must differ from the source base. The operation
// is resumable because rows keep their original primary keys and are upserted.
func MigrateLegacyCollections(
ctx context.Context,
milvusClient *client.Client,
options MultilingualMigrationOptions,
) (MigrationSummary, error) {
var summary MigrationSummary
if milvusClient == nil {
return summary, fmt.Errorf("milvus client is nil")
}
sourceBase := strings.TrimSpace(options.SourceCollectionBaseName)
targetBase := strings.TrimSpace(options.TargetCollectionBaseName)
if sourceBase == "" || targetBase == "" {
return summary, fmt.Errorf("source and target collection base names are required")
}
if sourceBase == targetBase {
return summary, fmt.Errorf("source and target collection base names must differ")
}
if options.BatchSize <= 0 {
options.BatchSize = defaultMultilingualMigrationBatchSize
}
log := logger.GetLogger(ctx)
collections, err := milvusClient.ListCollections(ctx, client.NewListCollectionOption())
if err != nil {
return summary, fmt.Errorf("list Milvus collections: %w", err)
}
sort.Strings(collections)
targetRepo := &milvusRepository{
client: milvusClient,
collectionBaseName: targetBase,
shardsNum: options.ShardsNum,
replicaNumber: options.ReplicaNumber,
}
for _, sourceCollectionName := range collections {
dimension, ok := collectionDimensionForBase(sourceCollectionName, sourceBase)
if !ok {
continue
}
summary.ExaminedCollections++
sourceCollection, err := milvusClient.DescribeCollection(
ctx,
client.NewDescribeCollectionOption(sourceCollectionName),
)
if err != nil {
return summary, fmt.Errorf("describe source collection %s: %w", sourceCollectionName, err)
}
if analyzerModeFromSchema(sourceCollection.Schema) == collectionAnalyzerMulti {
log.Infof(
"[Milvus] Source collection %s already uses multilingual analyzers, skipping",
sourceCollectionName,
)
continue
}
schemaDimension, err := dimensionFromSchema(sourceCollection.Schema)
if err != nil {
return summary, fmt.Errorf("read dimension from source collection %s: %w", sourceCollectionName, err)
}
if schemaDimension != dimension {
return summary, fmt.Errorf(
"source collection %s name dimension %d does not match schema dimension %d",
sourceCollectionName,
dimension,
schemaDimension,
)
}
targetCollectionName := fmt.Sprintf("%s_%d", targetBase, dimension)
sourceMetric, err := embeddingMetricFromCollection(ctx, milvusClient, sourceCollectionName)
if err != nil {
return summary, fmt.Errorf("read metric from source collection %s: %w", sourceCollectionName, err)
}
metricType, err := resolveMigrationMetric(options.MetricType, sourceMetric)
if err != nil {
return summary, fmt.Errorf("collection %s: %w", sourceCollectionName, err)
}
hasTarget, err := milvusClient.HasCollection(ctx, client.NewHasCollectionOption(targetCollectionName))
if err != nil {
return summary, fmt.Errorf("check target collection %s: %w", targetCollectionName, err)
}
if hasTarget {
targetMetric, err := embeddingMetricFromCollection(ctx, milvusClient, targetCollectionName)
if err != nil {
return summary, fmt.Errorf("read metric from target collection %s: %w", targetCollectionName, err)
}
if targetMetric != metricType {
return summary, fmt.Errorf(
"target collection %s uses metric %s, source collection %s uses %s; choose a new target base",
targetCollectionName,
targetMetric,
sourceCollectionName,
metricType,
)
}
}
targetRepo.metricType = metricType
if err := targetRepo.ensureCollection(ctx, dimension); err != nil {
return summary, fmt.Errorf("prepare target collection %s: %w", targetCollectionName, err)
}
mode, err := targetRepo.collectionAnalyzerMode(ctx, targetCollectionName)
if err != nil {
return summary, fmt.Errorf("inspect target collection %s: %w", targetCollectionName, err)
}
if mode != collectionAnalyzerMulti {
return summary, fmt.Errorf(
"target collection %s is not multilingual; choose a new target base",
targetCollectionName,
)
}
if err := loadMilvusCollection(ctx, milvusClient, sourceCollectionName); err != nil {
return summary, fmt.Errorf("load source collection %s: %w", sourceCollectionName, err)
}
copied, err := migrateCollectionRows(
ctx,
milvusClient,
sourceCollectionName,
targetCollectionName,
dimension,
options.BatchSize,
)
summary.MigratedRows += copied
if err != nil {
return summary, fmt.Errorf("migrate collection %s: %w", sourceCollectionName, err)
}
if err := flushMilvusCollection(ctx, milvusClient, targetCollectionName); err != nil {
return summary, fmt.Errorf("flush target collection %s: %w", targetCollectionName, err)
}
summary.MigratedCollections++
log.Infof(
"[Milvus] Migrated %d rows from %s to %s",
copied,
sourceCollectionName,
targetCollectionName,
)
}
return summary, nil
}
func collectionDimensionForBase(collectionName, baseName string) (int, bool) {
prefix := strings.TrimSpace(baseName) + "_"
if !strings.HasPrefix(collectionName, prefix) {
return 0, false
}
dimension, err := strconv.Atoi(strings.TrimPrefix(collectionName, prefix))
if err != nil || dimension <= 0 {
return 0, false
}
return dimension, true
}
func matchesDimensionCollection(collectionName, baseName string) bool {
_, ok := collectionDimensionForBase(collectionName, baseName)
return ok
}
// ParseMetricType accepts IP, COSINE, or L2. An empty value means the caller
// wants the source collection's metric.
func ParseMetricType(value string) (entity.MetricType, error) {
switch strings.ToUpper(strings.TrimSpace(value)) {
case "":
return "", nil
case "IP":
return entity.IP, nil
case "COSINE":
return entity.COSINE, nil
case "L2":
return entity.L2, nil
default:
return "", fmt.Errorf("unsupported metric-type %q, must be IP, COSINE, or L2", value)
}
}
func resolveMigrationMetric(requested, source entity.MetricType) (entity.MetricType, error) {
if source == "" {
return "", fmt.Errorf("source collection metric is unknown")
}
if requested == "" || requested == source {
return source, nil
}
return "", fmt.Errorf(
"requested metric %s does not match source collection metric %s",
requested,
source,
)
}
func metricTypeFromIndexParams(params map[string]string) (entity.MetricType, error) {
raw := strings.TrimSpace(params[index.MetricTypeKey])
if raw == "" {
if nested := strings.TrimSpace(params[index.ParamsKey]); nested != "" {
var extra map[string]any
if err := json.Unmarshal([]byte(nested), &extra); err == nil {
if value, ok := extra[index.MetricTypeKey]; ok {
raw = fmt.Sprint(value)
}
}
}
}
if raw == "" {
return "", fmt.Errorf("dense vector index is missing metric_type")
}
return ParseMetricType(raw)
}
func embeddingMetricFromCollection(
ctx context.Context,
milvusClient *client.Client,
collectionName string,
) (entity.MetricType, error) {
indexNames, err := milvusClient.ListIndexes(
ctx,
client.NewListIndexOption(collectionName).WithFieldName(fieldEmbedding),
)
if err != nil {
return "", fmt.Errorf("list indexes: %w", err)
}
if len(indexNames) == 0 {
return "", fmt.Errorf("no dense vector index found")
}
description, err := milvusClient.DescribeIndex(
ctx,
client.NewDescribeIndexOption(collectionName, indexNames[0]),
)
if err != nil {
return "", fmt.Errorf("describe index %s: %w", indexNames[0], err)
}
return metricTypeFromIndexParams(description.Params())
}
func primaryKeyForMigratedRow(
document *MilvusVectorEmbeddingWithScore,
ids column.Column,
rowIndex int,
) (string, error) {
if document != nil && strings.TrimSpace(document.ID) != "" {
return document.ID, nil
}
if ids != nil {
id, err := ids.GetAsString(rowIndex)
if err != nil {
return "", fmt.Errorf("read primary key at row %d: %w", rowIndex, err)
}
if strings.TrimSpace(id) != "" {
return id, nil
}
}
return "", fmt.Errorf("missing primary key at row %d", rowIndex)
}
func dimensionFromSchema(schema *entity.Schema) (int, error) {
if schema == nil {
return 0, fmt.Errorf("collection schema is nil")
}
for _, field := range schema.Fields {
if field == nil || field.Name != fieldEmbedding {
continue
}
rawDimension, ok := field.TypeParams[entity.TypeParamDim]
if !ok {
return 0, fmt.Errorf("embedding field has no dimension")
}
dimension, err := strconv.Atoi(rawDimension)
if err != nil || dimension <= 0 {
return 0, fmt.Errorf("invalid embedding dimension %q", rawDimension)
}
return dimension, nil
}
return 0, fmt.Errorf("embedding field %q was not found", fieldEmbedding)
}
func loadMilvusCollection(ctx context.Context, milvusClient *client.Client, collectionName string) error {
loadTask, err := milvusClient.LoadCollection(ctx, client.NewLoadCollectionOption(collectionName))
if err != nil {
return err
}
return loadTask.Await(ctx)
}
func flushMilvusCollection(ctx context.Context, milvusClient *client.Client, collectionName string) error {
flushTask, err := milvusClient.Flush(ctx, client.NewFlushOption(collectionName))
if err != nil {
return err
}
return flushTask.Await(ctx)
}
func migrateCollectionRows(
ctx context.Context,
milvusClient *client.Client,
sourceCollectionName string,
targetCollectionName string,
dimension int,
batchSize int,
) (int, error) {
log := logger.GetLogger(ctx)
totalCopied := 0
batchNumber := 0
queryIterator, err := milvusClient.QueryIterator(
ctx,
client.NewQueryIteratorOption(sourceCollectionName).
WithOutputFields(migrationOutputFields...).
WithBatchSize(batchSize),
)
if err != nil {
return totalCopied, fmt.Errorf(
"create query iterator for source collection %s: %w",
sourceCollectionName,
err,
)
}
for {
resultSet, err := queryIterator.Next(ctx)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return totalCopied, fmt.Errorf(
"query source collection %s with iterator: %w",
sourceCollectionName,
err,
)
}
if resultSet.ResultCount == 0 {
break
}
batchNumber++
documents, _, err := convertResultSet([]client.ResultSet{resultSet})
if err != nil {
return totalCopied, fmt.Errorf(
"decode source collection %s at iterator batch %d: %w",
sourceCollectionName,
batchNumber,
err,
)
}
if len(documents) == 0 {
return totalCopied, fmt.Errorf(
"source collection %s returned rows without decodable fields",
sourceCollectionName,
)
}
embeddings := make([]*MilvusVectorEmbedding, 0, len(documents))
for rowIndex, document := range documents {
if len(document.Embedding) != dimension {
return totalCopied, fmt.Errorf(
"source collection %s row %d has vector dimension %d, expected %d",
sourceCollectionName,
rowIndex,
len(document.Embedding),
dimension,
)
}
document.ID, err = primaryKeyForMigratedRow(document, resultSet.IDs, rowIndex)
if err != nil {
return totalCopied, fmt.Errorf(
"source collection %s at iterator batch %d: %w",
sourceCollectionName,
batchNumber,
err,
)
}
document.Language = detectAnalyzerName(document.Content)
embeddings = append(embeddings, &document.MilvusVectorEmbedding)
}
if _, err := milvusClient.Upsert(ctx, createUpsert(targetCollectionName, embeddings, true)); err != nil {
return totalCopied, fmt.Errorf(
"upsert target collection %s at iterator batch %d: %w",
targetCollectionName,
batchNumber,
err,
)
}
totalCopied += len(embeddings)
log.Infof("[Milvus] Copied %d rows from %s", totalCopied, sourceCollectionName)
}
return totalCopied, nil
}
@@ -0,0 +1,126 @@
package milvus
import (
"testing"
"github.com/milvus-io/milvus/client/v2/column"
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/milvus-io/milvus/client/v2/index"
client "github.com/milvus-io/milvus/client/v2/milvusclient"
"github.com/stretchr/testify/require"
)
func TestCollectionDimensionForBase(t *testing.T) {
dimension, ok := collectionDimensionForBase("academy_embeddings_1536", "academy_embeddings")
require.True(t, ok)
require.Equal(t, 1536, dimension)
_, ok = collectionDimensionForBase("academy_embeddings_multilingual_1536", "academy_embeddings")
require.False(t, ok)
_, ok = collectionDimensionForBase("academy_embeddings", "academy_embeddings")
require.False(t, ok)
_, ok = collectionDimensionForBase("academy_embeddings_1536_backup", "academy_embeddings")
require.False(t, ok)
require.True(t, matchesDimensionCollection(
"academy_embeddings_multilingual_1536",
"academy_embeddings_multilingual",
))
require.False(t, matchesDimensionCollection("academy_embeddings_1536", "academy_embeddings_multilingual"))
}
func TestParseMetricType(t *testing.T) {
metric, err := ParseMetricType("")
require.NoError(t, err)
require.Equal(t, entity.MetricType(""), metric)
metric, err = ParseMetricType(" cosine ")
require.NoError(t, err)
require.Equal(t, entity.COSINE, metric)
_, err = ParseMetricType("dot")
require.Error(t, err)
}
func TestResolveMigrationMetric(t *testing.T) {
metric, err := resolveMigrationMetric("", entity.IP)
require.NoError(t, err)
require.Equal(t, entity.IP, metric)
metric, err = resolveMigrationMetric(entity.IP, entity.IP)
require.NoError(t, err)
require.Equal(t, entity.IP, metric)
_, err = resolveMigrationMetric(entity.COSINE, entity.IP)
require.Error(t, err)
require.Contains(t, err.Error(), "does not match")
_, err = resolveMigrationMetric("", "")
require.Error(t, err)
}
func TestMetricTypeFromIndexParams(t *testing.T) {
metric, err := metricTypeFromIndexParams(map[string]string{
index.MetricTypeKey: "IP",
})
require.NoError(t, err)
require.Equal(t, entity.IP, metric)
metric, err = metricTypeFromIndexParams(map[string]string{
index.ParamsKey: `{"metric_type":"COSINE"}`,
})
require.NoError(t, err)
require.Equal(t, entity.COSINE, metric)
_, err = metricTypeFromIndexParams(map[string]string{})
require.Error(t, err)
}
func TestPrimaryKeyForMigratedRow(t *testing.T) {
id, err := primaryKeyForMigratedRow(&MilvusVectorEmbeddingWithScore{
MilvusVectorEmbedding: MilvusVectorEmbedding{ID: "pk-1"},
}, nil, 0)
require.NoError(t, err)
require.Equal(t, "pk-1", id)
ids := column.NewColumnVarChar(fieldID, []string{"from-ids"})
id, err = primaryKeyForMigratedRow(&MilvusVectorEmbeddingWithScore{}, ids, 0)
require.NoError(t, err)
require.Equal(t, "from-ids", id)
_, err = primaryKeyForMigratedRow(&MilvusVectorEmbeddingWithScore{}, nil, 3)
require.Error(t, err)
require.Contains(t, err.Error(), "missing primary key")
}
func TestConvertResultSetFloatVector(t *testing.T) {
embedding := []float32{0.1, 0.2, 0.3}
docs, _, err := convertResultSet([]client.ResultSet{{
ResultCount: 1,
Fields: client.DataSet{
column.NewColumnVarChar(fieldID, []string{"pk-1"}),
column.NewColumnVarChar(fieldContent, []string{"hello"}),
column.NewColumnVarChar(fieldLanguage, []string{"english"}),
column.NewColumnFloatVector(fieldEmbedding, 3, [][]float32{embedding}),
},
}})
require.NoError(t, err)
require.Len(t, docs, 1)
require.Equal(t, "pk-1", docs[0].ID)
require.Equal(t, "hello", docs[0].Content)
require.Equal(t, "english", docs[0].Language)
require.Equal(t, embedding, docs[0].Embedding)
}
func TestConvertResultSetDoubleArray(t *testing.T) {
docs, _, err := convertResultSet([]client.ResultSet{{
ResultCount: 1,
Fields: client.DataSet{
column.NewColumnVarChar(fieldID, []string{"pk-1"}),
column.NewColumnDoubleArray(fieldEmbedding, [][]float64{{1, 2, 3}}),
},
}})
require.NoError(t, err)
require.Len(t, docs, 1)
require.Equal(t, []float32{1, 2, 3}, docs[0].Embedding)
}
@@ -0,0 +1,65 @@
package milvus
import (
"context"
"fmt"
)
func (m *milvusRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
dimension int,
_ string,
) error {
collection := m.getCollectionName(dimension)
filter := &universalFilterCondition{Operator: operatorAnd, Value: []*universalFilterCondition{
{Field: fieldKnowledgeBaseID, Operator: operatorEqual, Value: sourceKB},
{Field: fieldKnowledgeID, Operator: operatorEqual, Value: knowledgeID},
}}
size, offset := 100, 0
collectionMode, err := m.collectionAnalyzerMode(ctx, collection)
if err != nil {
return err
}
return drainMoveRows(ctx, targetKB, func(ctx context.Context) ([]*MilvusVectorEmbeddingWithScore, error) {
rows, _, err := m.searchByFilter(ctx, collection, filter, &size, &offset)
return rows, err
}, func(ctx context.Context, rows []*MilvusVectorEmbedding) error {
_, err := m.client.Upsert(ctx, createUpsert(collection, rows, collectionMode == collectionAnalyzerMulti))
return err
})
}
// Drain the source predicate without offset windows. A repeated ID means the
// backend has not made the acknowledged update visible; fail for retry instead
// of advancing the document checkpoint or silently omitting remaining vectors.
func drainMoveRows(ctx context.Context, targetKB string,
read func(context.Context) ([]*MilvusVectorEmbeddingWithScore, error),
write func(context.Context, []*MilvusVectorEmbedding) error,
) error {
seen := map[string]bool{}
for {
rows, err := read(ctx)
if err != nil {
return err
}
if len(rows) == 0 {
return nil
}
batch := make([]*MilvusVectorEmbedding, 0, len(rows))
for _, row := range rows {
if row == nil || row.ID == "" || seen[row.ID] {
return fmt.Errorf("invalid or repeated move index")
}
seen[row.ID] = true
copyOfRow := row.MilvusVectorEmbedding
copyOfRow.KnowledgeBaseID = targetKB
copyOfRow.TagID = ""
batch = append(batch, &copyOfRow)
}
if err := write(ctx, batch); err != nil {
return err
}
}
}
@@ -0,0 +1,82 @@
package milvus
import (
"context"
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestMoveRowsDrainsPagesAndRetriesPartialUpsert(t *testing.T) {
remaining := map[string]*MilvusVectorEmbeddingWithScore{}
moved := map[string]*MilvusVectorEmbedding{}
for i := range 205 {
id := fmt.Sprint(i)
remaining[id] = &MilvusVectorEmbeddingWithScore{MilvusVectorEmbedding: MilvusVectorEmbedding{
ID: id,
KnowledgeID: "doc",
KnowledgeBaseID: "source",
TagID: "old-tag",
ChunkID: "chunk-" + id,
Content: "text",
Embedding: []float32{1, 2, 3},
IsEnabled: i%2 == 0,
}}
}
reads, writes := 0, 0
failure := errors.New("partial upsert")
read := func(context.Context) ([]*MilvusVectorEmbeddingWithScore, error) {
reads++
var rows []*MilvusVectorEmbeddingWithScore
for _, row := range remaining {
rows = append(rows, row)
if len(rows) == 100 {
break
}
}
return rows, nil
}
write := func(_ context.Context, rows []*MilvusVectorEmbedding) error {
writes++
for i, row := range rows {
original := remaining[row.ID]
require.NotNil(t, original)
require.Equal(t, "source", original.KnowledgeBaseID, "read rows must not be mutated before acknowledgement")
require.Equal(t, "target", row.KnowledgeBaseID)
require.Empty(t, row.TagID)
expected := original.MilvusVectorEmbedding
expected.KnowledgeBaseID = "target"
expected.TagID = ""
require.Equal(t, expected, *row)
moved[row.ID] = row
delete(remaining, row.ID)
if writes == 2 && i == 16 {
return failure
}
}
return nil
}
require.ErrorIs(t, drainMoveRows(context.Background(), "target", read, write), failure)
require.Len(t, remaining, 88)
require.NoError(t, drainMoveRows(context.Background(), "target", read, write))
require.Empty(t, remaining)
require.Len(t, moved, 205)
require.Equal(t, 4, reads, "retry must verify an empty source predicate")
}
func TestMoveRowsRejectsUnacknowledgedProgress(t *testing.T) {
row := &MilvusVectorEmbeddingWithScore{
MilvusVectorEmbedding: MilvusVectorEmbedding{ID: "id", KnowledgeBaseID: "source"},
}
err := drainMoveRows(
context.Background(),
"target",
func(context.Context) ([]*MilvusVectorEmbeddingWithScore, error) {
return []*MilvusVectorEmbeddingWithScore{row}, nil
},
func(context.Context, []*MilvusVectorEmbedding) error { return nil },
)
require.ErrorContains(t, err, "repeated")
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,102 @@
package milvus
import (
"context"
"errors"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestBuildMilvusIndexResultsPreservesSearchScores(t *testing.T) {
documents := []*MilvusVectorEmbeddingWithScore{
{MilvusVectorEmbedding: MilvusVectorEmbedding{ID: "id-1", ChunkID: "chunk-1"}},
{MilvusVectorEmbedding: MilvusVectorEmbedding{ID: "id-2", ChunkID: "chunk-2"}},
}
results, err := buildMilvusIndexResults(
documents,
[]float64{3.25, 0.75},
types.MatchTypeKeywords,
)
require.NoError(t, err)
require.Len(t, results, 2)
require.Equal(t, types.MatchTypeKeywords, results[0].MatchType)
require.Equal(t, 3.25, results[0].Score)
require.Equal(t, 0.75, results[1].Score)
}
func TestBuildMilvusIndexResultsRejectsScoreCountMismatch(t *testing.T) {
_, err := buildMilvusIndexResults(
[]*MilvusVectorEmbeddingWithScore{
{MilvusVectorEmbedding: MilvusVectorEmbedding{ID: "id-1"}},
},
nil,
types.MatchTypeKeywords,
)
require.Error(t, err)
}
func TestUpdateChunkEnabledStatusInCollectionSkipsEmptyChunkIDs(t *testing.T) {
repo := &milvusRepository{}
require.NoError(t, repo.updateChunkEnabledStatusInCollection(
context.Background(),
"academy_embeddings_1024",
nil,
false,
))
require.NoError(t, repo.updateChunkEnabledStatusInCollection(
context.Background(),
"academy_embeddings_1024",
[]string{},
true,
))
}
func TestUpdateChunkEnabledStatusInCollectionsPropagatesFailure(t *testing.T) {
wantErr := errors.New("upsert failed")
err := updateChunkEnabledStatusInCollections(
context.Background(),
[]string{"other_collection", "academy_embeddings_1024"},
"academy_embeddings",
nil,
[]string{"chunk-1"},
func(_ context.Context, collection string, _ []string, enabled bool) error {
if collection == "academy_embeddings_1024" && !enabled {
return wantErr
}
return nil
},
)
require.ErrorIs(t, err, wantErr)
}
func TestUpdateChunkEnabledStatusInCollectionsIgnoresExtendedPrefix(t *testing.T) {
var seen []string
seenSet := map[string]bool{}
err := updateChunkEnabledStatusInCollections(
context.Background(),
[]string{
"other_collection",
"academy_embeddings_1024",
"academy_embeddings_multilingual_1024",
"academy_embeddings_1024_backup",
},
"academy_embeddings",
[]string{"chunk-1"},
nil,
func(_ context.Context, collection string, _ []string, _ bool) error {
if !seenSet[collection] {
seenSet[collection] = true
seen = append(seen, collection)
}
return nil
},
)
require.NoError(t, err)
require.Equal(t, []string{"academy_embeddings_1024"}, seen)
}
@@ -0,0 +1,29 @@
package milvus
import (
"testing"
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/stretchr/testify/require"
)
// Milvus L2 reports the squared distance of unit vectors, 2 - 2cos. Scores
// leave the driver as cosine similarity and thresholds map onto the radius.
func TestMetricConversionL2(t *testing.T) {
t.Parallel()
m := &milvusRepository{metricType: entity.L2}
require.InDelta(t, 1.0, m.metricToSimilarity(0), 1e-9)
require.InDelta(t, 0.5, m.metricToSimilarity(1), 1e-9)
require.Greater(t, m.metricToSimilarity(0.2), m.metricToSimilarity(0.8), "nearer must score higher")
require.InDelta(t, 1.0, m.similarityToMetric(0.5), 1e-9)
require.InDelta(t, 0.5, m.metricToSimilarity(m.similarityToMetric(0.5)), 1e-9)
}
func TestMetricConversionIPAndCosinePassThrough(t *testing.T) {
t.Parallel()
for _, metric := range []entity.MetricType{entity.IP, entity.COSINE} {
m := &milvusRepository{metricType: metric}
require.InDelta(t, 0.73, m.metricToSimilarity(0.73), 1e-9)
require.InDelta(t, 0.4, m.similarityToMetric(0.4), 1e-9)
}
}
@@ -0,0 +1,40 @@
package milvus
import (
"sync"
"github.com/milvus-io/milvus/client/v2/entity"
client "github.com/milvus-io/milvus/client/v2/milvusclient"
)
type milvusRepository struct {
filter
client *client.Client
collectionBaseName string
metricType entity.MetricType
shardsNum int // 0 = use Milvus default (1)
replicaNumber int // 0 = use Milvus default (1); set at LoadCollection time
// Cache for initialized collections (dimension -> true)
initializedCollections sync.Map
// Cache for collection analyzer modes (collection name -> collectionAnalyzerMode).
collectionAnalyzerModes sync.Map
}
type MilvusVectorEmbedding struct {
ID string `json:"id"`
Content string `json:"content"`
Language string `json:"language"`
SourceID string `json:"source_id"`
SourceType int `json:"source_type"`
ChunkID string `json:"chunk_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
TagID string `json:"tag_id"`
Embedding []float32 `json:"embedding"`
IsEnabled bool `json:"is_enabled"`
}
type MilvusVectorEmbeddingWithScore struct {
MilvusVectorEmbedding
Score float64
}