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,228 @@
package doris
import (
"context"
"database/sql"
"fmt"
"os"
"sort"
"strings"
"academy/internal/logger"
)
const envDorisCompatMode = "DORIS_COMPAT_MODE"
type dorisCompatMode string
const (
dorisCompatModeAuto dorisCompatMode = "auto"
dorisCompatModeLegacy dorisCompatMode = "legacy"
dorisCompatModeInnerProductDuplicate dorisCompatMode = "inner_product_duplicate"
)
type dorisCompatProbe struct {
innerProductApproximate bool
cosineDistanceApproximate bool
}
func resolveConfiguredDorisCompatMode() (mode dorisCompatMode, invalid string) {
raw := strings.TrimSpace(os.Getenv(envDorisCompatMode))
if raw == "" {
return dorisCompatModeAuto, ""
}
switch strings.ToLower(raw) {
case string(dorisCompatModeAuto):
return dorisCompatModeAuto, ""
case string(dorisCompatModeLegacy):
return dorisCompatModeLegacy, ""
case string(dorisCompatModeInnerProductDuplicate), "inner-product-duplicate", "inner_product", "inner-product":
return dorisCompatModeInnerProductDuplicate, ""
default:
return dorisCompatModeAuto, raw
}
}
func (r *dorisRepository) resolveCompatMode(ctx context.Context) (dorisCompatMode, error) {
r.compatResolveOnce.Do(func() {
log := logger.GetLogger(ctx)
requested := r.compatModeRequested
if requested == "" {
r.compatModeResolved = dorisCompatModeInnerProductDuplicate
return
}
existingMode, exampleTable, foundExisting, err := r.detectExistingCompatMode(ctx)
if err != nil {
r.compatResolveErr = err
return
}
if foundExisting {
if requested != dorisCompatModeAuto && requested != existingMode {
r.compatResolveErr = fmt.Errorf(
"Doris compat mode %q does not match existing embedding tables (detected %q from %s). %s is not interchangeable after %s_* tables are created. Recreate the existing %s_* tables before switching modes, or set %s=%s",
requested,
existingMode,
exampleTable,
envDorisCompatMode,
r.tableBaseName,
r.tableBaseName,
envDorisCompatMode,
existingMode,
)
log.Errorf("[Doris] %v", r.compatResolveErr)
return
}
r.compatModeResolved = existingMode
log.Warnf(
"[Doris] Using compat mode %s from existing embedding tables (%s). %s is not interchangeable after %s_* tables are created; recreate those tables before switching modes.",
existingMode,
exampleTable,
envDorisCompatMode,
r.tableBaseName,
)
return
}
if requested == dorisCompatModeAuto {
probe, probeErr := r.probeCompatMode(ctx)
if probeErr != nil {
r.compatResolveErr = probeErr
log.Errorf("[Doris] %v", probeErr)
return
}
log.Infof(
"[Doris] Compat probe result: inner_product_approximate=%t, cosine_distance_approximate=%t",
probe.innerProductApproximate,
probe.cosineDistanceApproximate,
)
switch {
case probe.innerProductApproximate:
r.compatModeResolved = dorisCompatModeInnerProductDuplicate
case probe.cosineDistanceApproximate:
r.compatModeResolved = dorisCompatModeLegacy
default:
r.compatResolveErr = fmt.Errorf(
"Doris compatibility auto-detection could not find a supported vector function. Set %s=%s or %s=%s explicitly after verifying your Doris build. %s is not interchangeable after %s_* tables are created",
envDorisCompatMode,
dorisCompatModeInnerProductDuplicate,
envDorisCompatMode,
dorisCompatModeLegacy,
envDorisCompatMode,
r.tableBaseName,
)
log.Errorf("[Doris] %v", r.compatResolveErr)
return
}
log.Warnf(
"[Doris] Auto-selected compat mode %s for new embedding tables. %s is not interchangeable after %s_* tables are created; recreate those tables before switching modes.",
r.compatModeResolved,
envDorisCompatMode,
r.tableBaseName,
)
return
}
r.compatModeResolved = requested
log.Warnf(
"[Doris] Using configured compat mode %s for new embedding tables. %s is not interchangeable after %s_* tables are created; recreate those tables before switching modes.",
r.compatModeResolved,
envDorisCompatMode,
r.tableBaseName,
)
})
return r.compatModeResolved, r.compatResolveErr
}
func (r *dorisRepository) detectExistingCompatMode(ctx context.Context) (dorisCompatMode, string, bool, error) {
tables, err := r.listEmbeddingTables(ctx)
if err != nil {
return "", "", false, fmt.Errorf("list Doris embedding tables: %w", err)
}
if len(tables) == 0 {
return "", "", false, nil
}
sort.Strings(tables)
var detected dorisCompatMode
for _, table := range tables {
ddl, err := r.showCreateTable(ctx, table)
if err != nil {
return "", "", false, fmt.Errorf("show create table %s: %w", table, err)
}
mode, err := compatModeFromDDL(ddl)
if err != nil {
return "", "", false, fmt.Errorf("detect compat mode from %s: %w", table, err)
}
if detected == "" {
detected = mode
continue
}
if detected != mode {
return "", "", false, fmt.Errorf(
"existing Doris embedding tables use mixed compat modes (%s and %s). %s is not interchangeable after %s_* tables are created; recreate the existing %s_* tables with a single mode",
detected,
mode,
envDorisCompatMode,
r.tableBaseName,
r.tableBaseName,
)
}
}
return detected, tables[0], true, nil
}
func (r *dorisRepository) showCreateTable(ctx context.Context, table string) (string, error) {
row := r.db.QueryRowContext(ctx, fmt.Sprintf("SHOW CREATE TABLE `%s`", table))
var tableName, ddl string
if err := row.Scan(&tableName, &ddl); err != nil {
return "", err
}
return ddl, nil
}
func compatModeFromDDL(ddl string) (dorisCompatMode, error) {
normalized := strings.ToLower(ddl)
switch {
case strings.Contains(normalized, "duplicate key("):
return dorisCompatModeInnerProductDuplicate, nil
case strings.Contains(normalized, "unique key("):
return dorisCompatModeLegacy, nil
default:
return "", fmt.Errorf("unsupported table definition; expected UNIQUE KEY or DUPLICATE KEY")
}
}
func (r *dorisRepository) probeCompatMode(ctx context.Context) (dorisCompatProbe, error) {
probe := dorisCompatProbe{}
probe.innerProductApproximate = r.vectorFunctionSupported(ctx, "inner_product_approximate([1.0],[1.0])")
probe.cosineDistanceApproximate = r.vectorFunctionSupported(ctx, "cosine_distance_approximate([1.0],[1.0])")
return probe, nil
}
func (r *dorisRepository) vectorFunctionSupported(ctx context.Context, expr string) bool {
var value sql.NullFloat64
if err := r.db.QueryRowContext(ctx, "SELECT "+expr).Scan(&value); err != nil {
return false
}
return true
}
func (m dorisCompatMode) normalizeEmbeddings() bool {
return m != dorisCompatModeLegacy
}
func (m dorisCompatMode) usesReplaceWrite() bool {
return m != dorisCompatModeLegacy
}
func (m dorisCompatMode) usesRewriteChunkUpdates() bool {
return m != dorisCompatModeLegacy
}
@@ -0,0 +1,41 @@
package doris
import (
"context"
"fmt"
)
func (r *dorisRepository) ValidateKnowledgeIndexMove(ctx context.Context) error {
mode, err := r.resolveCompatMode(ctx)
if err != nil {
return err
}
if mode.usesRewriteChunkUpdates() {
// ANN DUPLICATE KEY tables implement replacement as DELETE + INSERT.
// A failed insert would lose the only vector copy; changing physical IDs
// would break the stable source-ID identity used by subsequent edits.
return fmt.Errorf("reuse_vectors move is not supported by Doris ANN tables; use reparse mode")
}
return nil
}
func (r *dorisRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
dimension int,
_ string,
) error {
if err := r.ValidateKnowledgeIndexMove(ctx); err != nil {
return err
}
if dimension <= 0 {
return fmt.Errorf("invalid embedding dimension")
}
query := fmt.Sprintf(
"UPDATE `%s` SET knowledge_base_id = ?, tag_id = '' WHERE knowledge_base_id = ? AND knowledge_id = ?",
r.getTableName(dimension),
)
_, err := r.db.ExecContext(ctx, query, targetKB, sourceKB, knowledgeID)
return err
}
@@ -0,0 +1,36 @@
package doris
import (
"context"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/require"
)
func TestMoveIndicesRejectsNonAtomicANNReplacement(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
require.ErrorContains(
t,
repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", []string{"chunk"}, 2, "document"),
"use reparse mode",
)
require.NoError(t, mock.ExpectationsWereMet(), "rejection must issue no vector delete or insert")
}
func TestMoveIndicesLegacyUpdatesOnlyExactSourceDocument(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
primeCompatMode(repo, dorisCompatModeLegacy, nil)
mock.ExpectExec("UPDATE `academy_embeddings_2` SET knowledge_base_id = \\?, tag_id = '' WHERE "+
"knowledge_base_id = \\? AND knowledge_id = \\?").
WithArgs("target", "source", "doc").
WillReturnResult(sqlmock.NewResult(0, 3))
require.NoError(
t,
repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", []string{"chunk"}, 2, "document"),
)
require.NoError(t, mock.ExpectationsWereMet())
}
@@ -0,0 +1,252 @@
package doris
import (
"math"
"strconv"
"strings"
"academy/internal/types"
)
// 字段名常量。Doris 是 SQL 库,字段名要在 SELECT/WHERE/INSERT 多处复用,
// 用常量统一防止笔误。
const (
fieldID = "id"
fieldContent = "content"
fieldSourceID = "source_id"
fieldSourceType = "source_type"
fieldChunkID = "chunk_id"
fieldKnowledgeID = "knowledge_id"
fieldKnowledgeBaseID = "knowledge_base_id"
fieldTagID = "tag_id"
fieldIsEnabled = "is_enabled"
fieldEmbedding = "embedding"
)
// columns 是 INSERT / SELECT 时使用的标准列序。
var columns = []string{
fieldID, fieldContent, fieldSourceID, fieldSourceType,
fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID,
fieldIsEnabled, fieldEmbedding,
}
// columnsForRetrieve 是 Retrieve 时 SELECT 的列序,
// 不包含 embedding(向量本身查询结果中无需返回,省带宽)。
var columnsForRetrieve = []string{
fieldID, fieldContent, fieldSourceID, fieldSourceType,
fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID,
fieldIsEnabled,
}
// columnsForCopy 是 CopyIndices 中分页 SELECT 时使用的列序,
// 比 columnsForRetrieve 多 embedding,因为复制目的是搬运向量本身。
var columnsForCopy = []string{
fieldID, fieldContent, fieldSourceID, fieldSourceType,
fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID,
fieldIsEnabled, fieldEmbedding,
}
// whereCond 表示一个 WHERE 子条件:clause 是参数化 SQL 片段(带 ? 占位),
// args 是对应顺序的参数值。所有用户输入字段(IDs)必须通过 args 传入,
// 严禁拼到 clause 字符串里。
type whereCond struct {
clause string
args []any
}
// whereBuilder 用于把 RetrieveParams 中的过滤条件翻译成 SQL WHERE 子句。
//
// 每个 add* 方法对应一种 IN / NOT IN / = 算子;最终 build() 用 AND 拼接。
type whereBuilder struct {
conds []whereCond
}
// addEqual 追加一个 field = ? 条件。
func (w *whereBuilder) addEqual(field string, value any) {
w.conds = append(w.conds, whereCond{
clause: field + " = ?",
args: []any{value},
})
}
// addIn 追加一个 field IN (?, ?, ...) 条件。values 为空时不追加任何东西。
func (w *whereBuilder) addIn(field string, values []string) {
if len(values) == 0 {
return
}
placeholders := make([]string, len(values))
args := make([]any, len(values))
for i, v := range values {
placeholders[i] = "?"
args[i] = v
}
w.conds = append(w.conds, whereCond{
clause: field + " IN (" + strings.Join(placeholders, ", ") + ")",
args: args,
})
}
// addNotIn 追加一个 field NOT IN (?, ?, ...) 条件。
func (w *whereBuilder) addNotIn(field string, values []string) {
if len(values) == 0 {
return
}
placeholders := make([]string, len(values))
args := make([]any, len(values))
for i, v := range values {
placeholders[i] = "?"
args[i] = v
}
w.conds = append(w.conds, whereCond{
clause: field + " NOT IN (" + strings.Join(placeholders, ", ") + ")",
args: args,
})
}
// build 返回 WHERE 子句(不含 "WHERE " 前缀)和参数数组。
// 没有任何条件时返回 ("1 = 1", nil),方便调用方无脑拼接。
func (w *whereBuilder) build() (string, []any) {
if len(w.conds) == 0 {
return "1 = 1", nil
}
parts := make([]string, len(w.conds))
var args []any
for i, c := range w.conds {
parts[i] = c.clause
args = append(args, c.args...)
}
return strings.Join(parts, " AND "), args
}
// buildBaseFilter 将 RetrieveParams 中的过滤条件翻译为 whereBuilder。
// 默认追加 is_enabled = TRUE,与 Qdrant/Milvus/Weaviate 保持一致:
// 关闭的 chunk 不参与检索。
func buildBaseFilter(params types.RetrieveParams) *whereBuilder {
w := &whereBuilder{}
w.addEqual(fieldIsEnabled, true)
if len(params.KnowledgeBaseIDs) > 0 {
w.addIn(fieldKnowledgeBaseID, params.KnowledgeBaseIDs)
}
if len(params.KnowledgeIDs) > 0 {
w.addIn(fieldKnowledgeID, params.KnowledgeIDs)
}
if len(params.TagIDs) > 0 {
w.addIn(fieldTagID, params.TagIDs)
}
if len(params.ExcludeKnowledgeIDs) > 0 {
w.addNotIn(fieldKnowledgeID, params.ExcludeKnowledgeIDs)
}
if len(params.ExcludeChunkIDs) > 0 {
w.addNotIn(fieldChunkID, params.ExcludeChunkIDs)
}
return w
}
// parseEmbeddingLiteral 解析 Doris ARRAY<FLOAT> 通过 MySQL 协议返回的
// 字面量字符串(形如 "[1,2,3]")为 []float32。
//
// CopyIndices 路径需要从源行读出向量本身再写回目标行;此处的解析容错优先:
// 不带 [] 也接受、空数组返回 nil。
func parseEmbeddingLiteral(raw []byte) ([]float32, error) {
s := strings.TrimSpace(string(raw))
if s == "" {
return nil, nil
}
s = strings.TrimPrefix(s, "[")
s = strings.TrimSuffix(s, "]")
if s == "" {
return nil, nil
}
parts := strings.Split(s, ",")
out := make([]float32, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p == "" {
continue
}
f, err := strconv.ParseFloat(p, 32)
if err != nil {
return nil, err
}
out = append(out, float32(f))
}
return out, nil
}
// validateEmbedding 校验向量元素均为有限值。
//
// strconv.FormatFloat 对 NaN/±Inf 会输出 "NaN"/"+Inf"/"-Inf",
// 这些字面量会让 Doris 拼出来的 SQL 报语法错误(或在某些版本下产生未定义结果)。
// 上游(嵌入模型)正常情况下不会输出非有限值,但 GPU OOM、上游 bug、
// 测试桩都可能触发;这里 fail-fast 比悄悄写脏数据安全。
func validateEmbedding(vec []float32) error {
for i, v := range vec {
if f := float64(v); math.IsNaN(f) || math.IsInf(f, 0) {
return errInvalidEmbedding{index: i, value: v}
}
}
return nil
}
// normalizeEmbedding returns a unit-length copy of vec so Doris inner-product
// ANN search can preserve cosine-style similarity semantics.
func normalizeEmbedding(vec []float32) []float32 {
if len(vec) == 0 {
return nil
}
var sumSquares float64
for _, value := range vec {
f := float64(value)
sumSquares += f * f
}
if sumSquares == 0 {
return append([]float32(nil), vec...)
}
norm := float32(math.Sqrt(sumSquares))
normalized := make([]float32, len(vec))
for i, value := range vec {
normalized[i] = value / norm
}
return normalized
}
// errInvalidEmbedding 描述哪个下标含非有限值;用结构体而非 fmt.Errorf
// 是为了让上层在日志里能拿到下标做问题定位。
type errInvalidEmbedding struct {
index int
value float32
}
func (e errInvalidEmbedding) Error() string {
return "doris: embedding[" + strconv.Itoa(e.index) +
"] is not finite: " + strconv.FormatFloat(float64(e.value), 'g', -1, 32)
}
// embeddingLiteral 把 []float32 转为 Doris ARRAY<FLOAT> 字面量字符串:
// "[1.23,4.56,...]"。
//
// 为何不用占位符:go-sql-driver/mysql 不支持 ARRAY 类型的参数绑定,
// Doris 端也只接受字面量形式。这里用 strconv.FormatFloat('g' + bitSize=32)
// 而不是 fmt.Sprintf("%f", v),原因有二:
// 1. fmt 在某些 locale 下会用千分位分隔符,破坏 SQL 语法;
// 2. 'g' 比 'f' 短且不会丢精度。
//
// 注入风险:[]float32 元素是嵌入模型输出的有限位数浮点数,序列化后只可能
// 包含 [0-9eE+-.\s] 字符,不会逃逸出字面量上下文。
func embeddingLiteral(vec []float32) string {
if len(vec) == 0 {
return "[]"
}
var sb strings.Builder
sb.Grow(len(vec) * 12)
sb.WriteByte('[')
for i, v := range vec {
if i > 0 {
sb.WriteByte(',')
}
sb.WriteString(strconv.FormatFloat(float64(v), 'g', -1, 32))
}
sb.WriteByte(']')
return sb.String()
}
@@ -0,0 +1,699 @@
package doris
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/google/uuid"
)
const (
defaultTableBaseName = "academy_embeddings"
envDorisTablePrefix = "DORIS_TABLE_PREFIX"
)
// NewDorisRetrieveEngineRepository 创建 Doris 检索引擎仓储。
//
// 参数:
// - db:MySQL 协议的 *sql.DB 实例。调用方负责 SetMaxOpenConns 等参数。
// - feHTTPBase:Stream Load 用的 FE HTTP 基地址(含 scheme),例如 "http://doris-fe:8030"。
// - username/password:MySQL 与 Stream Load 共用的凭据。
// - database:目标数据库名(既用于 MySQL DSN,也用于 Stream Load URL 路径)。
// - indexCfg:可空。为 nil 时退化为环境变量 + 默认值(env 路径)。
func NewDorisRetrieveEngineRepository(
db *sql.DB,
feHTTPBase, username, password, database string,
indexCfg *types.IndexConfig,
) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[Doris] Initializing Doris retriever engine repository")
tableBaseName := types.ResolveCollectionName(indexCfg, envDorisTablePrefix, defaultTableBaseName)
compatMode, invalidCompatMode := resolveConfiguredDorisCompatMode()
if invalidCompatMode != "" {
log.Warnf("[Doris] Invalid %s=%q, defaulting to %s", envDorisCompatMode, invalidCompatMode, dorisCompatModeAuto)
}
repo := &dorisRepository{
db: db,
httpClient: newDorisStreamLoadHTTPClient(),
feHTTPBase: strings.TrimRight(feHTTPBase, "/"),
username: username,
password: password,
database: database,
tableBaseName: tableBaseName,
bucketsNum: indexCfg.GetBucketsNum(0),
replicationNum: indexCfg.GetReplicationNum(0),
compatModeRequested: compatMode,
}
log.Infof("[Doris] Repository initialized: db=%s, base=%s, fe_http=%s, compat_mode=%s",
database, tableBaseName, repo.feHTTPBase, repo.compatModeRequested)
if os.Getenv(envDorisCompatMode) == "" {
log.Infof("[Doris] %s not set, defaulting to %s and probing on first use", envDorisCompatMode, dorisCompatModeAuto)
}
return repo
}
func (r *dorisRepository) EngineType() types.RetrieverEngineType {
return types.DorisRetrieverEngineType
}
func (r *dorisRepository) Support() []types.RetrieverType {
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
}
// EstimateStorageSize 估算给定 IndexInfo 列表的存储字节数。
//
// 参考 Qdrant 的算法:payload 字段长度 + 向量字节 + HNSW 邻居 + 元数据。
func (r *dorisRepository) EstimateStorageSize(_ context.Context,
indexInfoList []*types.IndexInfo, params map[string]any,
) int64 {
var total int64
for _, info := range indexInfoList {
emb := toDorisVectorEmbedding(info, params, dorisCompatModeInnerProductDuplicate)
total += calculateStorageSize(emb)
}
return total
}
// Save 写入单条记录到对应维度的表。空向量在 BatchSave 内部统一拒绝。
func (r *dorisRepository) Save(ctx context.Context,
info *types.IndexInfo, additionalParams map[string]any,
) error {
return r.BatchSave(ctx, []*types.IndexInfo{info}, additionalParams)
}
// BatchSave 把同一批 IndexInfo 按维度分组;Doris ANN 兼容表使用
// DUPLICATE KEY,因此这里显式按 id 做 delete + insert,保持原先的替换语义。
func (r *dorisRepository) BatchSave(ctx context.Context,
indexInfoList []*types.IndexInfo, additionalParams map[string]any,
) error {
log := logger.GetLogger(ctx)
if len(indexInfoList) == 0 {
return nil
}
compatMode, err := r.resolveCompatMode(ctx)
if err != nil {
return err
}
groups := make(map[int][]*DorisVectorEmbedding)
for _, info := range indexInfoList {
emb := toDorisVectorEmbedding(info, additionalParams, compatMode)
if len(emb.Embedding) == 0 {
log.Warnf("[Doris] Skipping empty embedding for chunk %s", info.ChunkID)
continue
}
if err := validateEmbedding(emb.Embedding); err != nil {
return fmt.Errorf("invalid embedding for chunk %s: %w", info.ChunkID, err)
}
// 给一个稳定的主键。SourceID 是上层最有意义的"行身份",
// 但同 chunk 多 question 的场景下 SourceID 已经唯一,所以直接用它。
if emb.ID == "" {
emb.ID = emb.SourceID
}
if emb.ID == "" {
emb.ID = uuid.New().String()
}
dim := len(emb.Embedding)
groups[dim] = append(groups[dim], emb)
}
for dim, rows := range groups {
if err := r.ensureTable(ctx, dim); err != nil {
return err
}
if compatMode.usesReplaceWrite() {
err = r.replaceRows(ctx, r.getTableName(dim), rows)
} else {
err = r.insertRows(ctx, r.getTableName(dim), rows)
}
if err != nil {
return fmt.Errorf("batch save dim=%d: %w", dim, err)
}
log.Infof("[Doris] Saved %d rows to %s", len(rows), r.getTableName(dim))
}
return nil
}
// insertRows 按列序拼一条多 VALUES 的 INSERT。embedding 列由于
// go-sql-driver/mysql 不支持 ARRAY 占位符,必须以字面量形式拼到 SQL 文本中。
func (r *dorisRepository) insertRows(ctx context.Context,
table string, rows []*DorisVectorEmbedding,
) error {
if len(rows) == 0 {
return nil
}
// 9 个普通占位符 + 1 个 embedding 字面量。
const perRowPlaceholders = "(?, ?, ?, ?, ?, ?, ?, ?, ?, %s)"
parts := make([]string, len(rows))
args := make([]any, 0, len(rows)*9)
for i, e := range rows {
parts[i] = fmt.Sprintf(perRowPlaceholders, embeddingLiteral(e.Embedding))
args = append(args,
e.ID, e.Content, e.SourceID, e.SourceType,
e.ChunkID, e.KnowledgeID, e.KnowledgeBaseID, e.TagID,
e.IsEnabled,
)
}
stmt := fmt.Sprintf("INSERT INTO `%s` (%s) VALUES %s",
table,
strings.Join(columns, ", "),
strings.Join(parts, ", "),
)
_, err := r.db.ExecContext(ctx, stmt, args...)
return err
}
// replaceRows 在 DUPLICATE KEY 表上显式模拟“按 id 覆盖”的语义。
func (r *dorisRepository) replaceRows(ctx context.Context,
table string, rows []*DorisVectorEmbedding,
) error {
rows = dedupeRowsByID(rows)
if len(rows) == 0 {
return nil
}
ids := make([]string, 0, len(rows))
for _, row := range rows {
ids = append(ids, row.ID)
}
if err := r.deleteRowsByID(ctx, table, ids); err != nil {
return err
}
return r.insertRows(ctx, table, rows)
}
func (r *dorisRepository) deleteRowsByID(ctx context.Context,
table string, ids []string,
) error {
if len(ids) == 0 {
return nil
}
placeholders := make([]string, len(ids))
args := make([]any, len(ids))
for i, id := range ids {
placeholders[i] = "?"
args[i] = id
}
stmt := fmt.Sprintf("DELETE FROM `%s` WHERE %s IN (%s)",
table, fieldID, strings.Join(placeholders, ", "))
_, err := r.db.ExecContext(ctx, stmt, args...)
return err
}
func dedupeRowsByID(rows []*DorisVectorEmbedding) []*DorisVectorEmbedding {
if len(rows) < 2 {
return rows
}
out := make([]*DorisVectorEmbedding, 0, len(rows))
positions := make(map[string]int, len(rows))
for _, row := range rows {
if idx, ok := positions[row.ID]; ok {
out[idx] = row
continue
}
positions[row.ID] = len(out)
out = append(out, row)
}
return out
}
// DeleteByChunkIDList 用 chunk_id 列删除。dimension 用于定位具体表。
func (r *dorisRepository) DeleteByChunkIDList(ctx context.Context,
chunkIDList []string, dimension int, _ string,
) error {
return r.deleteByField(ctx, fieldChunkID, chunkIDList, dimension)
}
// DeleteByKnowledgeIDList 用 knowledge_id 列删除。
func (r *dorisRepository) DeleteByKnowledgeIDList(ctx context.Context,
knowledgeIDList []string, dimension int, _ string,
) error {
return r.deleteByField(ctx, fieldKnowledgeID, knowledgeIDList, dimension)
}
// DeleteBySourceIDList 用 source_id 列删除。
func (r *dorisRepository) DeleteBySourceIDList(ctx context.Context,
sourceIDList []string, dimension int, _ string,
) error {
return r.deleteByField(ctx, fieldSourceID, sourceIDList, dimension)
}
// deleteByField 是三个 Delete* 方法的统一实现:
// DELETE FROM <table> WHERE <field> IN (?, ?, ...)。
func (r *dorisRepository) deleteByField(ctx context.Context,
field string, ids []string, dimension int,
) error {
log := logger.GetLogger(ctx)
if len(ids) == 0 {
return nil
}
table := r.getTableName(dimension)
placeholders := make([]string, len(ids))
args := make([]any, len(ids))
for i, v := range ids {
placeholders[i] = "?"
args[i] = v
}
stmt := fmt.Sprintf("DELETE FROM `%s` WHERE %s IN (%s)",
table, field, strings.Join(placeholders, ", "))
if _, err := r.db.ExecContext(ctx, stmt, args...); err != nil {
log.Errorf("[Doris] Delete by %s failed: %v", field, err)
return fmt.Errorf("delete by %s: %w", field, err)
}
log.Infof("[Doris] Deleted %d rows from %s by %s", len(ids), table, field)
return nil
}
// Retrieve 根据 RetrieverType 分发到向量检索或关键词检索。
func (r *dorisRepository) Retrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
switch params.RetrieverType {
case types.VectorRetrieverType:
return r.VectorRetrieve(ctx, params)
case types.KeywordsRetrieverType:
return r.KeywordsRetrieve(ctx, params)
}
return nil, fmt.Errorf("invalid retriever type: %v", params.RetrieverType)
}
// VectorRetrieve 对查询向量先做单位化,再调用 inner_product_approximate 做
// ANN 搜索;对单位向量而言,inner product 与 cosine similarity 等价,
// 因此 score 仍然保持“越大越相似”的语义。
func (r *dorisRepository) VectorRetrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
log := logger.GetLogger(ctx)
if err := validateEmbedding(params.Embedding); err != nil {
return nil, fmt.Errorf("invalid query embedding: %w", err)
}
compatMode, err := r.resolveCompatMode(ctx)
if err != nil {
return nil, err
}
queryEmbedding := append([]float32(nil), params.Embedding...)
if compatMode.normalizeEmbeddings() {
queryEmbedding = normalizeEmbedding(queryEmbedding)
}
dim := len(params.Embedding)
table := r.getTableName(dim)
exists, err := r.tableExists(ctx, table)
if err != nil {
return nil, fmt.Errorf("check table %s: %w", table, err)
}
if !exists {
log.Warnf("[Doris] Table %s does not exist, returning empty results", table)
return buildRetrieveResult(nil, types.VectorRetrieverType), nil
}
wb := buildBaseFilter(params)
whereClause, whereArgs := wb.build()
// embedding 必须用字面量,Doris 不支持 LIMIT/OFFSET 使用占位符,必须内联为字面量。
// 使用 HAVING 是因为 score 是 SELECT 列别名,WHERE 阶段还看不到。
scoreExpr := fmt.Sprintf("inner_product_approximate(`%s`, %s)", fieldEmbedding, embeddingLiteral(queryEmbedding))
if compatMode == dorisCompatModeLegacy {
scoreExpr = fmt.Sprintf("(1 - cosine_distance_approximate(`%s`, %s))", fieldEmbedding, embeddingLiteral(queryEmbedding))
}
stmt := fmt.Sprintf(
"SELECT %s, %s AS score "+
"FROM `%s` WHERE %s "+
"HAVING score >= ? "+
"ORDER BY score DESC LIMIT %d",
strings.Join(columnsForRetrieve, ", "),
scoreExpr,
table,
whereClause,
params.TopK,
)
args := append(whereArgs, params.Threshold)
rows, err := r.db.QueryContext(ctx, stmt, args...)
if err != nil {
return nil, r.wrapVectorRetrieveError(table, compatMode, err)
}
defer rows.Close()
results, err := scanRetrieveRows(rows, types.MatchTypeEmbedding)
if err != nil {
return nil, err
}
log.Infof("[Doris] Vector retrieval found %d results in %s", len(results), table)
return buildRetrieveResult(results, types.VectorRetrieverType), nil
}
// KeywordsRetrieve 用 Doris 倒排索引 + MATCH_ANY 做关键词匹配。
//
// 不需要 jieba 客户端分词:CREATE TABLE 时 idx_content 已经声明了 chinese parser。
// 不同维度的表跨表合并取 topK,与 Milvus/Weaviate 现状一致。
func (r *dorisRepository) KeywordsRetrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
log := logger.GetLogger(ctx)
query := strings.TrimSpace(params.Query)
if query == "" {
return buildRetrieveResult(nil, types.KeywordsRetrieverType), nil
}
tables, err := r.listEmbeddingTables(ctx)
if err != nil {
return nil, fmt.Errorf("list tables: %w", err)
}
if len(tables) == 0 {
return buildRetrieveResult(nil, types.KeywordsRetrieverType), nil
}
wb := buildBaseFilter(params)
whereClause, whereArgs := wb.build()
var all []*types.IndexWithScore
for _, table := range tables {
stmt := fmt.Sprintf(
"SELECT %s FROM `%s` WHERE %s AND %s MATCH_ANY ? LIMIT %d",
strings.Join(columnsForRetrieve, ", "),
table, whereClause, fieldContent,
params.TopK,
)
args := append(append([]any{}, whereArgs...), query)
rows, err := r.db.QueryContext(ctx, stmt, args...)
if err != nil {
log.Warnf("[Doris] Keyword retrieve in %s failed: %v", table, err)
continue
}
// score 在 KeywordsRetrieve 中固定 1.0,与 Qdrant 行为一致。
batch, scanErr := scanRetrieveRows(rows, types.MatchTypeKeywords)
_ = rows.Close()
if scanErr != nil {
return nil, scanErr
}
all = append(all, batch...)
}
if len(all) > params.TopK {
all = all[:params.TopK]
}
log.Infof("[Doris] Keywords retrieval found %d results across %d tables", len(all), len(tables))
return buildRetrieveResult(all, types.KeywordsRetrieverType), nil
}
// CopyIndices 把源知识库的 chunk 复制到目标知识库,避免重新生成 embedding。
//
// 与 Qdrant 的实现完全镜像:
// - 分页扫描源表
// - 按 sourceToTargetChunkIDMap 把 chunk_id 翻译过去
// - 处理 source_id 翻译规则(普通 chunk / 生成型问题 / 其他)
// - 把目标行写回同一个表
func (r *dorisRepository) CopyIndices(ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
_ string,
) error {
log := logger.GetLogger(ctx)
if len(sourceToTargetChunkIDMap) == 0 {
return nil
}
if err := r.ensureTable(ctx, dimension); err != nil {
return err
}
table := r.getTableName(dimension)
const pageSize = 64
offset := 0
totalCopied := 0
for {
stmt := fmt.Sprintf(
"SELECT %s FROM `%s` WHERE %s = ? ORDER BY %s LIMIT %d OFFSET %d",
strings.Join(columnsForCopy, ", "),
table, fieldKnowledgeBaseID, fieldID,
pageSize, offset,
)
rows, err := r.db.QueryContext(ctx, stmt, sourceKnowledgeBaseID)
if err != nil {
return fmt.Errorf("copy indices scan: %w", err)
}
batch, err := scanCopyRows(rows)
_ = rows.Close()
if err != nil {
return err
}
if len(batch) == 0 {
break
}
var targets []*DorisVectorEmbedding
for _, src := range batch {
targetChunkID, ok := sourceToTargetChunkIDMap[src.ChunkID]
if !ok {
log.Warnf("[Doris] Source chunk %s not in target mapping", src.ChunkID)
continue
}
targetKnowledgeID, ok := sourceToTargetKBIDMap[src.KnowledgeID]
if !ok {
log.Warnf("[Doris] Source knowledge %s not in target mapping", src.KnowledgeID)
continue
}
targetSourceID := translateSourceID(src.SourceID, src.ChunkID, targetChunkID)
targets = append(targets, &DorisVectorEmbedding{
ID: uuid.New().String(),
Content: src.Content,
SourceID: targetSourceID,
SourceType: src.SourceType,
ChunkID: targetChunkID,
KnowledgeID: targetKnowledgeID,
KnowledgeBaseID: targetKnowledgeBaseID,
TagID: src.TagID,
IsEnabled: src.IsEnabled,
Embedding: src.Embedding,
})
}
if len(targets) > 0 {
if err := r.insertRows(ctx, table, targets); err != nil {
return fmt.Errorf("copy indices insert: %w", err)
}
totalCopied += len(targets)
}
if len(batch) < pageSize {
break
}
offset += pageSize
}
log.Infof("[Doris] CopyIndices done, dim=%d, copied=%d", dimension, totalCopied)
return nil
}
// BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID 实际实现位于 streamload.go,
// 会按 compat mode 选择 partial update 或 rewrite rows。
// ---------------------------------------------------------------------------
// 私有辅助
// ---------------------------------------------------------------------------
// toDorisVectorEmbedding 把 IndexInfo + 上层传入的 embedding 映射 转换为
// Doris 行模型。Embedding 通过 additionalParams[fieldEmbedding] 中的
// map[string][]float32 按 SourceID 取出,与 Qdrant/Milvus 完全一致。
// inner_product_duplicate 模式会先单位化,legacy 模式保留原始向量。
func toDorisVectorEmbedding(
info *types.IndexInfo,
additionalParams map[string]any,
compatMode dorisCompatMode,
) *DorisVectorEmbedding {
emb := &DorisVectorEmbedding{
ID: info.ID,
Content: info.Content,
SourceID: info.SourceID,
SourceType: int(info.SourceType),
ChunkID: info.ChunkID,
KnowledgeID: info.KnowledgeID,
KnowledgeBaseID: info.KnowledgeBaseID,
TagID: info.TagID,
IsEnabled: info.IsEnabled,
}
if additionalParams != nil {
if v, ok := additionalParams[fieldEmbedding]; ok {
if m, ok := v.(map[string][]float32); ok {
emb.Embedding = append([]float32(nil), m[info.SourceID]...)
if compatMode.normalizeEmbeddings() {
emb.Embedding = normalizeEmbedding(emb.Embedding)
}
}
}
}
return emb
}
func (r *dorisRepository) wrapVectorRetrieveError(table string, compatMode dorisCompatMode, err error) error {
if compatMode == dorisCompatModeLegacy {
return fmt.Errorf(
"vector retrieve %s in Doris compat mode %s: %w. If your Doris build does not support cosine_distance_approximate or ANN on UNIQUE KEY tables, set %s=%s before creating embedding tables. %s is not interchangeable after %s_* tables are created",
table,
compatMode,
err,
envDorisCompatMode,
dorisCompatModeInnerProductDuplicate,
envDorisCompatMode,
r.tableBaseName,
)
}
return fmt.Errorf("vector retrieve %s in Doris compat mode %s: %w", table, compatMode, err)
}
// translateSourceID 把源 SourceID 翻译到目标 SourceID,与 Qdrant 实现完全镜像:
// - 普通 chunk:SourceID == ChunkID -> 使用 targetChunkID
// - 生成型问题:SourceID == "<chunkID>-<questionID>" -> "<targetChunkID>-<questionID>"
// - 其他场景:生成新的 UUID(保持唯一性)
func translateSourceID(originalSourceID, sourceChunkID, targetChunkID string) string {
switch {
case originalSourceID == sourceChunkID:
return targetChunkID
case strings.HasPrefix(originalSourceID, sourceChunkID+"-"):
questionID := strings.TrimPrefix(originalSourceID, sourceChunkID+"-")
return fmt.Sprintf("%s-%s", targetChunkID, questionID)
default:
return uuid.New().String()
}
}
// scanRetrieveRows 把 Retrieve 阶段的 rows 反序列化为 IndexWithScore 列表。
//
// 分两路:
// - 列数 == columnsForRetrieve+1:第 N+1 列是 score(向量检索路径)
// - 列数 == columnsForRetrieve:score 统一赋 1.0(关键词检索路径)
func scanRetrieveRows(rows *sql.Rows, matchType types.MatchType) ([]*types.IndexWithScore, error) {
cols, err := rows.Columns()
if err != nil {
return nil, err
}
withScore := len(cols) == len(columnsForRetrieve)+1
var out []*types.IndexWithScore
for rows.Next() {
var (
id, content, sourceID, chunkID string
knowledgeID, knowledgeBaseID, tagID string
sourceType int
isEnabled bool
score float64
err error
)
if withScore {
err = rows.Scan(&id, &content, &sourceID, &sourceType,
&chunkID, &knowledgeID, &knowledgeBaseID, &tagID, &isEnabled, &score)
} else {
err = rows.Scan(&id, &content, &sourceID, &sourceType,
&chunkID, &knowledgeID, &knowledgeBaseID, &tagID, &isEnabled)
score = 1.0
}
if err != nil {
return nil, fmt.Errorf("scan row: %w", err)
}
out = append(out, &types.IndexWithScore{
ID: id,
Content: content,
SourceID: sourceID,
SourceType: types.SourceType(sourceType),
ChunkID: chunkID,
KnowledgeID: knowledgeID,
KnowledgeBaseID: knowledgeBaseID,
TagID: tagID,
Score: score,
MatchType: matchType,
})
}
return out, rows.Err()
}
// scanCopyRows 反序列化 CopyIndices 的分页查询结果。
//
// 与 scanRetrieveRows 不同,这里需要 embedding 字段(去复制原始向量)。
// Doris 的 ARRAY<FLOAT> 通过 mysql 协议返回的是字符串字面量 "[1,2,3]"。
func scanCopyRows(rows *sql.Rows) ([]*DorisVectorEmbedding, error) {
var out []*DorisVectorEmbedding
for rows.Next() {
var (
id, content, sourceID, chunkID string
knowledgeID, knowledgeBaseID, tagID string
sourceType int
isEnabled bool
embeddingRaw sql.RawBytes
)
if err := rows.Scan(&id, &content, &sourceID, &sourceType,
&chunkID, &knowledgeID, &knowledgeBaseID, &tagID, &isEnabled, &embeddingRaw); err != nil {
return nil, fmt.Errorf("scan copy row: %w", err)
}
vec, err := parseEmbeddingLiteral(embeddingRaw)
if err != nil {
return nil, fmt.Errorf("parse embedding: %w", err)
}
out = append(out, &DorisVectorEmbedding{
ID: id,
Content: content,
SourceID: sourceID,
SourceType: sourceType,
ChunkID: chunkID,
KnowledgeID: knowledgeID,
KnowledgeBaseID: knowledgeBaseID,
TagID: tagID,
IsEnabled: isEnabled,
Embedding: vec,
})
}
return out, rows.Err()
}
// buildRetrieveResult 把 IndexWithScore 列表包装成 RetrieveResult。
func buildRetrieveResult(results []*types.IndexWithScore, retrieverType types.RetrieverType) []*types.RetrieveResult {
return []*types.RetrieveResult{{
Results: results,
RetrieverEngineType: types.DorisRetrieverEngineType,
RetrieverType: retrieverType,
Error: nil,
}}
}
// calculateStorageSize 估算单行的存储成本。
//
// 与 Qdrant 一致:payload 字符串字节 + 向量 (dim*4) + HNSW M*2*8 + 元数据 24。
func calculateStorageSize(emb *DorisVectorEmbedding) int64 {
var payload int64
payload += int64(len(emb.Content))
payload += int64(len(emb.SourceID))
payload += int64(len(emb.ChunkID))
payload += int64(len(emb.KnowledgeID))
payload += int64(len(emb.KnowledgeBaseID))
payload += int64(len(emb.TagID))
payload += 8 // source_type int
var vec int64
var hnsw int64
if len(emb.Embedding) > 0 {
vec = int64(len(emb.Embedding)) * 4
const hnswM = 32
hnsw = hnswM * 2 * 8
}
const metaBytes int64 = 24
return payload + vec + hnsw + metaBytes
}
@@ -0,0 +1,807 @@
package doris
import (
"context"
"database/sql"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// newTestRepo 构造一个共享 sqlmock 的 dorisRepository,
// 默认绕过 ensureTable(initializedTables 已置位),便于专注测试 SQL 形态。
//
// 返回的 cleanup 用 defer 调用即可。
func newTestRepo(t *testing.T) (*dorisRepository, sqlmock.Sqlmock, *httptest.Server, func()) {
t.Helper()
// httptest binds to loopback, which production SSRF policy correctly blocks.
// Make that one test host explicit and restore the process-global policy when
// the test completes.
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 默认行为:成功,回 1 行。
body, _ := io.ReadAll(r.Body)
_ = body
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"Status": "Success",
"NumberTotalRows": 1,
"NumberLoadedRows": 1,
"Label": "test",
})
}))
repo := &dorisRepository{
db: db,
httpClient: srv.Client(),
feHTTPBase: srv.URL,
username: "u",
password: "p",
database: "academy",
tableBaseName: "academy_embeddings",
}
cleanup := func() {
_ = db.Close()
srv.Close()
}
return repo, mock, srv, cleanup
}
func primeCompatMode(repo *dorisRepository, mode dorisCompatMode, err error) {
repo.compatModeResolved = mode
repo.compatResolveErr = err
repo.compatResolveOnce.Do(func() {})
}
// ---------------------------------------------------------------------------
// query.go:whereBuilder / embeddingLiteral / parseEmbeddingLiteral
// ---------------------------------------------------------------------------
func TestEmbeddingLiteralRoundTrip(t *testing.T) {
t.Run("empty vector returns []", func(t *testing.T) {
assert.Equal(t, "[]", embeddingLiteral(nil))
assert.Equal(t, "[]", embeddingLiteral([]float32{}))
})
t.Run("does not contain locale-sensitive separators", func(t *testing.T) {
s := embeddingLiteral([]float32{1.5, -2.25, 0.001})
// 必须只包含数字 / 点 / 负号 / e / 逗号 / 方括号
assert.Regexp(t, regexp.MustCompile(`^\[[\-+0-9eE.,]+\]$`), s)
})
t.Run("round trip", func(t *testing.T) {
orig := []float32{1.5, -2.25, 0.0625}
s := embeddingLiteral(orig)
got, err := parseEmbeddingLiteral([]byte(s))
require.NoError(t, err)
assert.Equal(t, orig, got)
})
t.Run("parse handles whitespace and missing brackets", func(t *testing.T) {
v, err := parseEmbeddingLiteral([]byte(" 1.0 , 2.0 ,3.0 "))
require.NoError(t, err)
assert.Equal(t, []float32{1.0, 2.0, 3.0}, v)
})
}
func TestWhereBuilder(t *testing.T) {
t.Run("empty builder returns 1 = 1", func(t *testing.T) {
w := &whereBuilder{}
clause, args := w.build()
assert.Equal(t, "1 = 1", clause)
assert.Nil(t, args)
})
t.Run("equal + IN + NOT IN", func(t *testing.T) {
w := &whereBuilder{}
w.addEqual("is_enabled", true)
w.addIn("knowledge_base_id", []string{"kb1", "kb2"})
w.addNotIn("chunk_id", []string{"x"})
clause, args := w.build()
assert.Contains(t, clause, "is_enabled = ?")
assert.Contains(t, clause, "knowledge_base_id IN (?, ?)")
assert.Contains(t, clause, "chunk_id NOT IN (?)")
assert.Equal(t, []any{true, "kb1", "kb2", "x"}, args)
})
t.Run("buildBaseFilter applies all params", func(t *testing.T) {
w := buildBaseFilter(types.RetrieveParams{
KnowledgeBaseIDs: []string{"kb1"},
KnowledgeIDs: []string{"k1", "k2"},
TagIDs: []string{"t1"},
ExcludeKnowledgeIDs: []string{"k9"},
ExcludeChunkIDs: []string{"c9"},
})
clause, _ := w.build()
assert.Contains(t, clause, "is_enabled = ?")
assert.Contains(t, clause, "knowledge_base_id IN (?)")
assert.Contains(t, clause, "knowledge_id IN (?, ?)")
assert.Contains(t, clause, "tag_id IN (?)")
assert.Contains(t, clause, "knowledge_id NOT IN (?)")
assert.Contains(t, clause, "chunk_id NOT IN (?)")
})
}
// ---------------------------------------------------------------------------
// streamload.go:chunkRows / partialUpdateRows
// ---------------------------------------------------------------------------
func TestChunkRows(t *testing.T) {
rows := []map[string]any{
{"id": "a", "is_enabled": true},
{"id": "b", "is_enabled": false},
{"id": "c", "is_enabled": true},
}
t.Run("single batch when fits", func(t *testing.T) {
batches := chunkRows(rows, 4096)
require.Len(t, batches, 1)
assert.Len(t, batches[0], 3)
})
t.Run("splits when exceeding maxBytes", func(t *testing.T) {
// 给一个非常小的上限,强制每行单独成段
batches := chunkRows(rows, 16)
assert.GreaterOrEqual(t, len(batches), 2)
var total int
for _, b := range batches {
total += len(b)
}
assert.Equal(t, len(rows), total)
})
}
func TestPartialUpdateRows_HappyPath(t *testing.T) {
repo, _, _, cleanup := newTestRepo(t)
defer cleanup()
// 自定义 server 验证请求形态。
var captured *http.Request
var capturedBody []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
captured = r
capturedBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"Status": "Success",
"NumberTotalRows": 2,
"NumberLoadedRows": 2,
"Label": "ok",
})
}))
defer srv.Close()
repo.feHTTPBase = srv.URL
rows := []map[string]any{
{"id": "id1", "is_enabled": true},
{"id": "id2", "is_enabled": false},
}
require.NoError(t, repo.partialUpdateRows(context.Background(),
"academy_embeddings_768", []string{"id", "is_enabled"}, rows))
require.NotNil(t, captured)
assert.Equal(t, http.MethodPut, captured.Method)
assert.Equal(t, "/api/academy/academy_embeddings_768/_stream_load", captured.URL.Path)
assert.Equal(t, "true", captured.Header.Get("partial_columns"))
assert.Equal(t, "true", captured.Header.Get("strip_outer_array"))
assert.Equal(t, "json", captured.Header.Get("format"))
assert.Equal(t, "id,is_enabled", captured.Header.Get("columns"))
assert.Equal(t, "APPEND", captured.Header.Get("merge_type"))
assert.True(t, strings.HasPrefix(captured.Header.Get("Authorization"), "Basic "))
var got []map[string]any
require.NoError(t, json.Unmarshal(capturedBody, &got))
assert.Len(t, got, 2)
assert.Equal(t, "id1", got[0]["id"])
}
func TestPartialUpdateRows_FailureSurfaced(t *testing.T) {
repo, _, _, cleanup := newTestRepo(t)
defer cleanup()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"Status": "Fail",
"Message": "label exists",
"ErrorURL": "http://...",
})
}))
defer srv.Close()
repo.feHTTPBase = srv.URL
err := repo.partialUpdateRows(context.Background(),
"t", []string{"id", "is_enabled"},
[]map[string]any{{"id": "x", "is_enabled": true}},
)
require.Error(t, err)
assert.Contains(t, err.Error(), "stream load failed")
}
func TestStreamLoadOnce_BlocksUnsafeTarget(t *testing.T) {
repo, _, _, cleanup := newTestRepo(t)
defer cleanup()
// Override the helper's loopback allowance: link-local metadata endpoints
// must be rejected before the HTTP client is called.
secutils.SetSSRFWhitelistFromRaw("")
repo.feHTTPBase = "http://169.254.169.254"
err := repo.streamLoadOnce(context.Background(), "t", []string{"id"},
[]map[string]any{{"id": "x"}})
require.Error(t, err)
assert.Contains(t, err.Error(), "blocked by SSRF validation")
}
func TestDorisStreamLoadHTTPClient_BlocksUnsafeRedirect(t *testing.T) {
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data", http.StatusTemporaryRedirect)
}))
defer server.Close()
req, err := http.NewRequest(http.MethodPut, server.URL, strings.NewReader("[]"))
require.NoError(t, err)
_, err = newDorisStreamLoadHTTPClient().Do(req)
require.Error(t, err)
assert.ErrorIs(t, err, secutils.ErrSSRFRedirectBlocked)
}
func TestDorisStreamLoadHTTPClient_ForwardsAuthorizationToTrustedRedirect(t *testing.T) {
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
var gotAuthorization, gotBody, gotColumns, gotMethod string
be := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuthorization = r.Header.Get(headerAuthorization)
gotColumns = r.Header.Get("columns")
gotMethod = r.Method
body, err := io.ReadAll(r.Body)
assert.NoError(t, err)
gotBody = string(body)
w.WriteHeader(http.StatusOK)
}))
defer be.Close()
fe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, be.URL, http.StatusTemporaryRedirect)
}))
defer fe.Close()
req, err := http.NewRequest(http.MethodPut, fe.URL, strings.NewReader("[]"))
require.NoError(t, err)
req.Header.Set(headerAuthorization, "Basic trusted-doris-credential")
req.Header.Set("columns", "id,content")
resp, err := newDorisStreamLoadHTTPClient().Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, "Basic trusted-doris-credential", gotAuthorization)
assert.Equal(t, "[]", gotBody)
assert.Equal(t, "id,content", gotColumns)
assert.Equal(t, http.MethodPut, gotMethod)
}
func TestDorisStreamLoadHTTPClient_RedirectBoundaries(t *testing.T) {
for _, tc := range []struct {
name, source, target, whitelist string
}{
{"untrusted port", "https://8.8.8.8:8030/load", "https://8.8.8.8:8040/load", ""},
{"untrusted host", "https://8.8.8.8/load", "https://1.1.1.1/load", ""},
{"HTTPS downgrade", "https://127.0.0.1:8030/load", "http://127.0.0.1:8040/load", "127.0.0.1"},
{"invalid scheme", "http://127.0.0.1/load", "ftp://127.0.0.1/load", "127.0.0.1"},
} {
t.Run(tc.name, func(t *testing.T) {
secutils.SetSSRFWhitelistFromRaw(tc.whitelist)
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
source, err := http.NewRequest(http.MethodPut, tc.source, strings.NewReader("[]"))
require.NoError(t, err)
source.Header.Set(headerAuthorization, "Basic trusted-doris-credential")
target, err := http.NewRequest(http.MethodPut, tc.target, strings.NewReader("[]"))
require.NoError(t, err)
err = newDorisStreamLoadHTTPClient().CheckRedirect(target, []*http.Request{source})
require.ErrorIs(t, err, secutils.ErrSSRFRedirectBlocked)
assert.Empty(t, target.Header.Get(headerAuthorization))
})
}
}
func TestDorisStreamLoadHTTPClient_RedirectLimit(t *testing.T) {
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
req, err := http.NewRequest(http.MethodPut, "http://127.0.0.1/load", strings.NewReader("[]"))
require.NoError(t, err)
via := make([]*http.Request, secutils.DefaultSSRFSafeHTTPClientConfig().MaxRedirects)
for i := range via {
via[i] = req
}
require.ErrorContains(t, newDorisStreamLoadHTTPClient().CheckRedirect(req, via), "stopped after")
}
// ---------------------------------------------------------------------------
// repository.go:SQL 形态
// ---------------------------------------------------------------------------
func TestDeleteByChunkIDList_SQLShape(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
mock.ExpectExec(`DELETE FROM .*academy_embeddings_768.* WHERE chunk_id IN \(\?, \?\)`).
WithArgs("c1", "c2").
WillReturnResult(sqlmock.NewResult(0, 2))
err := repo.DeleteByChunkIDList(context.Background(), []string{"c1", "c2"}, 768, "")
require.NoError(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestDeleteByKnowledgeIDList_NoOpOnEmpty(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
require.NoError(t, repo.DeleteByKnowledgeIDList(context.Background(), nil, 768, ""))
// 空列表不应触发任何 query
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestVectorRetrieve_SQLShape(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings_3").
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(1))
// Doris does not support placeholders for LIMIT, so TopK is inlined as a
// literal and is not a bound argument.
mock.ExpectQuery(`SELECT id, content, .*inner_product_approximate.*HAVING score >= \? ORDER BY score DESC LIMIT \d+`).
WithArgs(true, 0.5).
WillReturnRows(
sqlmock.NewRows([]string{
"id", "content", "source_id", "source_type",
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
"is_enabled", "score",
}).AddRow("id1", "hello", "src", 0, "c1", "k1", "kb1", "t1", true, 0.95),
)
results, err := repo.VectorRetrieve(context.Background(), types.RetrieveParams{
Embedding: []float32{1, 2, 3},
TopK: 5,
Threshold: 0.5,
RetrieverType: types.VectorRetrieverType,
})
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 1)
assert.Equal(t, "id1", results[0].Results[0].ID)
assert.InDelta(t, 0.95, results[0].Results[0].Score, 1e-9)
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestVectorRetrieve_SQLShape_LegacyMode(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
primeCompatMode(repo, dorisCompatModeLegacy, nil)
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings_3").
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(1))
mock.ExpectQuery(`SELECT id, content, .*cosine_distance_approximate.*HAVING score >= \? ORDER BY score DESC LIMIT \d+`).
WithArgs(true, 0.5).
WillReturnRows(
sqlmock.NewRows([]string{
"id", "content", "source_id", "source_type",
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
"is_enabled", "score",
}).AddRow("id1", "hello", "src", 0, "c1", "k1", "kb1", "t1", true, 0.8),
)
results, err := repo.VectorRetrieve(context.Background(), types.RetrieveParams{
Embedding: []float32{1, 2, 3},
TopK: 5,
Threshold: 0.5,
RetrieverType: types.VectorRetrieverType,
})
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 1)
assert.Equal(t, "id1", results[0].Results[0].ID)
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestNormalizeEmbedding(t *testing.T) {
t.Run("returns unit vector copy", func(t *testing.T) {
got := normalizeEmbedding([]float32{3, 4})
require.Len(t, got, 2)
assert.InDelta(t, 0.6, got[0], 1e-6)
assert.InDelta(t, 0.8, got[1], 1e-6)
})
t.Run("keeps zero vector finite", func(t *testing.T) {
got := normalizeEmbedding([]float32{0, 0})
require.Len(t, got, 2)
assert.Equal(t, []float32{0, 0}, got)
})
}
func TestKeywordsRetrieve_SQLShape(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings\\_%").
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).
AddRow("academy_embeddings_768"))
// LIMIT is inlined (see VectorRetrieve), so only is_enabled and the
// MATCH_ANY query string are bound arguments.
mock.ExpectQuery(`MATCH_ANY \?`).
WithArgs(true, "你好").
WillReturnRows(
sqlmock.NewRows([]string{
"id", "content", "source_id", "source_type",
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
"is_enabled",
}).AddRow("id1", "你好世界", "src", 0, "c1", "k1", "kb1", "", true),
)
results, err := repo.KeywordsRetrieve(context.Background(), types.RetrieveParams{
Query: "你好",
TopK: 3,
RetrieverType: types.KeywordsRetrieverType,
})
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 1)
assert.Equal(t, "id1", results[0].Results[0].ID)
assert.Equal(t, 1.0, results[0].Results[0].Score)
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestBatchUpdateChunkEnabledStatus_RewritesRows(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
defer db.Close()
repo := &dorisRepository{
db: db,
database: "academy",
tableBaseName: "academy_embeddings",
}
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings\\_%").
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).AddRow("academy_embeddings_768"))
mock.ExpectQuery(`SELECT id, content, source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id, is_enabled, embedding FROM .*academy_embeddings_768.* WHERE chunk_id IN`).
WithArgs("c1").
WillReturnRows(sqlmock.NewRows([]string{
"id", "content", "source_id", "source_type",
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
"is_enabled", "embedding",
}).AddRow("row-1", "hello", "src1", 0, "c1", "k1", "kb1", "t1", true, "[1,2,3]"))
mock.ExpectExec(`DELETE FROM .*academy_embeddings_768.* WHERE id IN \(\?\)`).
WithArgs("row-1").
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectExec(`INSERT INTO .*academy_embeddings_768.*VALUES \(\?, \?, \?, \?, \?, \?, \?, \?, \?, \[`).
WithArgs("row-1", "hello", "src1", 0, "c1", "k1", "kb1", "t1", false).
WillReturnResult(sqlmock.NewResult(0, 1))
require.NoError(t, repo.BatchUpdateChunkEnabledStatus(
context.Background(), map[string]bool{"c1": false}))
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestBatchUpdateChunkEnabledStatus_LegacyModeUsesPartialUpdate(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
primeCompatMode(repo, dorisCompatModeLegacy, nil)
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings\\_%").
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).AddRow("academy_embeddings_768"))
mock.ExpectQuery(`SELECT id, chunk_id FROM .*academy_embeddings_768.* WHERE chunk_id IN`).
WithArgs("c1").
WillReturnRows(sqlmock.NewRows([]string{"id", "chunk_id"}).AddRow("row-1", "c1"))
require.NoError(t, repo.BatchUpdateChunkEnabledStatus(
context.Background(), map[string]bool{"c1": false}))
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestEnsureTable_DDLShape(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
defer db.Close()
repo := &dorisRepository{
db: db,
database: "academy",
tableBaseName: "academy_embeddings",
bucketsNum: 5,
replicationNum: 2,
}
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
// 表不存在
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings_768").
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(0))
// CREATE TABLE 应包含关键属性和 Doris 支持的 inner_product ANN metric
mock.ExpectExec(`CREATE TABLE IF NOT EXISTS .*academy_embeddings_768.*metric_type"="inner_product".*DUPLICATE KEY\(id\).*BUCKETS 5.*replication_num.*=.*2`).
WillReturnResult(sqlmock.NewResult(0, 0))
// SHOW INDEX 一次即返回 ANN 已 FINISHED
mock.ExpectQuery(`SHOW INDEX FROM .*academy_embeddings_768.*`).
WillReturnRows(
sqlmock.NewRows([]string{"Table", "Key_name", "State"}).
AddRow("academy_embeddings_768", "idx_emb", "FINISHED"),
)
require.NoError(t, repo.ensureTable(context.Background(), 768))
// waitANNReady 在后台 goroutine 里执行,轮询 ExpectationsWereMet 直到 SHOW INDEX 也被消费。
require.Eventually(t, func() bool {
return mock.ExpectationsWereMet() == nil
}, 2*time.Second, 10*time.Millisecond, "expectations should be met after async ANN poll")
}
func TestEnsureTable_DDLShape_LegacyMode(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
defer db.Close()
repo := &dorisRepository{
db: db,
database: "academy",
tableBaseName: "academy_embeddings",
bucketsNum: 5,
replicationNum: 2,
}
primeCompatMode(repo, dorisCompatModeLegacy, nil)
mock.ExpectQuery(`SELECT COUNT\(1\) FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings_768").
WillReturnRows(sqlmock.NewRows([]string{"c"}).AddRow(0))
mock.ExpectExec(`CREATE TABLE IF NOT EXISTS .*academy_embeddings_768.*metric_type"="cosine_distance".*UNIQUE KEY\(id\).*enable_unique_key_merge_on_write.*true`).
WillReturnResult(sqlmock.NewResult(0, 0))
mock.ExpectQuery(`SHOW INDEX FROM .*academy_embeddings_768.*`).
WillReturnRows(
sqlmock.NewRows([]string{"Table", "Key_name", "State"}).
AddRow("academy_embeddings_768", "idx_emb", "FINISHED"),
)
require.NoError(t, repo.ensureTable(context.Background(), 768))
require.Eventually(t, func() bool {
return mock.ExpectationsWereMet() == nil
}, 2*time.Second, 10*time.Millisecond, "expectations should be met after async ANN poll")
}
func TestBatchSave_SQLShape(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
defer db.Close()
repo := &dorisRepository{
db: db,
database: "academy",
tableBaseName: "academy_embeddings",
}
primeCompatMode(repo, dorisCompatModeInnerProductDuplicate, nil)
repo.initializedTables.Store(3, true) // 跳过 ensureTable
mock.ExpectExec(`DELETE FROM .*academy_embeddings_3.* WHERE id IN \(\?\)`).
WithArgs("src1").
WillReturnResult(sqlmock.NewResult(0, 0))
mock.ExpectExec(`INSERT INTO .*academy_embeddings_3.*VALUES \(\?, \?, \?, \?, \?, \?, \?, \?, \?, \[`).
WithArgs(
"src1", "hello", "src1", 0,
"c1", "k1", "kb1", "",
true,
).
WillReturnResult(sqlmock.NewResult(0, 1))
err = repo.BatchSave(context.Background(),
[]*types.IndexInfo{{
Content: "hello",
SourceID: "src1",
ChunkID: "c1",
KnowledgeID: "k1",
KnowledgeBaseID: "kb1",
IsEnabled: true,
}},
map[string]any{
fieldEmbedding: map[string][]float32{
"src1": {1, 2, 3},
},
},
)
require.NoError(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestBatchSave_SQLShape_LegacyMode(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
defer db.Close()
repo := &dorisRepository{
db: db,
database: "academy",
tableBaseName: "academy_embeddings",
}
primeCompatMode(repo, dorisCompatModeLegacy, nil)
repo.initializedTables.Store(3, true)
mock.ExpectExec(`INSERT INTO .*academy_embeddings_3.*VALUES \(\?, \?, \?, \?, \?, \?, \?, \?, \?, \[`).
WithArgs(
"src1", "hello", "src1", 0,
"c1", "k1", "kb1", "",
true,
).
WillReturnResult(sqlmock.NewResult(0, 1))
err = repo.BatchSave(context.Background(),
[]*types.IndexInfo{{
Content: "hello",
SourceID: "src1",
ChunkID: "c1",
KnowledgeID: "k1",
KnowledgeBaseID: "kb1",
IsEnabled: true,
}},
map[string]any{
fieldEmbedding: map[string][]float32{
"src1": {1, 2, 3},
},
},
)
require.NoError(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestResolveCompatMode_RejectsExistingModeSwitch(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
repo.compatModeRequested = dorisCompatModeLegacy
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings\\_%").
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}).AddRow("academy_embeddings_768"))
mock.ExpectQuery(`SHOW CREATE TABLE .*academy_embeddings_768.*`).
WillReturnRows(sqlmock.NewRows([]string{"Table", "Create Table"}).AddRow(
"academy_embeddings_768",
"CREATE TABLE `academy_embeddings_768` (id VARCHAR(64)) ENGINE=OLAP DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 10 PROPERTIES(\"replication_num\"=\"1\")",
))
_, err := repo.resolveCompatMode(context.Background())
require.Error(t, err)
assert.Contains(t, err.Error(), "not interchangeable after academy_embeddings_*")
assert.Contains(t, err.Error(), string(dorisCompatModeInnerProductDuplicate))
assert.NoError(t, mock.ExpectationsWereMet())
}
func TestResolveCompatMode_AutoPrefersInnerProductDuplicate(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
repo.compatModeRequested = dorisCompatModeAuto
mock.ExpectQuery(`SELECT TABLE_NAME FROM information_schema.tables`).
WithArgs("academy", "academy_embeddings\\_%").
WillReturnRows(sqlmock.NewRows([]string{"TABLE_NAME"}))
mock.ExpectQuery(`SELECT inner_product_approximate\(\[1.0\],\[1.0\]\)`).
WillReturnRows(sqlmock.NewRows([]string{"v"}).AddRow(1.0))
mock.ExpectQuery(`SELECT cosine_distance_approximate\(\[1.0\],\[1.0\]\)`).
WillReturnError(errors.New("unsupported"))
mode, err := repo.resolveCompatMode(context.Background())
require.NoError(t, err)
assert.Equal(t, dorisCompatModeInnerProductDuplicate, mode)
assert.NoError(t, mock.ExpectationsWereMet())
}
// ---------------------------------------------------------------------------
// Engine wiring
// ---------------------------------------------------------------------------
func TestEngineTypeAndSupport(t *testing.T) {
repo, _, _, cleanup := newTestRepo(t)
defer cleanup()
assert.Equal(t, types.DorisRetrieverEngineType, repo.EngineType())
supports := repo.Support()
assert.Contains(t, supports, types.KeywordsRetrieverType)
assert.Contains(t, supports, types.VectorRetrieverType)
}
func TestRetrieve_DispatchesByType(t *testing.T) {
repo, mock, _, cleanup := newTestRepo(t)
defer cleanup()
// invalid retriever type -> error,不会触发任何 SQL
_, err := repo.Retrieve(context.Background(), types.RetrieveParams{
RetrieverType: "unknown",
})
require.Error(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
}
// ---------------------------------------------------------------------------
// regression / utility
// ---------------------------------------------------------------------------
func TestTranslateSourceID(t *testing.T) {
t.Run("plain chunk uses target chunk", func(t *testing.T) {
got := translateSourceID("c1", "c1", "tc1")
assert.Equal(t, "tc1", got)
})
t.Run("generated question preserves question id", func(t *testing.T) {
got := translateSourceID("c1-q9", "c1", "tc1")
assert.Equal(t, "tc1-q9", got)
})
t.Run("unrecognized source falls back to fresh uuid", func(t *testing.T) {
got := translateSourceID("totally-other", "c1", "tc1")
assert.NotEqual(t, "totally-other", got)
assert.Len(t, got, 36) // UUID 长度
})
}
func TestEstimateStorageSize(t *testing.T) {
repo, _, _, cleanup := newTestRepo(t)
defer cleanup()
out := repo.EstimateStorageSize(context.Background(),
[]*types.IndexInfo{{Content: "hello", ChunkID: "c1", KnowledgeID: "k1", KnowledgeBaseID: "kb1"}},
map[string]any{
fieldEmbedding: map[string][]float32{
"": {1, 2, 3},
},
},
)
assert.Greater(t, out, int64(0))
}
// 保证 *sql.Rows 错误不会被吞掉。
func TestScanRetrieveRows_Error(t *testing.T) {
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
mock.ExpectQuery("SELECT 1").
WillReturnError(errors.New("boom"))
rows, err := db.Query("SELECT 1")
if err != nil {
// query 直接失败也算预期
assert.Equal(t, "boom", err.Error())
return
}
_, scanErr := scanRetrieveRows(rows, types.MatchTypeEmbedding)
if scanErr != nil {
assert.Error(t, scanErr)
}
}
// silence unused import warning when sql isn't directly used
var _ = sql.ErrNoRows
@@ -0,0 +1,310 @@
package doris
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/logger"
)
// 默认的桶数 / 副本数。Doris 在 PROPERTIES 不指定时会用集群默认值,
// 这里给一个对单机/小集群更友好的保守值。
const (
defaultBucketsNum = 10
defaultReplicationNum = 1
// ANN 索引就绪轮询的最大等待时间。索引未就绪不阻塞写入路径,
// 只阻塞 ensureTable 自身(首次建表场景),所以 30s 是可接受的。
annReadyTimeout = 30 * time.Second
annReadyPoll = 1 * time.Second
)
// getTableName 返回某个维度对应的物理表名:<base>_<dim>。
//
// 与 Qdrant/Milvus/Weaviate 的 collection 命名约定一致,
// 这样不同 embedding 模型(不同维度)的数据互不冲突。
func (r *dorisRepository) getTableName(dimension int) string {
return fmt.Sprintf("%s_%d", r.tableBaseName, dimension)
}
// ensureTable 保证目标维度对应的表已经存在;
// 不存在则用 CREATE TABLE IF NOT EXISTS 创建,并在创建后轮询 ANN 索引就绪。
//
// 该方法在每次 Save / BatchSave 之前调用,结果缓存在 initializedTables 中,
// 同一进程内同一 dimension 只会真正打一次 SHOW TABLES + DDL。
func (r *dorisRepository) ensureTable(ctx context.Context, dimension int) error {
if _, ok := r.initializedTables.Load(dimension); ok {
return nil
}
compatMode, err := r.resolveCompatMode(ctx)
if err != nil {
return err
}
log := logger.GetLogger(ctx)
tableName := r.getTableName(dimension)
exists, err := r.tableExists(ctx, tableName)
if err != nil {
log.Errorf("[Doris] Failed to check table existence: %v", err)
return fmt.Errorf("check table existence: %w", err)
}
if !exists {
log.Infof("[Doris] Creating table %s with dimension %d in compat mode %s", tableName, dimension, compatMode)
if err := r.createTable(ctx, tableName, dimension, compatMode); err != nil {
log.Errorf("[Doris] Failed to create table: %v", err)
return fmt.Errorf("create table: %w", err)
}
// ANN 索引在 Doris 端异步构建。这里在后台 goroutine 里轮询就绪,
// 写入路径不阻塞——索引未就绪期间检索会退化为 brute-force(结果对、速度慢),
// 比让首批写入卡 30s 更可接受。
go func(tn string) {
// 用独立 context(带 timeout),避免请求级 ctx 取消把后台轮询也带走。
bgCtx, cancel := context.WithTimeout(context.Background(), annReadyTimeout)
defer cancel()
if err := r.waitANNReady(bgCtx, tn); err != nil {
logger.GetLogger(bgCtx).Warnf(
"[Doris] ANN index for %s not ready within %s: %v "+
"(queries may fall back to brute force temporarily)",
tn, annReadyTimeout, err)
return
}
logger.GetLogger(bgCtx).Infof("[Doris] ANN index for %s ready", tn)
}(tableName)
}
r.initializedTables.Store(dimension, true)
return nil
}
// tableExists 通过 information_schema 判断表是否存在。
//
// 不直接用 SHOW TABLES 是因为 Doris 4.1 对 SHOW TABLES LIKE 大小写敏感,
// 而 information_schema 与 MySQL 兼容性更好。
func (r *dorisRepository) tableExists(ctx context.Context, tableName string) (bool, error) {
const q = `SELECT COUNT(1) FROM information_schema.tables
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`
var n int
if err := r.db.QueryRowContext(ctx, q, r.database, tableName).Scan(&n); err != nil {
return false, err
}
return n > 0, nil
}
// createTable 发出 CREATE TABLE DDL。Doris DDL 是同步的(除 ANN 索引构建外),
// 返回成功即代表表已可写。
func (r *dorisRepository) createTable(ctx context.Context, tableName string, dimension int, compatMode dorisCompatMode) error {
buckets := r.bucketsNum
if buckets <= 0 {
buckets = defaultBucketsNum
}
replication := r.replicationNum
if replication <= 0 {
replication = defaultReplicationNum
}
ddl := buildCreateTableDDL(tableName, dimension, buckets, replication, compatMode)
_, err := r.db.ExecContext(ctx, ddl)
if err != nil && compatMode == dorisCompatModeLegacy {
return fmt.Errorf(
"legacy Doris table creation failed: %w. If your Doris build rejects ANN indexes on UNIQUE KEY tables, set %s=%s before creating embedding tables. %s is not interchangeable after %s_* tables are created",
err,
envDorisCompatMode,
dorisCompatModeInnerProductDuplicate,
envDorisCompatMode,
r.tableBaseName,
)
}
return err
}
// buildCreateTableDDL 根据维度生成 CREATE TABLE DDL。
//
// 关键点:
// - DUPLICATE KEY(id):兼容当前 Doris/SelectDB 对 ANN 索引的表模型要求。
// Academy 在 Go 端用 delete + insert 保持按 id 替换的写入语义。
// - INVERTED 索引覆盖所有过滤字段 + 中文分词的 content 全文索引。
// - ANN 索引使用 HNSW + inner_product;Doris 写入/查询前会对向量单位化,
// 因此整体仍保持与其他向量库一致的 cosine 相似度语义。
//
// 注意:DDL 中 dimension / buckets / replication 三个数值字段是 Go 端格式化拼接的,
// 不存在 SQL 注入风险(来源都是受控的 IndexConfig int)。
func buildCreateTableDDL(tableName string, dimension, buckets, replication int, compatMode dorisCompatMode) string {
metricType := "inner_product"
keyMode := "DUPLICATE KEY(id)"
properties := fmt.Sprintf("\t\"replication_num\"=\"%d\"", replication)
if compatMode == dorisCompatModeLegacy {
metricType = "cosine_distance"
keyMode = "UNIQUE KEY(id)"
properties = fmt.Sprintf("\t\"replication_num\"=\"%d\",\n\t\"enable_unique_key_merge_on_write\"=\"true\"", replication)
}
const tpl = `CREATE TABLE IF NOT EXISTS ` + "`%s`" + ` (
id VARCHAR(64) NOT NULL,
chunk_id VARCHAR(64),
knowledge_id VARCHAR(64),
knowledge_base_id VARCHAR(64),
source_id VARCHAR(255),
source_type INT,
tag_id VARCHAR(64),
is_enabled BOOLEAN,
content TEXT,
embedding ARRAY<FLOAT> NOT NULL,
INDEX idx_chunk (chunk_id) USING INVERTED,
INDEX idx_kb (knowledge_base_id) USING INVERTED,
INDEX idx_kid (knowledge_id) USING INVERTED,
INDEX idx_src (source_id) USING INVERTED,
INDEX idx_tag (tag_id) USING INVERTED,
INDEX idx_enabled (is_enabled) USING INVERTED,
INDEX idx_content (content) USING INVERTED PROPERTIES("parser"="chinese","support_phrase"="true"),
INDEX idx_emb (embedding) USING ANN PROPERTIES(
"index_type"="hnsw",
"metric_type"="%s",
"dim"="%d",
"max_degree"="32",
"ef_construction"="200"
)
) ENGINE=OLAP
%s
DISTRIBUTED BY HASH(id) BUCKETS %d
PROPERTIES(
%s
);`
return fmt.Sprintf(tpl, tableName, metricType, dimension, keyMode, buckets, properties)
}
// waitANNReady 轮询 SHOW INDEX,等待 ANN 索引进入 FINISHED 状态。
//
// Doris 的 ANN 索引在建表后会异步构建,期间查询会退化为 brute-force(结果对,速度慢)。
// 此处仅做"尽力而为"的等待:到点未就绪只记 warning,不阻塞写入。
func (r *dorisRepository) waitANNReady(ctx context.Context, tableName string) error {
deadline := time.Now().Add(annReadyTimeout)
for {
ready, err := r.annIndexReady(ctx, tableName)
if err != nil {
return err
}
if ready {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("ann index not ready within %s", annReadyTimeout)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(annReadyPoll):
}
}
}
// annIndexReady 检查 ANN 索引的 State 是否为 FINISHED。
//
// SHOW INDEX FROM <table> 在 Doris 上返回多列;不同小版本列序略有差异,
// 这里以列名匹配(来自 information_schema.statistics + 自定义 view 不可行,
// 直接用 SHOW INDEX 然后扫描即可)。
//
// 兼容策略:如果 SHOW INDEX 返回中找不到 idx_emb 行(极旧版本),视为已就绪,
// 避免因为不同 Doris 版本的输出差异把启动卡死。
func (r *dorisRepository) annIndexReady(ctx context.Context, tableName string) (bool, error) {
rows, err := r.db.QueryContext(ctx,
fmt.Sprintf("SHOW INDEX FROM `%s`", tableName))
if err != nil {
return false, err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return false, err
}
keyNameIdx, stateIdx := -1, -1
for i, c := range cols {
switch strings.ToLower(c) {
case "key_name":
keyNameIdx = i
case "state", "index_state":
stateIdx = i
}
}
for rows.Next() {
// 使用 sql.RawBytes 接收以兼容不同列类型。
raw := make([]any, len(cols))
ptrs := make([]any, len(cols))
for i := range raw {
ptrs[i] = &raw[i]
}
if err := rows.Scan(ptrs...); err != nil {
return false, err
}
var keyName, state string
if keyNameIdx >= 0 {
keyName = bytesToString(raw[keyNameIdx])
}
if stateIdx >= 0 {
state = bytesToString(raw[stateIdx])
}
if keyName != "idx_emb" {
continue
}
if stateIdx < 0 {
// 旧版本不暴露 state 列,乐观认为已就绪。
return true, nil
}
if !strings.EqualFold(state, "FINISHED") &&
!strings.EqualFold(state, "NORMAL") {
return false, nil
}
}
if err := rows.Err(); err != nil {
return false, err
}
// 走到这里有两种情况:
// 1. 找到了 idx_emb 行,且 state 已是 FINISHED/NORMAL(或 stateIdx<0 的旧版本);
// 2. 没找到 idx_emb 行(极旧 Doris 不暴露该索引名);
// 都视为已就绪,不阻塞。未就绪的分支已在循环内提前 return false。
return true, nil
}
// listEmbeddingTables 返回当前 database 下所有 <base>_% 命名的表,
// 用于关键词检索 / 跨维度 BatchUpdate。
func (r *dorisRepository) listEmbeddingTables(ctx context.Context) ([]string, error) {
const q = `SELECT TABLE_NAME FROM information_schema.tables
WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE ?`
rows, err := r.db.QueryContext(ctx, q, r.database, r.tableBaseName+"\\_%")
if err != nil {
return nil, err
}
defer rows.Close()
var names []string
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
return nil, err
}
names = append(names, n)
}
return names, rows.Err()
}
// bytesToString 把 SHOW INDEX 返回的 raw any(通常是 []byte 或 string)
// 安全转成字符串。
func bytesToString(v any) string {
switch s := v.(type) {
case []byte:
return string(s)
case string:
return s
case nil:
return ""
default:
return fmt.Sprintf("%v", s)
}
}
@@ -0,0 +1,512 @@
package doris
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"academy/internal/logger"
secutils "academy/internal/utils"
)
// Stream Load 相关常量。
const (
// 单批 Stream Load 的 JSON body 上限(保守值,远小于 Doris 默认 streaming_load_max_mb=10240)。
// 主要目的是控制单次 HTTP 请求的尾延迟,超过则自动拆批。
streamLoadMaxBatchBytes = 1 << 20 // 1 MiB
// HTTP 头 Authorization 用 Basic auth;Stream Load 也支持 token,
// 这里走最常用的用户名/密码方案与 MySQL 协议保持一致。
headerAuthorization = "Authorization"
headerExpect = "Expect"
headerContentType = "Content-Type"
)
// streamLoadResponse 是 Doris FE/BE 返回的 Stream Load 结果体。
//
// 关键字段:Status 应为 "Success" 或 "Publish Timeout"(后者表示数据已写入但发布事务超时,
// 仍视为成功)。其它状态都视为失败。
type streamLoadResponse struct {
TxnId int64 `json:"TxnId"`
Label string `json:"Label"`
Status string `json:"Status"`
Message string `json:"Message"`
NumberTotalRows int64 `json:"NumberTotalRows"`
NumberLoadedRows int64 `json:"NumberLoadedRows"`
NumberFilteredRows int64 `json:"NumberFilteredRows"`
NumberUnselectedRows int64 `json:"NumberUnselectedRows"`
LoadBytes int64 `json:"LoadBytes"`
LoadTimeMs int64 `json:"LoadTimeMs"`
BeginTxnTimeMs int64 `json:"BeginTxnTimeMs"`
StreamLoadPutTimeMs int64 `json:"StreamLoadPutTimeMs"`
ReadDataTimeMs int64 `json:"ReadDataTimeMs"`
WriteDataTimeMs int64 `json:"WriteDataTimeMs"`
CommitAndPublishTimeMs int64 `json:"CommitAndPublishTimeMs"`
ErrorURL string `json:"ErrorURL"`
}
// streamLoadURL 拼装某张表的 Stream Load HTTP 端点。
func (r *dorisRepository) streamLoadURL(table string) string {
return fmt.Sprintf("%s/api/%s/%s/_stream_load",
r.feHTTPBase, url.PathEscape(r.database), url.PathEscape(table))
}
// newDorisStreamLoadHTTPClient protects both the initial FE request and every
// FE -> BE redirect at connection time. Doris requires Basic auth to survive
// the 307 redirect, so redirect targets on another host must be explicitly
// trusted through the SSRF whitelist before credentials are forwarded.
func newDorisStreamLoadHTTPClient() *http.Client {
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
// Stream Load calls carry their own context deadline. Preserve the previous
// client behaviour instead of imposing the generic 30-second HTTP timeout.
cfg.Timeout = 0
client := secutils.NewSSRFSafeHTTPClient(cfg)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= cfg.MaxRedirects {
return fmt.Errorf("stopped after %d redirects", cfg.MaxRedirects)
}
if len(via) == 0 {
return nil
}
// Stream Load deliberately replays PUT bodies to a BE. Keep this
// exception local to Doris; generic clients must not replay requests
// across origins. Every cross-origin destination must be trusted.
source := via[0].URL
sameOrigin := strings.EqualFold(source.Scheme, req.URL.Scheme) &&
strings.EqualFold(source.Host, req.URL.Host)
if !sameOrigin && !secutils.IsSSRFWhitelisted(req.URL.Hostname()) {
return fmt.Errorf("%w: stream load target host %q is not trusted to receive credentials",
secutils.ErrSSRFRedirectBlocked, req.URL.Hostname())
}
if strings.EqualFold(source.Scheme, "https") && !strings.EqualFold(req.URL.Scheme, "https") {
return fmt.Errorf("%w: stream load HTTPS downgrade is forbidden", secutils.ErrSSRFRedirectBlocked)
}
if err := secutils.ValidateURLForSSRF(req.URL.String()); err != nil {
return fmt.Errorf("%w: %w", secutils.ErrSSRFRedirectBlocked, err)
}
// The shared transport still validates each URL and connection. Preserve
// load options and restore Basic auth only after checking the destination.
req.Header.Set(headerAuthorization, via[0].Header.Get(headerAuthorization))
return nil
}
return client
}
// partialUpdateRows 把若干行通过 Stream Load 的 partial update 模式写回目标表。
//
// columns 是参与本次 partial update 的列(必须包含 UNIQUE KEY 列,即 "id")。
// rows 中每一项是一个与 columns 等长的字段值数组。
//
// 实现要点:
// 1. 用 JSON 数组的 body 形式,header 加 strip_outer_array=true。
// 2. 设置 partial_columns=true、merge_type=APPEND,触发 Doris 的 partial update 模式
// (Doris 4.1 + UNIQUE KEY MoW 表的标准玩法)。
// 3. 按 streamLoadMaxBatchBytes 自动拆批,避免单次过大。
// 4. 处理 307:Doris 的 FE 会 redirect 到 BE,net/http 默认会跟随;
// 这里需要保证 GetBody 可重发(已通过 bytes.NewReader 构造 Body 满足)。
func (r *dorisRepository) partialUpdateRows(ctx context.Context,
table string, columns []string, rows []map[string]any,
) error {
if len(rows) == 0 {
return nil
}
for _, batch := range chunkRows(rows, streamLoadMaxBatchBytes) {
if err := r.streamLoadOnce(ctx, table, columns, batch); err != nil {
return err
}
}
return nil
}
// streamLoadOnce 发出一次 Stream Load HTTP 请求。
func (r *dorisRepository) streamLoadOnce(ctx context.Context,
table string, columns []string, rows []map[string]any,
) error {
log := logger.GetLogger(ctx)
if len(rows) == 0 {
return nil
}
body, err := json.Marshal(rows)
if err != nil {
return fmt.Errorf("marshal stream load body: %w", err)
}
url := r.streamLoadURL(table)
// Validate at the final outbound boundary as well as when user-supplied
// vector-store configuration is created. This covers stored/env configs and
// keeps the tainted value from reaching http.Client.Do unchecked.
if err := secutils.ValidateURLForSSRF(url); err != nil {
return fmt.Errorf("stream load URL blocked by SSRF validation: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("build stream load request: %w", err)
}
// GetBody 让 redirect 时可以重新读 body(FE -> BE 的 307 需要重发 PUT body)。
bodyCopy := append([]byte(nil), body...)
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(bodyCopy)), nil
}
req.ContentLength = int64(len(body))
auth := base64.StdEncoding.EncodeToString([]byte(r.username + ":" + r.password))
req.Header.Set(headerAuthorization, "Basic "+auth)
req.Header.Set(headerExpect, "100-continue")
req.Header.Set(headerContentType, "application/json")
req.Header.Set("format", "json")
req.Header.Set("strip_outer_array", "true")
req.Header.Set("partial_columns", "true")
req.Header.Set("columns", strings.Join(columns, ","))
req.Header.Set("merge_type", "APPEND")
resp, err := r.httpClient.Do(req)
if err != nil {
return fmt.Errorf("stream load HTTP: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read stream load response: %w", err)
}
if resp.StatusCode/100 != 2 {
return fmt.Errorf("stream load HTTP %d: %s", resp.StatusCode, string(respBody))
}
var result streamLoadResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return fmt.Errorf("decode stream load response: %w (raw=%s)", err, string(respBody))
}
switch result.Status {
case "Success", "Publish Timeout":
log.Infof("[Doris] Stream load %s OK: rows=%d, loaded=%d, label=%s",
table, result.NumberTotalRows, result.NumberLoadedRows, result.Label)
return nil
default:
return fmt.Errorf("stream load failed: status=%s msg=%s err_url=%s",
result.Status, result.Message, result.ErrorURL)
}
}
// chunkRows 把行按累积 JSON 体大小切分,每段不超过 maxBytes。
//
// 注意:JSON 序列化的实际开销大约是 marshal 后的字节数,而单行 marshal
// 加上逗号 + 数组括号约等于本估算。这里用粗略估计避免每段都 marshal。
func chunkRows(rows []map[string]any, maxBytes int) [][]map[string]any {
if len(rows) == 0 {
return nil
}
var (
out [][]map[string]any
curr []map[string]any
size int
header = 2 // "[" + "]"
)
for _, row := range rows {
raw, err := json.Marshal(row)
if err != nil {
// marshal 失败时把这一行单独成段,由上层 streamLoadOnce 再次 marshal 报错。
if len(curr) > 0 {
out = append(out, curr)
}
out = append(out, []map[string]any{row})
curr = nil
size = 0
continue
}
// 加上逗号位(除第一行之外)。
need := len(raw)
if len(curr) > 0 {
need++
}
if size+need+header > maxBytes && len(curr) > 0 {
out = append(out, curr)
curr = nil
size = 0
}
curr = append(curr, row)
size += need
}
if len(curr) > 0 {
out = append(out, curr)
}
return out
}
// ---------------------------------------------------------------------------
// 业务面方法:BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID
// ---------------------------------------------------------------------------
// BatchUpdateChunkEnabledStatus 批量更新 chunk 的 is_enabled 字段。
// legacy 模式走 Stream Load partial update;inner_product_duplicate 模式改为读整行后 replaceRows 写回。
func (r *dorisRepository) BatchUpdateChunkEnabledStatus(ctx context.Context,
chunkStatusMap map[string]bool,
) error {
if len(chunkStatusMap) == 0 {
return nil
}
compatMode, err := r.resolveCompatMode(ctx)
if err != nil {
return err
}
if !compatMode.usesRewriteChunkUpdates() {
return r.batchUpdateChunkEnabledStatusLegacy(ctx, chunkStatusMap)
}
chunkIDs := make([]string, 0, len(chunkStatusMap))
for id := range chunkStatusMap {
chunkIDs = append(chunkIDs, id)
}
return r.rewriteChunkRows(ctx, chunkIDs, func(row *DorisVectorEmbedding) bool {
enabled, ok := chunkStatusMap[row.ChunkID]
if !ok || row.IsEnabled == enabled {
return false
}
row.IsEnabled = enabled
return true
}, "rewrite is_enabled")
}
// BatchUpdateChunkTagID 批量更新 chunk 的 tag_id 字段。逻辑与 EnabledStatus 一致。
func (r *dorisRepository) BatchUpdateChunkTagID(ctx context.Context,
chunkTagMap map[string]string,
) error {
if len(chunkTagMap) == 0 {
return nil
}
compatMode, err := r.resolveCompatMode(ctx)
if err != nil {
return err
}
if !compatMode.usesRewriteChunkUpdates() {
return r.batchUpdateChunkTagIDLegacy(ctx, chunkTagMap)
}
chunkIDs := make([]string, 0, len(chunkTagMap))
for id := range chunkTagMap {
chunkIDs = append(chunkIDs, id)
}
return r.rewriteChunkRows(ctx, chunkIDs, func(row *DorisVectorEmbedding) bool {
tagID, ok := chunkTagMap[row.ChunkID]
if !ok || row.TagID == tagID {
return false
}
row.TagID = tagID
return true
}, "rewrite tag_id")
}
func (r *dorisRepository) rewriteChunkRows(ctx context.Context,
chunkIDs []string,
mutate func(*DorisVectorEmbedding) bool,
action string,
) error {
if len(chunkIDs) == 0 {
return nil
}
tables, err := r.listEmbeddingTables(ctx)
if err != nil {
return fmt.Errorf("list tables: %w", err)
}
for _, table := range tables {
rows, err := r.loadRowsByChunkIDs(ctx, table, chunkIDs)
if err != nil {
return fmt.Errorf("load chunk rows from %s: %w", table, err)
}
updated := make([]*DorisVectorEmbedding, 0, len(rows))
for _, row := range rows {
if !mutate(row) {
continue
}
updated = append(updated, row)
}
if len(updated) == 0 {
continue
}
if err := r.replaceRows(ctx, table, updated); err != nil {
return fmt.Errorf("%s in %s: %w", action, table, err)
}
}
return nil
}
func (r *dorisRepository) batchUpdateChunkEnabledStatusLegacy(ctx context.Context,
chunkStatusMap map[string]bool,
) error {
chunkIDs := make([]string, 0, len(chunkStatusMap))
for id := range chunkStatusMap {
chunkIDs = append(chunkIDs, id)
}
mapping, err := r.lookupChunkRowKeys(ctx, chunkIDs)
if err != nil {
return err
}
byTable := make(map[string][]map[string]any)
for chunkID, locations := range mapping {
enabled, ok := chunkStatusMap[chunkID]
if !ok {
continue
}
for _, loc := range locations {
byTable[loc.table] = append(byTable[loc.table], map[string]any{
fieldID: loc.id,
fieldIsEnabled: enabled,
})
}
}
for table, rows := range byTable {
if err := r.partialUpdateRows(ctx, table, []string{fieldID, fieldIsEnabled}, rows); err != nil {
return fmt.Errorf("partial update is_enabled in %s: %w", table, err)
}
}
return nil
}
func (r *dorisRepository) batchUpdateChunkTagIDLegacy(ctx context.Context,
chunkTagMap map[string]string,
) error {
chunkIDs := make([]string, 0, len(chunkTagMap))
for id := range chunkTagMap {
chunkIDs = append(chunkIDs, id)
}
mapping, err := r.lookupChunkRowKeys(ctx, chunkIDs)
if err != nil {
return err
}
byTable := make(map[string][]map[string]any)
for chunkID, locations := range mapping {
tagID, ok := chunkTagMap[chunkID]
if !ok {
continue
}
for _, loc := range locations {
byTable[loc.table] = append(byTable[loc.table], map[string]any{
fieldID: loc.id,
fieldTagID: tagID,
})
}
}
for table, rows := range byTable {
if err := r.partialUpdateRows(ctx, table, []string{fieldID, fieldTagID}, rows); err != nil {
return fmt.Errorf("partial update tag_id in %s: %w", table, err)
}
}
return nil
}
func (r *dorisRepository) loadRowsByChunkIDs(ctx context.Context,
table string, chunkIDs []string,
) ([]*DorisVectorEmbedding, error) {
if len(chunkIDs) == 0 {
return nil, nil
}
placeholders := make([]string, len(chunkIDs))
args := make([]any, len(chunkIDs))
for i, v := range chunkIDs {
placeholders[i] = "?"
args[i] = v
}
stmt := fmt.Sprintf(
"SELECT %s FROM `%s` WHERE %s IN (%s)",
strings.Join(columnsForCopy, ", "),
table,
fieldChunkID,
strings.Join(placeholders, ", "),
)
rows, err := r.db.QueryContext(ctx, stmt, args...)
if err != nil {
return nil, err
}
batch, err := scanCopyRows(rows)
_ = rows.Close()
if err != nil {
return nil, err
}
return batch, nil
}
// rowLocation 表示某行在哪个表里、主键 id 是什么。
type rowLocation struct {
table string
id string
}
// lookupChunkRowKeys 查询给定的 chunkIDs 在所有 <base>_<dim> 表中的物理位置:
// - key:chunk_id
// - value:[(table, id), ...],因为同一 chunk 可能在多个维度的表里都有副本。
//
// 跨表查询使用 listEmbeddingTables 列出的所有匹配表;每张表执行一次
// SELECT id, chunk_id FROM <table> WHERE chunk_id IN (?, ?, ...)。
func (r *dorisRepository) lookupChunkRowKeys(ctx context.Context,
chunkIDs []string,
) (map[string][]rowLocation, error) {
if len(chunkIDs) == 0 {
return nil, nil
}
tables, err := r.listEmbeddingTables(ctx)
if err != nil {
return nil, fmt.Errorf("list tables: %w", err)
}
if len(tables) == 0 {
return nil, nil
}
placeholders := make([]string, len(chunkIDs))
args := make([]any, len(chunkIDs))
for i, v := range chunkIDs {
placeholders[i] = "?"
args[i] = v
}
out := make(map[string][]rowLocation)
for _, table := range tables {
stmt := fmt.Sprintf(
"SELECT %s, %s FROM `%s` WHERE %s IN (%s)",
fieldID, fieldChunkID, table, fieldChunkID, strings.Join(placeholders, ", "),
)
rows, err := r.db.QueryContext(ctx, stmt, args...)
if err != nil {
return nil, fmt.Errorf("lookup chunk row keys in %s: %w", table, err)
}
for rows.Next() {
var id, chunkID string
if err := rows.Scan(&id, &chunkID); err != nil {
_ = rows.Close()
return nil, fmt.Errorf("scan row keys: %w", err)
}
out[chunkID] = append(out[chunkID], rowLocation{table: table, id: id})
}
if err := rows.Err(); err != nil {
_ = rows.Close()
return nil, err
}
_ = rows.Close()
}
return out, nil
}
@@ -0,0 +1,70 @@
package doris
import (
"database/sql"
"net/http"
"sync"
)
// dorisRepository 是 Apache Doris 4.1 的检索引擎仓储实现。
//
// 通信通道:
// - 读写主链路:MySQL 协议(database/sql + go-sql-driver/mysql),FE 默认 9030 端口。
// - Stream Load:HTTP(FE 默认 8030 端口),legacy 模式用于 partial update。
//
// 表结构按维度分表:<tableBaseName>_<dim>。
// 兼容模式由 DORIS_COMPAT_MODE 决定:
// - legacy:UNIQUE KEY(id) + cosine_distance ANN + Stream Load partial update
// - inner_product_duplicate:DUPLICATE KEY(id) + normalized inner product + delete/insert rewrite
//
// 该设置在 embedding 表创建后不可直接互换;切换模式前需要重建这些表。
//
// 与 Qdrant/Milvus/Weaviate 一样,initializedTables 缓存"已确保存在"的维度,
// 避免每次写入都打 SHOW TABLES。
type dorisRepository struct {
db *sql.DB
httpClient *http.Client
// fe HTTP base,例如 "http://doris-fe:8030"。Stream Load 路径
// 由 streamLoadURL(table) 拼接:<feHTTPBase>/api/<database>/<table>/_stream_load。
feHTTPBase string
username string
password string
database string
tableBaseName string
bucketsNum int // 0 -> default 10
replicationNum int // 0 -> default 1
compatModeRequested dorisCompatMode
compatModeResolved dorisCompatMode
compatResolveOnce sync.Once
compatResolveErr error
// 已经确保过 ensureTable 的维度集合:dim -> true。
initializedTables sync.Map
}
// DorisVectorEmbedding 是落到 Doris 表里的一行的领域模型。
//
// 字段顺序与 schema.go 中的 INSERT 列序保持一致,
// 调整时需要同时更新 createInsert 与 columns。
type DorisVectorEmbedding struct {
ID string
Content string
SourceID string
SourceType int
ChunkID string
KnowledgeID string
KnowledgeBaseID string
TagID string
IsEnabled bool
Embedding []float32
}
// DorisVectorEmbeddingWithScore 是检索结果的领域模型,
// Score 在向量检索时按当前 compat mode 计算,在关键词检索时统一赋 1.0。
type DorisVectorEmbeddingWithScore struct {
DorisVectorEmbedding
Score float64
}
@@ -0,0 +1,78 @@
package elasticsearch
import (
"maps"
"slices"
"academy/internal/types"
)
// VectorEmbedding defines the Elasticsearch document structure for vector embeddings
type VectorEmbedding struct {
Content string `json:"content" gorm:"column:content;not null"` // Text content of the chunk
SourceID string `json:"source_id" gorm:"column:source_id;not null"` // ID of the source document
SourceType int `json:"source_type" gorm:"column:source_type;not null"` // Type of the source document
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"` // Unique ID of the text chunk
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
TagID string `json:"tag_id" gorm:"column:tag_id"` // Tag ID for categorization
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled
IsRecommended bool `json:"is_recommended"` // Whether the chunk is recommended
}
// VectorEmbeddingWithScore extends VectorEmbedding with similarity score
type VectorEmbeddingWithScore struct {
VectorEmbedding
Score float64 // Similarity score from vector search
}
// ToDBVectorEmbedding converts IndexInfo to Elasticsearch document format
func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string]interface{}) *VectorEmbedding {
vector := &VectorEmbedding{
Content: embedding.Content,
SourceID: embedding.SourceID,
SourceType: int(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
TagID: embedding.TagID,
IsEnabled: embedding.IsEnabled,
IsRecommended: embedding.IsRecommended,
}
// Add embedding data if available in additionalParams
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
if embeddingMap, ok := additionalParams["embedding"].(map[string][]float32); ok {
vector.Embedding = embeddingMap[embedding.SourceID]
}
}
// Get is_enabled from additionalParams if available
if additionalParams != nil {
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
if enabled, exists := chunkEnabledMap[embedding.ChunkID]; exists {
vector.IsEnabled = enabled
}
}
}
return vector
}
// FromDBVectorEmbeddingWithScore converts Elasticsearch document to IndexWithScore domain model
func FromDBVectorEmbeddingWithScore(id string,
embedding *VectorEmbeddingWithScore,
matchType types.MatchType,
) *types.IndexWithScore {
return &types.IndexWithScore{
ID: id,
SourceID: embedding.SourceID,
SourceType: types.SourceType(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
TagID: embedding.TagID,
Content: embedding.Content,
Score: embedding.Score,
MatchType: matchType,
IsEnabled: embedding.IsEnabled,
}
}
@@ -0,0 +1,150 @@
package v7
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
"academy/internal/types/interfaces"
"github.com/elastic/go-elasticsearch/v7"
)
// bulkReasonSentinel stands for document content that a per-item error.reason
// can carry; the error returned to the caller must never include it.
const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY"
// fakeBulkServer answers every request the v7 repository makes while BatchSave
// runs, and returns body for the _bulk call.
type fakeBulkServer struct {
body string
calls int
}
func (f *fakeBulkServer) handler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/_bulk"):
f.calls++
_, _ = io.WriteString(w, f.body)
case strings.HasSuffix(r.URL.Path, "/_mapping"):
_, _ = io.WriteString(w,
`{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`)
case r.Method == http.MethodHead:
w.WriteHeader(http.StatusNotFound)
default:
_, _ = io.WriteString(w,
`{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`)
}
}
}
// newBulkTestRepository builds the repository through its public constructor
// against a fake Elasticsearch that answers _bulk with body.
func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) {
t.Helper()
fake := &fakeBulkServer{body: body}
server := httptest.NewServer(fake.handler())
t.Cleanup(server.Close)
client, err := elasticsearch.NewClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
return NewElasticsearchEngineRepository(client, nil, nil), fake
}
func bulkTestIndexInfos() []*typesLocal.IndexInfo {
return []*typesLocal.IndexInfo{
{
Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
{
Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
}
}
func bulkTestParams() map[string]any {
return map[string]any{
"embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}},
}
}
// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832:
// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document
// rejected for a mapping mismatch, a read-only index or an item-level
// rejection is visible only in the response body. BatchSave must surface those
// per-item failures instead of logging a warning and reporting success.
func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) {
cases := []struct {
name string
body string
wantContains []string
}{
{
name: "all documents rejected",
body: `{"took":1,"errors":true,"items":[` +
`{"index":{"_id":"chunk-1","status":400,` +
`"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` +
`{"index":{"_id":"chunk-2","status":429,` +
`"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{
"2/2 documents failed",
"chunk-1", "mapper_parsing_exception",
"chunk-2", "es_rejected_execution_exception",
},
},
{
name: "partial failure",
body: `{"took":1,"errors":true,"items":[` +
`{"index":{"_id":"chunk-1","status":201,"result":"created"}},` +
`{"index":{"_id":"chunk-2","status":400,` +
`"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"},
},
{
name: "malformed response body",
body: `{"took":1`,
wantContains: []string{"failed to parse bulk response"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
repo, fake := newBulkTestRepository(t, tc.body)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.Error(t, err)
for _, want := range tc.wantContains {
assert.Contains(t, err.Error(), want)
}
assert.NotContains(t, err.Error(), bulkReasonSentinel,
"the returned error must not carry error.reason")
})
}
t.Run("all documents accepted", func(t *testing.T) {
repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+
`{"index":{"_id":"chunk-1","status":201,"result":"created"}},`+
`{"index":{"_id":"chunk-2","status":201,"result":"created"}}]}`)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.NoError(t, err)
})
}
@@ -0,0 +1,145 @@
package v7
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/elastic/go-elasticsearch/v7"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// copySourceHits covers every source_id shape CopyIndices remaps: a regular
// chunk row, a generated-question row sharing that chunk, a row with an
// unrelated source_id (remapped to a fresh uuid), and a legacy row written
// before is_enabled existed.
const copySourceHits = `[
{"_index":"vectors","_id":"d1","_score":1,"_source":{"content":"chunk","source_id":"c1","source_type":0,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.1,0.2],"is_enabled":true}},
{"_index":"vectors","_id":"d2","_score":1,"_source":{"content":"question","source_id":"c1-q1","source_type":1,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.3,0.4],"is_enabled":true}},
{"_index":"vectors","_id":"d3","_score":1,"_source":{"content":"summary","source_id":"img-9","source_type":2,
"chunk_id":"c2","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.5,0.6],"is_enabled":false}},
{"_index":"vectors","_id":"d4","_score":1,"_source":{"content":"legacy","source_id":"c3","source_type":0,
"chunk_id":"c3","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.7,0.8]}}
]`
type copiedDoc struct {
Content string `json:"content"`
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"`
Embedding []float32 `json:"embedding"`
IsEnabled *bool `json:"is_enabled"`
}
// fakeCopyServer serves one page of copySourceHits and records the search
// query and every document sent through _bulk.
type fakeCopyServer struct {
mu sync.Mutex
searchQuery string
docs []copiedDoc
}
func (f *fakeCopyServer) handler(t *testing.T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
body, _ := io.ReadAll(r.Body)
f.mu.Lock()
defer f.mu.Unlock()
switch r.URL.Path {
case "/":
_, _ = w.Write([]byte(`{"version":{"number":"7.17.0","build_flavor":"default"},` +
`"tagline":"You Know, for Search"}`))
case "/vectors/_search":
f.searchQuery = string(body)
_, _ = w.Write([]byte(`{"took":1,"timed_out":false,` +
`"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},` +
`"hits":{"total":{"value":4,"relation":"eq"},"hits":` + copySourceHits + `}}`))
case "/vectors/_bulk":
sc := bufio.NewScanner(bytes.NewReader(body))
sc.Buffer(make([]byte, 0, 1<<20), 1<<20)
for sc.Scan() {
line := sc.Bytes()
var probe map[string]json.RawMessage
require.NoError(t, json.Unmarshal(line, &probe))
if _, ok := probe["content"]; !ok {
continue // action line
}
var doc copiedDoc
require.NoError(t, json.Unmarshal(line, &doc))
f.docs = append(f.docs, doc)
}
_, _ = w.Write([]byte(`{"took":1,"errors":false,"items":[]}`))
default:
t.Errorf("unexpected path: %s", r.URL.Path)
}
}
}
func TestCopyIndicesKeepsVectorsAndEnabledState(t *testing.T) {
fake := &fakeCopyServer{}
server := httptest.NewServer(fake.handler(t))
defer server.Close()
client, err := elasticsearch.NewClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.CopyIndices(context.Background(), "kb-src",
map[string]string{"k1": "tk1"},
map[string]string{"c1": "t1", "c2": "t2", "c3": "t3"},
"kb-dst", 2, "manual")
require.NoError(t, err)
assert.NotContains(t, fake.searchQuery, "is_enabled",
"the copy scan must include disabled source rows so they stay disabled, not vanish")
require.Len(t, fake.docs, 4)
byContent := make(map[string]copiedDoc, len(fake.docs))
for _, d := range fake.docs {
byContent[d.Content] = d
assert.Equal(t, "tk1", d.KnowledgeID)
assert.Equal(t, "kb-dst", d.KnowledgeBaseID)
require.NotNil(t, d.IsEnabled, "is_enabled must be written for %q", d.Content)
}
chunk := byContent["chunk"]
assert.Equal(t, "t1", chunk.ChunkID)
assert.Equal(t, "t1", chunk.SourceID)
assert.Equal(t, 0, chunk.SourceType)
assert.Equal(t, []float32{0.1, 0.2}, chunk.Embedding)
assert.True(t, *chunk.IsEnabled)
question := byContent["question"]
assert.Equal(t, "t1", question.ChunkID)
assert.Equal(t, "t1-q1", question.SourceID)
assert.Equal(t, 1, question.SourceType)
assert.Equal(t, []float32{0.3, 0.4}, question.Embedding)
assert.True(t, *question.IsEnabled)
summary := byContent["summary"]
assert.Equal(t, "t2", summary.ChunkID)
assert.NotEqual(t, "img-9", summary.SourceID)
assert.False(t, strings.HasPrefix(summary.SourceID, "t2"), "unrelated source ids get a fresh uuid")
assert.Equal(t, 2, summary.SourceType)
assert.Equal(t, []float32{0.5, 0.6}, summary.Embedding)
assert.False(t, *summary.IsEnabled)
legacy := byContent["legacy"]
assert.Equal(t, "t3", legacy.SourceID)
assert.Equal(t, []float32{0.7, 0.8}, legacy.Embedding)
assert.True(t, *legacy.IsEnabled, "a source row without is_enabled is enabled for retrieval")
}
@@ -0,0 +1,59 @@
package v7
import (
"bytes"
"context"
"encoding/json"
"fmt"
)
func (e *elasticsearchRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
_ int,
_ string,
) error {
body, err := json.Marshal(map[string]any{
"query": map[string]any{"bool": map[string]any{"filter": []any{
map[string]any{"term": map[string]any{e.idField("knowledge_base_id"): sourceKB}},
map[string]any{"term": map[string]any{e.idField("knowledge_id"): knowledgeID}},
}}},
"script": map[string]any{
"lang": "painless",
"source": "ctx._source.knowledge_base_id = params.target; ctx._source.tag_id = ''",
"params": map[string]any{"target": targetKB},
},
})
if err != nil {
return err
}
resp, err := e.client.UpdateByQuery(
[]string{e.index},
e.client.UpdateByQuery.WithContext(ctx),
e.client.UpdateByQuery.WithBody(bytes.NewReader(body)),
e.client.UpdateByQuery.WithRefresh(true),
)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.IsError() {
return fmt.Errorf("move indices: %s", resp.String())
}
var result struct {
Total *int64 `json:"total"`
Updated *int64 `json:"updated"`
TimedOut bool `json:"timed_out"`
Conflicts int `json:"version_conflicts"`
Failures []json.RawMessage `json:"failures"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return err
}
if result.Total == nil || result.Updated == nil || *result.Total < 0 || *result.Total != *result.Updated ||
result.TimedOut || result.Conflicts != 0 || len(result.Failures) != 0 {
return fmt.Errorf("move indices was incomplete")
}
return nil
}
@@ -0,0 +1,59 @@
package v7
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/elastic/go-elasticsearch/v7"
"github.com/stretchr/testify/require"
)
func TestMoveIndicesRequiresCompleteCounts(t *testing.T) {
for _, tt := range []struct {
name, body string
fails bool
}{
{"complete", `{"total":100,"updated":100}`, false},
{"empty retry", `{"total":0,"updated":0}`, false},
{"partial", `{"total":100,"updated":40}`, true},
{"missing total", `{"updated":40}`, true},
{"missing updated", `{"total":40}`, true},
{"missing counts", `{}`, true},
{"negative", `{"total":-1,"updated":-1}`, true},
{"conflict", `{"total":1,"updated":1,"version_conflicts":1}`, true},
{"timeout", `{"total":1,"updated":1,"timed_out":true}`, true},
} {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
if r.URL.Path == "/" {
_, _ = w.Write(
[]byte(
`{"version":{"number":"7.17.0","build_flavor":"default"},"tagline":"You Know, for Search"}`,
),
)
return
}
if r.URL.Path != "/vectors/_update_by_query" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
_, _ = w.Write([]byte(tt.body))
}))
defer server.Close()
client, err := elasticsearch.NewClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, "file")
if tt.fails {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
package v7
import (
"context"
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
)
// Regression test for #3156: the script_score source must floor the cosine
// similarity at 0. An unclamped negative cosine makes Lucene reject the whole
// search request ("script_score script returned an invalid score ... Must be a
// non-negative score!"), turning one dissimilar document into a full vector
// retrieval outage (all shards failed).
func TestVectorScoreScriptSourceClampsNegativeCosine(t *testing.T) {
require.Equal(t,
"Math.max(cosineSimilarity(params.query_vector,'embedding'), 0.0)",
vectorScoreScriptSource)
}
// The marshaled query body must carry the clamped script source end to end.
func TestBuildVectorSearchQueryClampsScriptScore(t *testing.T) {
e := &elasticsearchRepository{}
params := typesLocal.RetrieveParams{
Embedding: []float32{-1, 0},
Threshold: 0.15,
TopK: 5,
KnowledgeBaseIDs: []string{"kb-1"},
}
query, err := e.buildVectorSearchQuery(context.Background(), params)
require.NoError(t, err)
var body struct {
Query struct {
ScriptScore struct {
Script struct {
Source string `json:"source"`
} `json:"script"`
MinScore float64 `json:"min_score"`
} `json:"script_score"`
} `json:"query"`
}
require.NoError(t, json.Unmarshal([]byte(query), &body))
require.Equal(t,
"Math.max(cosineSimilarity(params.query_vector,'embedding'), 0.0)",
body.Query.ScriptScore.Script.Source)
require.InDelta(t, 0.15, body.Query.ScriptScore.MinScore, 1e-6)
}
@@ -0,0 +1,146 @@
package v8
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
"academy/internal/types/interfaces"
"github.com/elastic/go-elasticsearch/v8"
)
// bulkReasonSentinel stands for document content that a per-item error.reason
// can carry; the error returned to the caller must never include it.
const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY"
// fakeBulkServer answers every request the v8 repository makes while BatchSave
// runs, and returns body for the _bulk call.
type fakeBulkServer struct {
body string
calls int
}
func (f *fakeBulkServer) handler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
switch {
case strings.HasSuffix(r.URL.Path, "/_bulk"):
f.calls++
_, _ = io.WriteString(w, f.body)
case strings.HasSuffix(r.URL.Path, "/_mapping"):
_, _ = io.WriteString(w,
`{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`)
case r.Method == http.MethodHead:
w.WriteHeader(http.StatusNotFound)
default:
_, _ = io.WriteString(w,
`{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`)
}
}
}
// newBulkTestRepository builds the repository through its public constructor
// against a fake Elasticsearch that answers _bulk with body.
func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) {
t.Helper()
fake := &fakeBulkServer{body: body}
server := httptest.NewServer(fake.handler())
t.Cleanup(server.Close)
client, err := elasticsearch.NewTypedClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
return NewElasticsearchEngineRepository(client, nil, nil), fake
}
func bulkTestIndexInfos() []*typesLocal.IndexInfo {
return []*typesLocal.IndexInfo{
{
Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
{
Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
}
}
func bulkTestParams() map[string]any {
return map[string]any{
"embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}},
}
}
// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832:
// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document
// rejected for a mapping mismatch, a read-only index or an item-level
// rejection is visible only in the response body. BatchSave must surface those
// per-item failures to the caller.
func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) {
cases := []struct {
name string
body string
wantContains []string
}{
{
name: "all documents rejected",
body: `{"took":1,"errors":true,"items":[` +
`{"create":{"_id":"chunk-1","status":400,` +
`"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` +
`{"create":{"_id":"chunk-2","status":429,` +
`"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{
"2/2 documents failed",
"chunk-1", "mapper_parsing_exception",
"chunk-2", "es_rejected_execution_exception",
},
},
{
name: "partial failure",
body: `{"took":1,"errors":true,"items":[` +
`{"create":{"_id":"chunk-1","status":201,"result":"created"}},` +
`{"create":{"_id":"chunk-2","status":400,` +
`"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
repo, fake := newBulkTestRepository(t, tc.body)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.Error(t, err)
for _, want := range tc.wantContains {
assert.Contains(t, err.Error(), want)
}
assert.NotContains(t, err.Error(), bulkReasonSentinel,
"the returned error must not carry error.reason")
})
}
t.Run("all documents accepted", func(t *testing.T) {
repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+
`{"create":{"_id":"chunk-1","status":201,"result":"created"}},`+
`{"create":{"_id":"chunk-2","status":201,"result":"created"}}]}`)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.NoError(t, err)
})
}
@@ -0,0 +1,142 @@
package v8
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/elastic/go-elasticsearch/v8"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// copySourceHits covers every source_id shape CopyIndices remaps: a regular
// chunk row, a generated-question row sharing that chunk, a row with an
// unrelated source_id (remapped to a fresh uuid), and a legacy row written
// before is_enabled existed.
const copySourceHits = `[
{"_index":"vectors","_id":"d1","_score":1,"_source":{"content":"chunk","source_id":"c1","source_type":0,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.1,0.2],"is_enabled":true}},
{"_index":"vectors","_id":"d2","_score":1,"_source":{"content":"question","source_id":"c1-q1","source_type":1,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.3,0.4],"is_enabled":true}},
{"_index":"vectors","_id":"d3","_score":1,"_source":{"content":"summary","source_id":"img-9","source_type":2,
"chunk_id":"c2","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.5,0.6],"is_enabled":false}},
{"_index":"vectors","_id":"d4","_score":1,"_source":{"content":"legacy","source_id":"c3","source_type":0,
"chunk_id":"c3","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.7,0.8]}}
]`
type copiedDoc struct {
Content string `json:"content"`
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"`
Embedding []float32 `json:"embedding"`
IsEnabled *bool `json:"is_enabled"`
}
// fakeCopyServer serves one page of copySourceHits and records the search
// query and every document sent through _bulk.
type fakeCopyServer struct {
mu sync.Mutex
searchQuery string
docs []copiedDoc
}
func (f *fakeCopyServer) handler(t *testing.T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
body, _ := io.ReadAll(r.Body)
f.mu.Lock()
defer f.mu.Unlock()
switch r.URL.Path {
case "/vectors/_search":
f.searchQuery = string(body)
_, _ = w.Write([]byte(`{"took":1,"timed_out":false,` +
`"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},` +
`"hits":{"total":{"value":4,"relation":"eq"},"hits":` + copySourceHits + `}}`))
case "/vectors/_bulk":
sc := bufio.NewScanner(bytes.NewReader(body))
sc.Buffer(make([]byte, 0, 1<<20), 1<<20)
for sc.Scan() {
line := sc.Bytes()
var probe map[string]json.RawMessage
require.NoError(t, json.Unmarshal(line, &probe))
if _, ok := probe["content"]; !ok {
continue // action line
}
var doc copiedDoc
require.NoError(t, json.Unmarshal(line, &doc))
f.docs = append(f.docs, doc)
}
_, _ = w.Write([]byte(`{"took":1,"errors":false,"items":[]}`))
default:
t.Errorf("unexpected path: %s", r.URL.Path)
}
}
}
func TestCopyIndicesKeepsVectorsAndEnabledState(t *testing.T) {
fake := &fakeCopyServer{}
server := httptest.NewServer(fake.handler(t))
defer server.Close()
client, err := elasticsearch.NewTypedClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.CopyIndices(context.Background(), "kb-src",
map[string]string{"k1": "tk1"},
map[string]string{"c1": "t1", "c2": "t2", "c3": "t3"},
"kb-dst", 2, "manual")
require.NoError(t, err)
assert.NotContains(t, fake.searchQuery, "is_enabled",
"the copy scan must include disabled source rows so they stay disabled, not vanish")
require.Len(t, fake.docs, 4)
byContent := make(map[string]copiedDoc, len(fake.docs))
for _, d := range fake.docs {
byContent[d.Content] = d
assert.Equal(t, "tk1", d.KnowledgeID)
assert.Equal(t, "kb-dst", d.KnowledgeBaseID)
require.NotNil(t, d.IsEnabled, "is_enabled must be written for %q", d.Content)
}
chunk := byContent["chunk"]
assert.Equal(t, "t1", chunk.ChunkID)
assert.Equal(t, "t1", chunk.SourceID)
assert.Equal(t, 0, chunk.SourceType)
assert.Equal(t, []float32{0.1, 0.2}, chunk.Embedding)
assert.True(t, *chunk.IsEnabled)
question := byContent["question"]
assert.Equal(t, "t1", question.ChunkID)
assert.Equal(t, "t1-q1", question.SourceID)
assert.Equal(t, 1, question.SourceType)
assert.Equal(t, []float32{0.3, 0.4}, question.Embedding)
assert.True(t, *question.IsEnabled)
summary := byContent["summary"]
assert.Equal(t, "t2", summary.ChunkID)
assert.NotEqual(t, "img-9", summary.SourceID)
assert.False(t, strings.HasPrefix(summary.SourceID, "t2"), "unrelated source ids get a fresh uuid")
assert.Equal(t, 2, summary.SourceType)
assert.Equal(t, []float32{0.5, 0.6}, summary.Embedding)
assert.False(t, *summary.IsEnabled)
legacy := byContent["legacy"]
assert.Equal(t, "t3", legacy.SourceID)
assert.Equal(t, []float32{0.7, 0.8}, legacy.Embedding)
assert.True(t, *legacy.IsEnabled, "a source row without is_enabled is enabled for retrieval")
}
@@ -0,0 +1,48 @@
// Package v8 implements retrieval against its configured vector backend.
package v8
import (
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
)
func (e *elasticsearchRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
_ int,
_ string,
) error {
query := &types.Query{Bool: &types.BoolQuery{Filter: []types.Query{
{
Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_base_id"): []string{sourceKB}},
},
},
{
Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_id"): []string{knowledgeID}},
},
},
}}}
source := "ctx._source.knowledge_base_id = params.target; ctx._source.tag_id = ''"
target, err := json.Marshal(targetKB)
if err != nil {
return err
}
script := &types.Script{Source: &source, Params: map[string]json.RawMessage{"target": target}}
result, err := e.client.UpdateByQuery(e.index).Query(query).Script(script).Refresh(true).Do(ctx)
if err != nil {
return err
}
if result == nil || result.Total == nil || result.Updated == nil ||
*result.Total < 0 || *result.Total != *result.Updated || (result.TimedOut != nil && *result.TimedOut) ||
(result.VersionConflicts != nil && *result.VersionConflicts != 0) ||
len(result.Failures) != 0 {
return fmt.Errorf("move indices was incomplete")
}
return nil
}
@@ -0,0 +1,59 @@
package v8
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/elastic/go-elasticsearch/v8"
"github.com/stretchr/testify/require"
)
func TestMoveIndicesRequiresCompleteCounts(t *testing.T) {
for _, tt := range []struct {
name, body string
fails bool
}{
{"complete", `{"total":100,"updated":100}`, false},
{"empty retry", `{"total":0,"updated":0}`, false},
{"partial", `{"total":100,"updated":40}`, true},
{"missing total", `{"updated":40}`, true},
{"missing updated", `{"total":40}`, true},
{"missing counts", `{}`, true},
{"negative", `{"total":-1,"updated":-1}`, true},
{"conflict", `{"total":1,"updated":1,"version_conflicts":1}`, true},
{"timeout", `{"total":1,"updated":1,"timed_out":true}`, true},
} {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
if r.URL.Path == "/" {
_, _ = w.Write(
[]byte(
`{"version":{"number":"7.17.0","build_flavor":"default"},"tagline":"You Know, for Search"}`,
),
)
return
}
if r.URL.Path != "/vectors/_update_by_query" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
_, _ = w.Write([]byte(tt.body))
}))
defer server.Close()
client, err := elasticsearch.NewTypedClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, "file")
if tt.fails {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
@@ -0,0 +1,897 @@
package v8
import (
"context"
"encoding/json"
"fmt"
"strings"
elasticsearchRetriever "academy/internal/application/repository/retriever/elasticsearch"
"academy/internal/config"
"academy/internal/logger"
typesLocal "academy/internal/types"
"academy/internal/types/interfaces"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/bulk"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/scriptlanguage"
"github.com/google/uuid"
)
// elasticsearchRepository implements the RetrieveEngineRepository interface for Elasticsearch v8
type elasticsearchRepository struct {
client *elasticsearch.TypedClient // Elasticsearch client instance
index string // Name of the Elasticsearch index to use
useKeywordSuffix bool // Whether to append .keyword suffix to ID field names in queries
numberOfShards int // Shard count for index creation (0 = ES default)
numberOfReplicas int // Replica count for index creation (-1 = unset, use ES default)
}
// NewElasticsearchEngineRepository creates and initializes a new Elasticsearch v8 repository.
// indexCfg is optional — pass nil to use env var / default values (env path).
func NewElasticsearchEngineRepository(client *elasticsearch.TypedClient,
config *config.Config,
indexCfg *typesLocal.IndexConfig,
) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[Elasticsearch] Initializing Elasticsearch v8 retriever engine repository")
indexName := typesLocal.ResolveIndexName(indexCfg, "ELASTICSEARCH_INDEX", "xwrag_default")
// Create repository instance and ensure index exists
res := &elasticsearchRepository{
client: client,
index: indexName,
numberOfShards: indexCfg.GetNumberOfShards(0),
numberOfReplicas: indexCfg.GetNumberOfReplicas(-1),
}
if err := res.createIndexIfNotExists(context.Background()); err != nil {
log.Errorf("[Elasticsearch] Failed to create index: %v", err)
} else {
log.Info("[Elasticsearch] Successfully initialized repository")
}
res.detectFieldTypes(context.Background())
return res
}
// idField returns the query field name for an ID field, appending ".keyword"
// suffix when the index uses text-type mappings with keyword sub-fields.
func (e *elasticsearchRepository) idField(name string) string {
if e.useKeywordSuffix {
return name + ".keyword"
}
return name
}
// detectFieldTypes inspects the index mapping to determine whether ID fields
// are mapped as "keyword" (no suffix needed) or "text" (needs ".keyword" suffix).
func (e *elasticsearchRepository) detectFieldTypes(ctx context.Context) {
log := logger.GetLogger(ctx)
mappingResp, err := e.client.Indices.GetMapping().Index(e.index).Do(ctx)
if err != nil {
log.Warnf("[Elasticsearch] Failed to get index mapping, defaulting to .keyword suffix: %v", err)
e.useKeywordSuffix = true
return
}
indexMapping, ok := mappingResp[e.index]
if !ok {
log.Warnf("[Elasticsearch] Index %s not found in mapping response, defaulting to .keyword suffix", e.index)
e.useKeywordSuffix = true
return
}
if prop, ok := indexMapping.Mappings.Properties["chunk_id"]; ok {
propBytes, err := json.Marshal(prop)
if err == nil {
var propInfo struct {
Type string `json:"type"`
}
if json.Unmarshal(propBytes, &propInfo) == nil && propInfo.Type == "keyword" {
e.useKeywordSuffix = false
log.Infof("[Elasticsearch] Detected keyword type for ID fields, querying without .keyword suffix")
return
}
}
e.useKeywordSuffix = true
log.Infof("[Elasticsearch] ID fields are not keyword type, querying with .keyword suffix")
return
}
log.Infof("[Elasticsearch] No mapping detected for chunk_id (empty index?), defaulting to .keyword suffix")
e.useKeywordSuffix = true
}
// EngineType returns the type of retriever engine (Elasticsearch)
func (e *elasticsearchRepository) EngineType() typesLocal.RetrieverEngineType {
return typesLocal.ElasticsearchRetrieverEngineType
}
// Support returns the retrieval types supported by this repository (Keywords and Vector)
func (e *elasticsearchRepository) Support() []typesLocal.RetrieverType {
return []typesLocal.RetrieverType{typesLocal.KeywordsRetrieverType, typesLocal.VectorRetrieverType}
}
// calculateStorageSize estimates the storage size in bytes for a single index document
func (e *elasticsearchRepository) calculateStorageSize(embedding *elasticsearchRetriever.VectorEmbedding) int64 {
// 1. Content text size
contentSizeBytes := int64(len(embedding.Content))
// 2. Vector embedding size
var vectorSizeBytes int64 = 0
if embedding.Embedding != nil {
// 4 bytes per dimension (full precision float)
vectorSizeBytes = int64(len(embedding.Embedding) * 4)
}
// 3. Metadata size (IDs, timestamps, and other fixed overhead)
metadataSizeBytes := int64(250) // Approximately 250 bytes of metadata
// 4. Index overhead (Elasticsearch index expansion factor ~1.5)
indexOverheadBytes := (contentSizeBytes + vectorSizeBytes) * 5 / 10
// Total size in bytes
totalSizeBytes := contentSizeBytes + vectorSizeBytes + metadataSizeBytes + indexOverheadBytes
return totalSizeBytes
}
// EstimateStorageSize calculates the estimated storage size for a list of indices
// Returns the total size in bytes
func (e *elasticsearchRepository) EstimateStorageSize(ctx context.Context,
indexInfoList []*typesLocal.IndexInfo, params map[string]any,
) int64 {
var totalStorageSize int64 = 0
for _, embedding := range indexInfoList {
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, params)
totalStorageSize += e.calculateStorageSize(embeddingDB)
}
logger.GetLogger(ctx).Infof(
"[Elasticsearch] Storage size for %d indices: %d bytes", len(indexInfoList), totalStorageSize,
)
return totalStorageSize
}
// Save stores a single index document in Elasticsearch
// Returns an error if the operation fails
func (e *elasticsearchRepository) Save(ctx context.Context,
embedding *typesLocal.IndexInfo,
additionalParams map[string]any,
) error {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Saving index for chunk ID: %s", embedding.ChunkID)
// Convert to database format
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, additionalParams)
if len(embeddingDB.Embedding) == 0 {
err := fmt.Errorf("empty embedding vector for chunk ID: %s", embedding.ChunkID)
log.Errorf("[Elasticsearch] %v", err)
return err
}
// Index the document
resp, err := e.client.Index(e.index).Request(embeddingDB).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to save index: %v", err)
return err
}
log.Infof("[Elasticsearch] Successfully saved index for chunk ID: %s, document ID: %s", embedding.ChunkID, resp.Id_)
return nil
}
// BatchSave stores multiple index documents in Elasticsearch using bulk API
// Returns an error if the operation fails
func (e *elasticsearchRepository) BatchSave(ctx context.Context,
embeddingList []*typesLocal.IndexInfo, additionalParams map[string]any,
) error {
log := logger.GetLogger(ctx)
if len(embeddingList) == 0 {
log.Warn("[Elasticsearch] Empty list provided to BatchSave, skipping")
return nil
}
log.Infof("[Elasticsearch] Batch saving %d indices", len(embeddingList))
indexRequest := e.client.Bulk().Index(e.index)
// Add each document to the bulk request
for _, embedding := range embeddingList {
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, additionalParams)
err := indexRequest.CreateOp(types.CreateOperation{Index_: &e.index}, embeddingDB)
if err != nil {
log.Errorf("[Elasticsearch] Failed to create bulk operation: %v", err)
return fmt.Errorf("failed to create op: %w", err)
}
log.Debugf("[Elasticsearch] Added chunk ID %s to bulk request", embedding.ChunkID)
}
// Execute the bulk request. Elasticsearch answers an accepted _bulk call
// with HTTP 200 even when it rejects individual documents, so the
// per-item errors in the response body are the only failure signal.
resp, err := indexRequest.Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to execute bulk operation: %v", err)
return fmt.Errorf("failed to do bulk: %w", err)
}
if err := inspectBulkResponse(ctx, resp); err != nil {
return err
}
log.Infof("[Elasticsearch] Successfully batch saved %d indices", len(embeddingList))
return nil
}
// bulkErrorSummaryLimit caps how many per-item failures are described in the
// returned error; the reported count always covers every failed item.
const bulkErrorSummaryLimit = 5
// inspectBulkResponse converts per-item _bulk failures into an error. A bulk
// request that the server accepted answers HTTP 200, so a document rejected
// for a mapping mismatch, a read-only index or an item-level rejection is
// visible only in the response body.
//
// The error names the document _id and the bounded error.type of up to
// bulkErrorSummaryLimit failed items. error.reason is deliberately excluded
// because it can embed document content.
func inspectBulkResponse(ctx context.Context, resp *bulk.Response) error {
if resp == nil || !resp.Errors {
return nil
}
log := logger.GetLogger(ctx)
msgs := make([]string, 0, bulkErrorSummaryLimit)
failed := 0
for _, item := range resp.Items {
for op, detail := range item {
if detail.Error == nil {
continue
}
failed++
id := ""
if detail.Id_ != nil {
id = *detail.Id_
}
log.Debugf("[Elasticsearch] Bulk item failed: op=%s id=%s type=%s",
op, id, detail.Error.Type)
if len(msgs) < bulkErrorSummaryLimit {
msgs = append(msgs, fmt.Sprintf("[%s %s] %s", op, id, detail.Error.Type))
}
}
}
if failed == 0 {
return fmt.Errorf("elasticsearch: bulk reported errors without per-item failure detail")
}
return fmt.Errorf("elasticsearch: bulk partial failure (%d/%d documents failed, first %d: %s)",
failed, len(resp.Items), len(msgs), strings.Join(msgs, "; "))
}
// DeleteByChunkIDList removes documents from the index based on chunk IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int, knowledgeType string) error {
log := logger.GetLogger(ctx)
if len(chunkIDList) == 0 {
log.Warn("[Elasticsearch] Empty chunk ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by chunk IDs, count: %d", len(chunkIDList))
// Use DeleteByQuery to delete all documents matching the chunk IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{e.idField("chunk_id"): chunkIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by chunk IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by chunk IDs")
return nil
}
// DeleteBySourceIDList removes documents from the index based on source IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int, knowledgeType string) error {
log := logger.GetLogger(ctx)
if len(sourceIDList) == 0 {
log.Warn("[Elasticsearch] Empty source ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by source IDs, count: %d", len(sourceIDList))
// Use DeleteByQuery to delete all documents matching the source IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{e.idField("source_id"): sourceIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by source IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by source IDs")
return nil
}
// DeleteByKnowledgeIDList removes documents from the index based on knowledge IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteByKnowledgeIDList(ctx context.Context,
knowledgeIDList []string, dimension int, knowledgeType string,
) error {
log := logger.GetLogger(ctx)
if len(knowledgeIDList) == 0 {
log.Warn("[Elasticsearch] Empty knowledge ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by knowledge IDs, count: %d", len(knowledgeIDList))
// Use DeleteByQuery to delete all documents matching the knowledge IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_id"): knowledgeIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by knowledge IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by knowledge IDs")
return nil
}
// getBaseConds creates the base query conditions for retrieval operations
// Returns a slice of Query objects with must and must_not conditions
// KnowledgeBaseIDs and KnowledgeIDs use AND logic (search specific documents within knowledge bases)
func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams) []types.Query {
must := []types.Query{}
// KnowledgeBaseIDs and KnowledgeIDs use AND logic
// - If only KnowledgeBaseIDs: search entire knowledge bases
// - If only KnowledgeIDs: search specific documents
// - If both: search specific documents within the knowledge bases (AND)
if len(params.KnowledgeBaseIDs) > 0 {
must = append(must, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("knowledge_base_id"): params.KnowledgeBaseIDs,
},
}})
}
if len(params.KnowledgeIDs) > 0 {
must = append(must, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("knowledge_id"): params.KnowledgeIDs,
},
}})
}
// Filter by tag IDs if specified
if len(params.TagIDs) > 0 {
must = append(must, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("tag_id"): params.TagIDs,
},
}})
}
mustNot := make([]types.Query, 0)
// Exclude disabled chunks (is_enabled = false)
// Note: Historical data without is_enabled field will be included (not matching must_not)
mustNot = append(mustNot, types.Query{Term: map[string]types.TermQuery{
"is_enabled": {Value: false},
}})
if len(params.ExcludeKnowledgeIDs) > 0 {
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_id"): params.ExcludeKnowledgeIDs},
}})
}
if len(params.ExcludeChunkIDs) > 0 {
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("chunk_id"): params.ExcludeChunkIDs},
}})
}
return []types.Query{{Bool: &types.BoolQuery{Must: must, MustNot: mustNot}}}
}
// createIndexIfNotExists checks if the specified index exists and creates it if not
// Returns an error if the operation fails
func (e *elasticsearchRepository) createIndexIfNotExists(ctx context.Context) error {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Checking if index exists: %s", e.index)
// Check if index exists
exists, err := e.client.Indices.Exists(e.index).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to check if index exists: %v", err)
return err
}
if exists {
log.Debugf("[Elasticsearch] Index already exists: %s", e.index)
return nil
}
// Create index if it doesn't exist, with optional shards/replicas settings
log.Infof("[Elasticsearch] Creating index: %s", e.index)
createReq := e.client.Indices.Create(e.index)
if e.numberOfShards > 0 || e.numberOfReplicas >= 0 {
settings := &types.IndexSettings{}
if e.numberOfShards > 0 {
shards := fmt.Sprintf("%d", e.numberOfShards)
settings.NumberOfShards = &shards
}
if e.numberOfReplicas >= 0 {
replicas := fmt.Sprintf("%d", e.numberOfReplicas)
settings.NumberOfReplicas = &replicas
}
createReq = createReq.Settings(settings)
}
_, err = createReq.Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to create index: %v", err)
return err
}
log.Infof("[Elasticsearch] Index created successfully: %s", e.index)
return nil
}
// Retrieve dispatches the retrieval operation to the appropriate method based on retriever type
// Returns a slice of RetrieveResult and an error if the operation fails
func (e *elasticsearchRepository) Retrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Processing retrieval request of type: %s", params.RetrieverType)
// Route to appropriate retrieval method
switch params.RetrieverType {
case typesLocal.VectorRetrieverType:
return e.VectorRetrieve(ctx, params)
case typesLocal.KeywordsRetrieverType:
return e.KeywordsRetrieve(ctx, params)
}
err := fmt.Errorf("invalid retriever type: %v", params.RetrieverType)
log.Errorf("[Elasticsearch] %v", err)
return nil, err
}
// vectorScoreScriptSource scores every document by its cosine similarity to the
// query vector, floored at 0. Lucene rejects negative final script_score values
// ("script_score script returned an invalid score ... Must be a non-negative
// score!"), so an unclamped negative cosine — which occurs whenever any stored
// vector points away from the query — fails the entire search request with a
// 400 (all shards failed) instead of merely ranking that document last. The
// floor keeps the score in the [0, 1] range the shared retriever score
// normalizer documents for this engine; documents clamped to 0 fall below any
// positive min_score threshold.
var vectorScoreScriptSource = "Math.max(cosineSimilarity(params.query_vector, 'embedding'), 0.0)"
// buildVectorScriptScoreQuery wraps the cosine-similarity scoring script in a
// script_score query over the request's base filter conditions.
func (e *elasticsearchRepository) buildVectorScriptScoreQuery(
params typesLocal.RetrieveParams,
) (*types.ScriptScoreQuery, error) {
queryVectorJSON, err := json.Marshal(params.Embedding)
if err != nil {
return nil, fmt.Errorf("failed to marshal query embedding: %w", err)
}
minScore := float32(params.Threshold)
return &types.ScriptScoreQuery{
Query: types.Query{Bool: &types.BoolQuery{Filter: e.getBaseConds(params)}},
Script: types.Script{
Source: &vectorScoreScriptSource,
Params: map[string]json.RawMessage{
"query_vector": json.RawMessage(queryVectorJSON),
},
},
MinScore: &minScore,
}, nil
}
// VectorRetrieve performs vector similarity search using cosine similarity
// Returns a slice of RetrieveResult containing matching documents
func (e *elasticsearchRepository) VectorRetrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Infof("[Elasticsearch] Vector retrieval: dim=%d, topK=%d, threshold=%.4f",
len(params.Embedding), params.TopK, params.Threshold)
scriptScore, err := e.buildVectorScriptScoreQuery(params)
if err != nil {
log.Errorf("[Elasticsearch] Failed to marshal query vector: %v", err)
return nil, err
}
// Exclude embedding field from source to reduce response size
sourceFilter := &types.SourceFilter{
Excludes: []string{"embedding"},
}
log.Debugf("[Elasticsearch] Executing vector search in index: %s", e.index)
// Execute search with minimum score threshold
response, err := e.client.Search().Index(e.index).Request(&search.Request{
Query: &types.Query{ScriptScore: scriptScore},
Size: &params.TopK,
Source_: sourceFilter,
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Vector search failed: %v", err)
return nil, err
}
// Process search results
var results []*typesLocal.IndexWithScore
for _, hit := range response.Hits.Hits {
var embedding *elasticsearchRetriever.VectorEmbeddingWithScore
if err := json.Unmarshal(hit.Source_, &embedding); err != nil {
log.Errorf("[Elasticsearch] Failed to unmarshal search result: %v", err)
return nil, err
}
embedding.Score = float64(*hit.Score_)
results = append(results,
elasticsearchRetriever.FromDBVectorEmbeddingWithScore(*hit.Id_, embedding, typesLocal.MatchTypeEmbedding))
}
if len(results) == 0 {
log.Warnf("[Elasticsearch] No vector matches found that meet threshold %.4f", params.Threshold)
} else {
log.Infof("[Elasticsearch] Vector retrieval found %d results", len(results))
log.Debugf("[Elasticsearch] Top result score: %.4f", results[0].Score)
}
return []*typesLocal.RetrieveResult{
{
Results: results,
RetrieverEngineType: typesLocal.ElasticsearchRetrieverEngineType,
RetrieverType: typesLocal.VectorRetrieverType,
Error: nil,
},
}, nil
}
// KeywordsRetrieve performs keyword-based search in document content
// Returns a slice of RetrieveResult containing matching documents
func (e *elasticsearchRepository) KeywordsRetrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Infof("[Elasticsearch] Performing keywords retrieval with query: %s, topK: %d", params.Query, params.TopK)
filter := e.getBaseConds(params)
// Build must conditions for content matching
must := []types.Query{
{Match: map[string]types.MatchQuery{"content": {Query: params.Query}}},
}
// Exclude embedding field from source to reduce response size
sourceFilter := &types.SourceFilter{
Excludes: []string{"embedding"},
}
log.Debugf("[Elasticsearch] Executing keyword search in index: %s", e.index)
response, err := e.client.Search().Index(e.index).Request(&search.Request{
Query: &types.Query{Bool: &types.BoolQuery{Filter: filter, Must: must}},
Size: &params.TopK,
Source_: sourceFilter,
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Keywords search failed: %v", err)
return nil, err
}
// Process search results
var results []*typesLocal.IndexWithScore
for _, hit := range response.Hits.Hits {
var embedding *elasticsearchRetriever.VectorEmbeddingWithScore
if err := json.Unmarshal(hit.Source_, &embedding); err != nil {
log.Errorf("[Elasticsearch] Failed to unmarshal search result: %v", err)
return nil, err
}
embedding.Score = float64(*hit.Score_)
results = append(results,
elasticsearchRetriever.FromDBVectorEmbeddingWithScore(*hit.Id_, embedding, typesLocal.MatchTypeKeywords),
)
}
if len(results) == 0 {
log.Warnf("[Elasticsearch] No keyword matches found for query: %s", params.Query)
} else {
log.Infof("[Elasticsearch] Keywords retrieval found %d results", len(results))
log.Debugf("[Elasticsearch] Top result score: %.4f", results[0].Score)
}
return []*typesLocal.RetrieveResult{
{
Results: results,
RetrieverEngineType: typesLocal.ElasticsearchRetrieverEngineType,
RetrieverType: typesLocal.KeywordsRetrieverType,
Error: nil,
},
}, nil
}
// copySourceDoc decodes a source row for CopyIndices. IsEnabled shadows the
// embedded field so a row written before is_enabled existed, which retrieval
// treats as enabled, can be told apart from an explicit false.
type copySourceDoc struct {
elasticsearchRetriever.VectorEmbedding
IsEnabled *bool `json:"is_enabled"`
}
// CopyIndices 复制索引数据
func (e *elasticsearchRepository) CopyIndices(ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
knowledgeType string,
) error {
log := logger.GetLogger(ctx)
log.Infof(
"[Elasticsearch] Copying indices from source knowledge base %s to target knowledge base %s, count: %d",
sourceKnowledgeBaseID, targetKnowledgeBaseID, len(sourceToTargetChunkIDMap),
)
if len(sourceToTargetChunkIDMap) == 0 {
log.Warn("[Elasticsearch] Empty mapping, skipping copy")
return nil
}
// Scan every row of the source knowledge base. getBaseConds is not used
// here because it drops disabled rows, which must be copied as disabled.
filter := []types.Query{{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("knowledge_base_id"): []string{sourceKnowledgeBaseID},
},
}}}
// Set batch processing parameters
batchSize := 500
from := 0
totalCopied := 0
for {
// Execute pagination query
searchResponse, err := e.client.Search().Index(e.index).
Query(&types.Query{Bool: &types.BoolQuery{Filter: filter}}).
From(from).
Size(batchSize).
Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to query source index data: %v", err)
return err
}
hitsCount := len(searchResponse.Hits.Hits)
if hitsCount == 0 {
break
}
log.Infof("[Elasticsearch] Found %d source index data, batch start position: %d", hitsCount, from)
// Prepare index list for BatchSave
var indexInfoList []*typesLocal.IndexInfo
// Collect all embedding vector data for additionalParams
embeddingMap := make(map[string][]float32)
for _, hit := range searchResponse.Hits.Hits {
// Parse source document
var sourceDoc copySourceDoc
if err := json.Unmarshal(hit.Source_, &sourceDoc); err != nil {
log.Errorf("[Elasticsearch] Failed to parse source index data: %v", err)
continue
}
// Get mapped target chunk ID and knowledge ID
targetChunkID, ok := sourceToTargetChunkIDMap[sourceDoc.ChunkID]
if !ok {
log.Warnf("[Elasticsearch] Source chunk %s not found in target mapping, skipping", sourceDoc.ChunkID)
continue
}
targetKnowledgeID, ok := sourceToTargetKBIDMap[sourceDoc.KnowledgeID]
if !ok {
log.Warnf(
"[Elasticsearch] Source knowledge %s not found in target mapping, skipping",
sourceDoc.KnowledgeID,
)
continue
}
// Handle SourceID transformation for generated questions
// Generated questions have SourceID format: {chunkID}-{questionID}
// Regular chunks have SourceID == ChunkID
var targetSourceID string
if sourceDoc.SourceID == sourceDoc.ChunkID {
// Regular chunk, use targetChunkID as SourceID
targetSourceID = targetChunkID
} else if strings.HasPrefix(sourceDoc.SourceID, sourceDoc.ChunkID+"-") {
// This is a generated question, preserve the questionID part
questionID := strings.TrimPrefix(sourceDoc.SourceID, sourceDoc.ChunkID+"-")
targetSourceID = fmt.Sprintf("%s-%s", targetChunkID, questionID)
} else {
// For other complex scenarios, generate new unique SourceID
targetSourceID = uuid.New().String()
}
// BatchSave looks embeddings up by SourceID, so key by the target
// SourceID; rows of one chunk would collide on the chunk ID.
if len(sourceDoc.Embedding) > 0 {
embeddingMap[targetSourceID] = sourceDoc.Embedding
}
// Create new index information
indexInfo := &typesLocal.IndexInfo{
Content: sourceDoc.Content,
SourceID: targetSourceID,
SourceType: typesLocal.SourceType(sourceDoc.SourceType),
ChunkID: targetChunkID,
KnowledgeID: targetKnowledgeID,
KnowledgeBaseID: targetKnowledgeBaseID,
IsEnabled: sourceDoc.IsEnabled == nil || *sourceDoc.IsEnabled,
}
indexInfoList = append(indexInfoList, indexInfo)
totalCopied++
}
// Use BatchSave function to save index
if len(indexInfoList) > 0 {
// Add embedding vector to additional parameters
additionalParams := map[string]any{
"embedding": embeddingMap,
}
if err := e.BatchSave(ctx, indexInfoList, additionalParams); err != nil {
log.Errorf("[Elasticsearch] Failed to batch save index: %v", err)
return err
}
log.Infof("[Elasticsearch] Successfully copied batch data, batch size: %d, total copied: %d",
len(indexInfoList), totalCopied)
}
// Move to next batch
from += hitsCount
// If the number of returned records is less than the request size, it means the last page has been reached
if hitsCount < batchSize {
break
}
}
log.Infof("[Elasticsearch] Index copy completed, total copied: %d", totalCopied)
return nil
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(
ctx context.Context,
chunkStatusMap map[string]bool,
) error {
log := logger.GetLogger(ctx)
if len(chunkStatusMap) == 0 {
log.Warnf("[Elasticsearch] Chunk status map is empty, skipping update")
return nil
}
log.Infof("[Elasticsearch] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
// Group chunks by enabled status for batch updates
enabledChunkIDs := make([]string, 0)
disabledChunkIDs := make([]string, 0)
for chunkID, enabled := range chunkStatusMap {
if enabled {
enabledChunkIDs = append(enabledChunkIDs, chunkID)
} else {
disabledChunkIDs = append(disabledChunkIDs, chunkID)
}
}
// Batch update enabled chunks using update_by_query
if len(enabledChunkIDs) > 0 {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("chunk_id"): enabledChunkIDs,
},
}},
},
}
source := "ctx._source.is_enabled = true"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update enabled chunks: %v", err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to enabled", len(enabledChunkIDs))
}
// Batch update disabled chunks using update_by_query
if len(disabledChunkIDs) > 0 {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("chunk_id"): disabledChunkIDs,
},
}},
},
}
source := "ctx._source.is_enabled = false"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update disabled chunks: %v", err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to disabled", len(disabledChunkIDs))
}
log.Infof("[Elasticsearch] Successfully batch updated chunk enabled status")
return nil
}
// BatchUpdateChunkTagID updates the tag ID of chunks in batch
func (e *elasticsearchRepository) BatchUpdateChunkTagID(
ctx context.Context,
chunkTagMap map[string]string,
) error {
log := logger.GetLogger(ctx)
if len(chunkTagMap) == 0 {
log.Warnf("[Elasticsearch] Chunk tag map is empty, skipping update")
return nil
}
log.Infof("[Elasticsearch] Batch updating chunk tag ID, count: %d", len(chunkTagMap))
// Group chunks by tag ID for batch updates
tagGroups := make(map[string][]string)
for chunkID, tagID := range chunkTagMap {
tagGroups[tagID] = append(tagGroups[tagID], chunkID)
}
// Batch update chunks for each tag ID using update_by_query
for tagID, chunkIDs := range tagGroups {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("chunk_id"): chunkIDs,
},
}},
},
}
source := "ctx._source.tag_id = params.tag_id"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
Params: map[string]json.RawMessage{
"tag_id": json.RawMessage(`"` + tagID + `"`),
},
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update chunks with tag_id %s: %v", tagID, err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to tag_id=%s", len(chunkIDs), tagID)
}
log.Infof("[Elasticsearch] Successfully batch updated chunk tag ID")
return nil
}
@@ -0,0 +1,49 @@
package v8
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
)
// Regression test for #3156: the script_score source must floor the cosine
// similarity at 0. An unclamped negative cosine makes Lucene reject the whole
// search request ("script_score script returned an invalid score ... Must be a
// non-negative score!"), turning one dissimilar document into a full vector
// retrieval outage (all shards failed).
func TestVectorScoreScriptSourceClampsNegativeCosine(t *testing.T) {
require.Equal(t,
"Math.max(cosineSimilarity(params.query_vector, 'embedding'), 0.0)",
vectorScoreScriptSource)
}
func TestBuildVectorScriptScoreQuery(t *testing.T) {
e := &elasticsearchRepository{}
params := typesLocal.RetrieveParams{
Embedding: []float32{1, 0},
Threshold: 0.15,
TopK: 10,
KnowledgeBaseIDs: []string{"kb-1"},
}
q, err := e.buildVectorScriptScoreQuery(params)
require.NoError(t, err)
require.NotNil(t, q)
require.NotNil(t, q.Script.Source)
require.Equal(t, vectorScoreScriptSource, *q.Script.Source)
require.NotNil(t, q.MinScore)
require.InDelta(t, 0.15, float64(*q.MinScore), 1e-6)
require.NotNil(t, q.Query.Bool)
require.Len(t, q.Query.Bool.Filter, 1)
var queryVector []float32
require.NotNil(t, q.Script.Params["query_vector"])
require.NoError(t, json.Unmarshal(q.Script.Params["query_vector"], &queryVector))
require.Equal(t, []float32{1, 0}, queryVector)
}
@@ -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
}
@@ -0,0 +1,192 @@
// Package neo4j implements the knowledge graph storage and query adapters.
package neo4j
import (
"context"
"fmt"
"strings"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
// NewGraphSearchRepository constructs the bounded public-query adapter.
func NewGraphSearchRepository(driver neo4j.Driver) interfaces.GraphSearchRepository {
return &Neo4jRepository{driver: driver, nodePrefix: "ENTITY"}
}
// graphSearchProjection bounds fields before they cross Bolt. One extra item
// (or character) lets the service report clipping instead of a false total.
func graphSearchProjection(alias string) string {
return alias + ` {
id: elementId(` + alias + `),
name: substring(` + alias + `.name, 0, 513),
knowledge_id: substring(` + alias + `.kg, 0, 129),
chunks: [c IN ` + alias + `.chunks[..513] | substring(c, 0, 129)],
attributes: [a IN ` + alias + `.attributes[..21] | substring(a, 0, 1001)]
}`
}
// graphSearchLabel quotes every identifier. KB IDs are data, never Cypher,
// including imported/legacy IDs containing punctuation or backticks.
func (n *Neo4jRepository) graphSearchLabel(namespace types.NameSpace) (string, error) {
if namespace.KnowledgeBase == "" || namespace.Knowledge != "" {
return "", fmt.Errorf("graph search requires exactly one knowledge base")
}
labels := n.Labels(namespace)
for i, label := range labels {
labels[i] = "`" + strings.ReplaceAll(label, "`", "``") + "`"
}
return strings.Join(labels, ":"), nil
}
// SearchGraph returns ranked seed entities and a bounded one-hop neighbourhood.
func (n *Neo4jRepository) SearchGraph(
ctx context.Context, namespace types.NameSpace, query string,
) (*types.GraphSearchCandidates, error) {
if n.driver == nil {
return nil, nil // Distinguished from an available backend with no matches.
}
label, err := n.graphSearchLabel(namespace)
if err != nil {
return nil, err
}
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeRead})
defer func() {
if err := session.Close(ctx); err != nil {
logger.Warnf(ctx, "Failed to close graph query session: %v", err)
}
}()
value, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
out := &types.GraphSearchCandidates{Graph: &types.GraphData{}}
seedResult, err := tx.Run(ctx, `
MATCH (n:`+label+`)
WHERE n.name CONTAINS $query
WITH n ORDER BY CASE WHEN n.name = $query THEN 0 ELSE 1 END,
size(n.name), n.name, n.kg, elementId(n)
LIMIT $probeLimit
RETURN `+graphSearchProjection("n")+` AS n`,
map[string]any{"query": query, "probeLimit": types.GraphSearchMaxSeeds + 1})
if err != nil {
return nil, err
}
seedIDs := []string{}
seen := map[string]bool{}
for seedResult.Next(ctx) {
if len(seedIDs) == types.GraphSearchMaxSeeds {
out.TruncationReasons = append(out.TruncationReasons, "candidate_seeds")
continue
}
node, err := decodeGraphSearchProjection(seedResult.Record(), "n")
if err != nil {
return nil, err
}
seedIDs = append(seedIDs, node.ID)
seen[node.ID] = true
out.Graph.Node = append(out.Graph.Node, node)
}
if err := seedResult.Err(); err != nil {
return nil, err
}
if len(seedIDs) == 0 {
return out, nil
}
// Keep relation-less seeds, and expand each stored edge only from its
// earliest seed. Target matches cannot reverse the stored direction or
// fill the budget twice. Both endpoints must carry the KB label.
rows, err := tx.Run(ctx, `
UNWIND range(0, size($seeds) - 1) AS seed_index
MATCH (n:`+label+`) WHERE elementId(n) = $seeds[seed_index]
MATCH (n)-[r]-(m:`+label+`)
WHERE NOT elementId(m) IN $seeds[0..seed_index]
WITH n, r, m, seed_index ORDER BY seed_index, elementId(r)
LIMIT $probeLimit
RETURN `+graphSearchProjection("n")+` AS n, `+graphSearchProjection("m")+` AS m,
elementId(r) AS id, elementId(startNode(r)) AS source_id,
elementId(endNode(r)) AS target_id, substring(type(r), 0, 129) AS type`,
map[string]any{"seeds": seedIDs, "probeLimit": types.GraphSearchMaxRows + 1})
if err != nil {
return nil, err
}
count := 0
for rows.Next(ctx) {
if count == types.GraphSearchMaxRows {
out.TruncationReasons = append(out.TruncationReasons, "candidate_relations")
continue
}
count++
for _, alias := range []string{"n", "m"} {
node, err := decodeGraphSearchProjection(rows.Record(), alias)
if err != nil {
return nil, err
}
if !seen[node.ID] {
out.Graph.Node = append(out.Graph.Node, node)
seen[node.ID] = true
}
}
relation := &types.GraphRelation{}
for field, dest := range map[string]*string{
"id": &relation.ID, "source_id": &relation.SourceID,
"target_id": &relation.TargetID, "type": &relation.Type,
} {
v, _, err := neo4j.GetRecordValue[string](rows.Record(), field)
if err != nil || v == "" {
return nil, fmt.Errorf("invalid graph relationship field %s", field)
}
*dest = v
}
if !seen[relation.SourceID] || !seen[relation.TargetID] {
return nil, fmt.Errorf("graph relationship has an unreturned endpoint")
}
out.Graph.Relation = append(out.Graph.Relation, relation)
}
if err := rows.Err(); err != nil {
return nil, err
}
return out, nil
}, neo4j.WithTxTimeout(types.GraphSearchTimeout))
if err != nil {
return nil, err
}
return value.(*types.GraphSearchCandidates), nil
}
func decodeGraphSearchProjection(record *neo4j.Record, alias string) (*types.GraphNode, error) {
if record == nil {
return nil, fmt.Errorf("nil graph search record")
}
value, ok := record.Get(alias)
props, isMap := value.(map[string]any)
if !ok || !isMap {
return nil, fmt.Errorf("invalid graph node projection")
}
node := &types.GraphNode{}
for key, dest := range map[string]*string{"id": &node.ID, "name": &node.Name, "knowledge_id": &node.KnowledgeID} {
value, ok := props[key].(string)
if !ok || value == "" {
return nil, fmt.Errorf("graph node has no %s", key)
}
*dest = value
}
for key, dest := range map[string]*[]string{"chunks": &node.Chunks, "attributes": &node.Attributes} {
*dest = []string{}
if props[key] == nil {
continue
}
values, ok := props[key].([]any)
if !ok {
return nil, fmt.Errorf("invalid graph node %s", key)
}
for _, value := range values {
text, ok := value.(string)
if !ok {
return nil, fmt.Errorf("invalid graph node %s item", key)
}
*dest = append(*dest, text)
}
}
return node, nil
}
@@ -0,0 +1,169 @@
package neo4j
import (
"context"
"fmt"
"os"
"strings"
"testing"
"time"
"academy/internal/types"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGraphSearchLabelAndDisabledBackend(t *testing.T) {
repo := &Neo4jRepository{nodePrefix: "ENTITY"}
label, err := repo.graphSearchLabel(types.NameSpace{KnowledgeBase: "kb-`):MATCH (x)"})
require.NoError(t, err)
require.Equal(t, "`ENTITYkb_``):MATCH (x)`", label)
_, err = repo.graphSearchLabel(types.NameSpace{})
require.Error(t, err)
_, err = repo.graphSearchLabel(types.NameSpace{KnowledgeBase: "kb", Knowledge: "doc"})
require.Error(t, err)
result, err := repo.SearchGraph(context.Background(), types.NameSpace{KnowledgeBase: "kb"}, "Acme")
require.NoError(t, err)
require.Nil(t, result)
}
func TestGraphSearchProjectionValidation(t *testing.T) {
valid := map[string]any{
"id": "n", "name": "Acme", "knowledge_id": "doc",
"chunks": []any{"c1"}, "attributes": []any{"attr"},
}
record := &neo4j.Record{Keys: []string{"n"}, Values: []any{valid}}
node, err := decodeGraphSearchProjection(record, "n")
require.NoError(t, err)
require.Equal(t, []string{"c1"}, node.Chunks)
_, err = decodeGraphSearchProjection(nil, "n")
require.Error(t, err)
for _, key := range []string{"id", "name", "knowledge_id", "chunks", "attributes"} {
props := map[string]any{}
for k, v := range valid {
props[k] = v
}
props[key] = 17
_, err = decodeGraphSearchProjection(&neo4j.Record{Keys: []string{"n"}, Values: []any{props}}, "n")
require.Error(t, err, key)
}
}
func TestGraphSearchIntegration(t *testing.T) {
uri := os.Getenv("ACADEMY_NEO4J_TEST_URI")
if uri == "" {
t.Skip("set ACADEMY_NEO4J_TEST_URI to run the live public graph-query regression")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
driver, err := neo4j.NewDriver(uri, neo4j.NoAuth())
require.NoError(t, err)
t.Cleanup(func() { assert.NoError(t, driver.Close(context.Background())) })
require.NoError(t, driver.VerifyConnectivity(ctx))
repo := NewGraphSearchRepository(driver).(*Neo4jRepository)
// Exercise escaping against a real engine, not only a string assertion.
ns := types.NameSpace{KnowledgeBase: fmt.Sprintf("public_graph_%d_`", time.Now().UnixNano())}
label, err := repo.graphSearchLabel(ns)
require.NoError(t, err)
outsideLabel, err := repo.graphSearchLabel(types.NameSpace{KnowledgeBase: ns.KnowledgeBase + "_outside"})
require.NoError(t, err)
t.Cleanup(func() {
cleanupCtx, stop := context.WithTimeout(context.Background(), 10*time.Second)
defer stop()
_, err := neo4j.ExecuteQuery(cleanupCtx, driver, "MATCH (n:"+label+") DETACH DELETE n",
nil, neo4j.EagerResultTransformer)
assert.NoError(t, err)
})
_, err = neo4j.ExecuteQuery(ctx, driver, `
CREATE (a:`+label+` {name:'Acme', kg:'doc1', chunks:['c1'], attributes:['attr1']}),
(b:`+label+` {name:'Acme Shanghai', kg:'doc1', chunks:['c1'], attributes:[]}),
(a2:`+label+` {name:'Acme', kg:'doc2', chunks:['c2'], attributes:['attr2']}),
(b2:`+label+` {name:'Acme Shanghai', kg:'doc2', chunks:['c2'], attributes:[]}),
(isolated:`+label+` {name:'Isolated', kg:'doc1', chunks:['c1'], attributes:[]}),
(outside:`+outsideLabel+` {name:'Outside', kg:'secret', chunks:['secret']}),
(a)-[:HEADQUARTERED_IN]->(b), (b)-[:RELATED_TO]->(a), (a)-[:SELF]->(a),
(a2)-[:HAS_BRANCH_IN]->(b2), (a)-[:MUST_NOT_LEAK]->(outside)
`, nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
t.Cleanup(func() {
_, err := neo4j.ExecuteQuery(context.Background(), driver,
"MATCH (n:"+outsideLabel+") DETACH DELETE n", nil, neo4j.EagerResultTransformer)
assert.NoError(t, err)
})
for _, query := range []string{"Acme", "Shanghai"} {
result, err := repo.SearchGraph(ctx, ns, query)
require.NoError(t, err)
require.Len(t, result.Graph.Node, 4)
expectedRelations := 4
if query == "Shanghai" {
expectedRelations = 3 // Self-loop is outside this one-hop neighbourhood.
}
require.Len(t, result.Graph.Relation, expectedRelations)
names := map[string]string{}
for _, node := range result.Graph.Node {
names[node.ID] = node.Name
}
for _, relation := range result.Graph.Relation {
require.NotEqual(t, "MUST_NOT_LEAK", relation.Type)
if relation.Type == "HEADQUARTERED_IN" {
require.Equal(t, "Acme", names[relation.SourceID])
require.Equal(t, "Acme Shanghai", names[relation.TargetID])
}
}
require.Empty(t, result.TruncationReasons)
}
isolated, err := repo.SearchGraph(ctx, ns, "Isolated")
require.NoError(t, err)
require.Len(t, isolated.Graph.Node, 1)
require.Empty(t, isolated.Graph.Relation)
empty, err := repo.SearchGraph(ctx, ns, "no match")
require.NoError(t, err)
require.Empty(t, empty.Graph.Node)
// Full query text remains a parameter, including a Cypher-looking payload.
empty, err = repo.SearchGraph(ctx, ns, "' RETURN 1 //")
require.NoError(t, err)
require.Empty(t, empty.Graph.Node)
t.Run("seed cap and exact-name priority", func(t *testing.T) {
_, err := neo4j.ExecuteQuery(ctx, driver, `
UNWIND range(0, 104) AS i CREATE (n:`+label+`
{name:'Cap '+toString(i), kg:'doc', chunks:['c1'], attributes:[]})
WITH count(*) AS created
CREATE (exact:`+label+` {name:'Cap', kg:'doc', chunks:['c1'], attributes:[]})`,
nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
result, err := repo.SearchGraph(ctx, ns, "Cap")
require.NoError(t, err)
require.Len(t, result.Graph.Node, types.GraphSearchMaxSeeds)
require.Equal(t, "Cap", result.Graph.Node[0].Name)
require.Contains(t, result.TruncationReasons, "candidate_seeds")
})
t.Run("row cap without duplicate edge expansion", func(t *testing.T) {
_, err := neo4j.ExecuteQuery(ctx, driver, `
CREATE (hub:`+label+` {name:'Hub', kg:'doc', chunks:['c1'], attributes:[]})
WITH hub UNWIND range(0, 512) AS i
CREATE (leaf:`+label+` {name:'Leaf '+toString(i), kg:'doc', chunks:['c1'], attributes:[]}),
(hub)-[:CONNECTS]->(leaf)`,
nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
result, err := repo.SearchGraph(ctx, ns, "Hub")
require.NoError(t, err)
require.Len(t, result.Graph.Relation, types.GraphSearchMaxRows)
require.Contains(t, result.TruncationReasons, "candidate_relations")
})
t.Run("field projections are bounded before Bolt", func(t *testing.T) {
_, err := neo4j.ExecuteQuery(ctx, driver, `
CREATE (n:`+label+` {name:'Large', kg:'doc', chunks:$chunks, attributes:$attributes})`,
map[string]any{
"chunks": strings.Split(strings.Repeat("c,", 600), ","),
"attributes": []string{strings.Repeat("中", 3000)},
}, neo4j.EagerResultTransformer)
require.NoError(t, err)
result, err := repo.SearchGraph(ctx, ns, "Large")
require.NoError(t, err)
require.Len(t, result.Graph.Node, 1)
require.Len(t, result.Graph.Node[0].Chunks, 513)
require.Len(t, []rune(result.Graph.Node[0].Attributes[0]), 1001)
})
}
@@ -0,0 +1,360 @@
package neo4j
import (
"context"
"fmt"
"strings"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
// Neo4jRepository is a repository for Neo4j
type Neo4jRepository struct {
driver neo4j.Driver
nodePrefix string
}
const (
// graphSearchMaxSeedNodes bounds how many entities a single graph search
// expands from. The match is a substring match, so this is the knob that
// keeps one vague entity name from pulling in the whole graph.
graphSearchMaxSeedNodes = 200
// graphSearchMaxRows bounds returned (node, relation) rows as a backstop
// for hub entities whose neighbourhood alone is huge.
graphSearchMaxRows = 2000
)
// NewNeo4jRepository creates a new Neo4j repository
func NewNeo4jRepository(driver neo4j.Driver) interfaces.RetrieveGraphRepository {
return &Neo4jRepository{driver: driver, nodePrefix: "ENTITY"}
}
// _remove_hyphen removes hyphens from a string
func _remove_hyphen(s string) string {
return strings.ReplaceAll(s, "-", "_")
}
// Labels returns the labels for a namespace
func (n *Neo4jRepository) Labels(namespace types.NameSpace) []string {
res := make([]string, 0)
for _, label := range namespace.Labels() {
res = append(res, n.nodePrefix+_remove_hyphen(label))
}
return res
}
// Label returns the label for a namespace
func (n *Neo4jRepository) Label(namespace types.NameSpace) string {
labels := n.Labels(namespace)
return strings.Join(labels, ":")
}
// AddGraph adds a graph to the Neo4j repository
func (n *Neo4jRepository) AddGraph(ctx context.Context, namespace types.NameSpace, graphs []*types.GraphData) error {
if n.driver == nil {
logger.Warnf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
return nil
}
for _, graph := range graphs {
if err := n.addGraph(ctx, namespace, graph); err != nil {
return err
}
}
return nil
}
// addGraph adds a graph to the Neo4j repository
func (n *Neo4jRepository) addGraph(ctx context.Context, namespace types.NameSpace, graph *types.GraphData) error {
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
defer session.Close(ctx)
_, err := session.ExecuteWrite(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
// Node import query
node_import_query := `
UNWIND $data AS row
CALL apoc.merge.node(row.labels, {name: row.name, kg: row.knowledge_id}, row.props, {}) YIELD node
SET node.chunks = apoc.coll.union(node.chunks, row.chunks)
RETURN distinct 'done' AS result
`
nodeData := []map[string]interface{}{}
for _, node := range graph.Node {
nodeData = append(nodeData, map[string]interface{}{
"name": node.Name,
"knowledge_id": namespace.Knowledge,
"props": map[string][]string{"attributes": node.Attributes},
"chunks": node.Chunks,
"labels": n.Labels(namespace),
})
}
if _, err := tx.Run(ctx, node_import_query, map[string]interface{}{"data": nodeData}); err != nil {
return nil, fmt.Errorf("failed to create nodes: %v", err)
}
// Relationship import query
rel_import_query := `
UNWIND $data AS row
CALL apoc.merge.node(row.source_labels, {name: row.source, kg: row.knowledge_id}, {}, {}) YIELD node as source
CALL apoc.merge.node(row.target_labels, {name: row.target, kg: row.knowledge_id}, {}, {}) YIELD node as target
CALL apoc.merge.relationship(source, row.type, {}, row.attributes, target) YIELD rel
RETURN distinct 'done'
`
relData := []map[string]interface{}{}
for _, rel := range graph.Relation {
relData = append(relData, map[string]interface{}{
"source": rel.Node1,
"target": rel.Node2,
"knowledge_id": namespace.Knowledge,
"type": rel.Type,
"source_labels": n.Labels(namespace),
"target_labels": n.Labels(namespace),
})
}
if _, err := tx.Run(ctx, rel_import_query, map[string]interface{}{"data": relData}); err != nil {
return nil, fmt.Errorf("failed to create relationships: %v", err)
}
return nil, nil
})
if err != nil {
logger.Errorf(ctx, "failed to add graph: %v", err)
return err
}
return nil
}
// DelGraph deletes a graph from the Neo4j repository
func (n *Neo4jRepository) DelGraph(ctx context.Context, namespaces []types.NameSpace) error {
if n.driver == nil {
logger.Warnf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
return nil
}
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
defer session.Close(ctx)
result, err := session.ExecuteWrite(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
for _, namespace := range namespaces {
labelExpr := n.Label(namespace)
deleteRelsQuery := `
CALL apoc.periodic.iterate(
"MATCH (n:` + labelExpr + ` {kg: $knowledge_id})-[r]-(m:` + labelExpr + ` {kg: $knowledge_id}) RETURN r",
"DELETE r",
{batchSize: 1000, parallel: true, params: {knowledge_id: $knowledge_id}}
) YIELD batches, total
RETURN total
`
if _, err := tx.Run(ctx, deleteRelsQuery, map[string]interface{}{"knowledge_id": namespace.Knowledge}); err != nil {
return nil, fmt.Errorf("failed to delete relationships: %v", err)
}
deleteNodesQuery := `
CALL apoc.periodic.iterate(
"MATCH (n:` + labelExpr + ` {kg: $knowledge_id}) RETURN n",
"DELETE n",
{batchSize: 1000, parallel: true, params: {knowledge_id: $knowledge_id}}
) YIELD batches, total
RETURN total
`
if _, err := tx.Run(ctx, deleteNodesQuery, map[string]interface{}{"knowledge_id": namespace.Knowledge}); err != nil {
return nil, fmt.Errorf("failed to delete nodes: %v", err)
}
}
return nil, nil
})
if err != nil {
return err
}
logger.Infof(ctx, "delete graph result: %v", result)
return nil
}
// SearchNode searches for nodes in the Neo4j repository.
//
// The result set is bounded twice; graphSearchCypher owns the query, its
// ordering and the parameters, so both caps can be pinned by a unit test
// without a live database.
func (n *Neo4jRepository) SearchNode(
ctx context.Context,
namespace types.NameSpace,
nodes []string,
) (*types.GraphData, error) {
if n.driver == nil {
logger.Warnf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
return nil, nil
}
session := n.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeRead})
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
query, params := graphSearchCypher(n.Label(namespace), nodes)
result, err := tx.Run(ctx, query, params)
if err != nil {
return nil, fmt.Errorf("failed to run query: %v", err)
}
graphData, err := decodeGraphSearchResult(ctx, result)
if err != nil {
return nil, err
}
// Make truncation visible. A silent cap reads as "the graph has no more
// matches" when in fact candidates were dropped.
if len(graphData.Relation) >= graphSearchMaxRows {
logger.Warnf(ctx,
"graph search hit the row cap: %d nodes / %d relations returned "+
"(seed cap %d, row cap %d) — results are truncated; "+
"narrow the entity or raise graphSearchMaxRows",
len(graphData.Node), len(graphData.Relation),
graphSearchMaxSeedNodes, graphSearchMaxRows)
} else {
// Debug, not Info: this runs on the retrieval path for every query.
logger.Debugf(ctx, "graph search: %d nodes / %d relations (seed cap %d, row cap %d)",
len(graphData.Node), len(graphData.Relation),
graphSearchMaxSeedNodes, graphSearchMaxRows)
}
return graphData, nil
})
if err != nil {
logger.Errorf(ctx, "search node failed: %v", err)
return nil, err
}
return result.(*types.GraphData), nil
}
// decodeGraphSearchResult keeps document instances distinct and restores the
// stored direction even when the seed is the target of an undirected match.
func decodeGraphSearchResult(ctx context.Context, result neo4j.Result) (*types.GraphData, error) {
graph := &types.GraphData{}
nodeSeen := make(map[string]*types.GraphNode)
relationSeen := make(map[string]bool)
for result.Next(ctx) {
record := result.Record()
if record == nil {
return nil, fmt.Errorf("graph query returned a nil record")
}
n, _, err := neo4j.GetRecordValue[neo4j.Node](record, "n")
if err != nil {
return nil, fmt.Errorf("failed to decode graph seed: %w", err)
}
m, _, err := neo4j.GetRecordValue[neo4j.Node](record, "m")
if err != nil {
return nil, fmt.Errorf("failed to decode graph neighbour: %w", err)
}
r, _, err := neo4j.GetRecordValue[neo4j.Relationship](record, "r")
if err != nil {
return nil, fmt.Errorf("failed to decode graph relationship: %w", err)
}
// Keep the matched seed first for evidence ranking, independently of direction.
for _, node := range []neo4j.Node{n, m} {
if nodeSeen[node.ElementId] != nil {
continue
}
decoded, err := decodeGraphNode(node)
if err != nil {
return nil, err
}
nodeSeen[node.ElementId] = decoded
graph.Node = append(graph.Node, decoded)
}
source, target := n, m
if r.StartElementId == m.ElementId && r.EndElementId == n.ElementId {
source, target = m, n
} else if r.StartElementId != n.ElementId || r.EndElementId != m.ElementId {
return nil, fmt.Errorf("graph relationship %q does not connect its returned endpoints", r.ElementId)
}
if r.ElementId == "" {
return nil, fmt.Errorf("graph relationship has no element identity")
}
if !relationSeen[r.ElementId] {
relationSeen[r.ElementId] = true
graph.Relation = append(graph.Relation, &types.GraphRelation{
Node1: nodeSeen[source.ElementId].Name, Node2: nodeSeen[target.ElementId].Name, Type: r.Type,
ID: r.ElementId, SourceID: source.ElementId, TargetID: target.ElementId,
})
}
}
if err := result.Err(); err != nil {
return nil, fmt.Errorf("failed to read graph query results: %w", err)
}
return graph, nil
}
func decodeGraphNode(node neo4j.Node) (*types.GraphNode, error) {
name, ok := node.Props["name"].(string)
if node.ElementId == "" || !ok || name == "" {
return nil, fmt.Errorf("graph node %q has no identity or name", node.ElementId)
}
chunks, ok := node.Props["chunks"].([]any)
if !ok && node.Props["chunks"] != nil {
return nil, fmt.Errorf("graph node %q has invalid chunks", node.ElementId)
}
attributes, ok := node.Props["attributes"].([]any)
if !ok && node.Props["attributes"] != nil {
return nil, fmt.Errorf("graph node %q has invalid attributes", node.ElementId)
}
knowledgeID, _ := node.Props["kg"].(string)
return &types.GraphNode{
Name: name, Chunks: listI2listS(chunks), Attributes: listI2listS(attributes),
ID: node.ElementId, KnowledgeID: knowledgeID,
}, nil
}
// graphSearchCypher builds the bounded graph-search query and its parameters
// for one label expression and one set of entity names.
//
// The WHERE clause is a substring match, so a short entity name (or one that is
// a component of many others) matches a large slice of the graph: without a
// bound this returned 1309 nodes / 1917 relations for a single query, which
// then exceeded the reranker's per-request limit and made chunk_merge walk the
// entire set. Three rules keep the caps from deciding the result by accident:
//
// - Only entities that have at least one relationship can seed an expansion —
// a relation-less match occupies one of the seed slots and then contributes
// nothing.
// - Exact name matches rank first, then the shortest names, then alphabetical
// order. Ordering by name alone lets an entity whose name *is* the query
// fall outside the cap once the substring matches exceed it.
// - The seed order is carried into the row LIMIT, so a truncated result keeps the
// neighbourhoods of the highest-ranked seeds rather than an arbitrary
// subset of the rows.
//
// Each edge is expanded only from its earliest seed, so duplicate endpoint
// matches cannot consume the row cap. Only the bounded seed list is collected;
// grouping every candidate relationship would require unbounded working memory.
func graphSearchCypher(labelExpr string, nodes []string) (string, map[string]interface{}) {
query := `
MATCH (n:` + labelExpr + `)
WHERE ANY(nodeText IN $nodes WHERE n.name CONTAINS nodeText)
AND EXISTS { (n)--() }
WITH n,
CASE WHEN n.name IN $nodes THEN 0 ELSE 1 END AS seed_rank,
size(n.name) AS name_len,
n.name AS name
ORDER BY seed_rank, name_len, name, n.kg, elementId(n)
LIMIT $maxSeedNodes
WITH collect(n) AS seeds
UNWIND range(0, size(seeds) - 1) AS seed_index
WITH seeds[seed_index] AS n, seeds[0..seed_index] AS earlier_seeds, seed_index
MATCH (n)-[r]-(m:` + labelExpr + `)
WHERE NOT m IN earlier_seeds
WITH n, r, m, seed_index
ORDER BY seed_index, elementId(r)
LIMIT $maxRows
RETURN n, r, m
`
params := map[string]interface{}{
"nodes": nodes,
"maxSeedNodes": graphSearchMaxSeedNodes,
"maxRows": graphSearchMaxRows,
}
return query, params
}
func listI2listS(list []any) []string {
result := make([]string, len(list))
for i, v := range list {
result[i] = fmt.Sprintf("%v", v)
}
return result
}
@@ -0,0 +1,224 @@
package neo4j
import (
"context"
"errors"
"strings"
"testing"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestGraphSearchCypherBoundsAndOrders pins the three review points on #3550:
// relation-less seeds are excluded, exact name matches outrank substring-only
// hits, and both LIMITs are preceded by the same ordering key so a truncated
// result keeps the neighbourhoods of the highest-ranked seeds.
func TestGraphSearchCypherBoundsAndOrders(t *testing.T) {
query, params := graphSearchCypher("ENTITY_kb", []string{"安恒"})
for _, want := range []string{
"EXISTS { (n)--() }",
"CASE WHEN n.name IN $nodes THEN 0 ELSE 1 END AS seed_rank",
"ORDER BY seed_rank, name_len, name",
"WITH collect(n) AS seeds",
"UNWIND range(0, size(seeds) - 1) AS seed_index",
"WHERE NOT m IN earlier_seeds",
"ORDER BY seed_index, elementId(r)",
"LIMIT $maxSeedNodes",
"LIMIT $maxRows",
} {
if !strings.Contains(query, want) {
t.Errorf("query is missing %q:\n%s", want, query)
}
}
// Collect only the capped seeds, never the unbounded relationship candidates.
collectAt := strings.Index(query, "WITH collect(n) AS seeds")
if collectAt < strings.Index(query, "LIMIT $maxSeedNodes") || strings.Count(query, "collect(") != 1 {
t.Errorf("only the bounded seed list may be collected:\n%s", query)
}
if !strings.Contains(query, "name, n.kg, elementId(n)") {
t.Errorf("same-named document instances need stable tie breakers:\n%s", query)
}
if strings.Index(query, "WHERE NOT m IN earlier_seeds") > strings.Index(query, "LIMIT $maxRows") {
t.Errorf("duplicate endpoint matches must be removed before the row cap:\n%s", query)
}
if strings.Index(query, "LIMIT $maxSeedNodes") > strings.Index(query, "LIMIT $maxRows") {
t.Errorf("the seed cap must be applied before the row cap:\n%s", query)
}
// A relation-less seed expands to nothing, so it must not survive the first
// cap (the check has to sit in the first WHERE, before the seed ordering).
whereAt := strings.Index(query, "EXISTS { (n)--() }")
seedCapAt := strings.Index(query, "LIMIT $maxSeedNodes")
if whereAt < 0 || seedCapAt < 0 || whereAt > seedCapAt {
t.Errorf("the relationship check must precede the seed cap:\n%s", query)
}
if params["maxSeedNodes"] != graphSearchMaxSeedNodes {
t.Errorf("maxSeedNodes = %v, want %d", params["maxSeedNodes"], graphSearchMaxSeedNodes)
}
if params["maxRows"] != graphSearchMaxRows {
t.Errorf("maxRows = %v, want %d", params["maxRows"], graphSearchMaxRows)
}
if got, ok := params["nodes"].([]string); !ok || len(got) != 1 || got[0] != "安恒" {
t.Errorf("nodes param = %#v, want []string{\"安恒\"}", params["nodes"])
}
// The label expression is interpolated rather than parameterised, so it has
// to reach every match in the query.
if !strings.Contains(query, "MATCH (n:ENTITY_kb)") || !strings.Contains(query, "MATCH (n)-[r]-(m:ENTITY_kb)") {
t.Errorf("label expression not applied to both matches:\n%s", query)
}
}
type graphRecordResult struct {
neo4j.Result
records []*neo4j.Record
index int
err error
}
func (r *graphRecordResult) Next(context.Context) bool {
if r.index >= len(r.records) {
return false
}
r.index++
return true
}
func (r *graphRecordResult) Record() *neo4j.Record { return r.records[r.index-1] }
func (r *graphRecordResult) Err() error { return r.err }
func graphTestNode(id, name, document, chunk string, attributes ...string) neo4j.Node {
attrs := make([]any, len(attributes))
for i, attribute := range attributes {
attrs[i] = attribute
}
return neo4j.Node{ElementId: id, Props: map[string]any{
"name": name, "kg": document, "chunks": []any{chunk}, "attributes": attrs,
}}
}
func graphTestRecord(n, m neo4j.Node, r neo4j.Relationship) *neo4j.Record {
return &neo4j.Record{Keys: []string{"n", "r", "m"}, Values: []any{n, r, m}}
}
func TestDecodeGraphSearchDirectionAndIdentity(t *testing.T) {
a := graphTestNode("a", "Acme", "doc1", "c1")
b := graphTestNode("b", "Shanghai", "doc1", "c1")
r := neo4j.Relationship{ElementId: "r", StartElementId: "a", EndElementId: "b", Type: "LOCATED_IN"}
reverse := neo4j.Relationship{ElementId: "reverse", StartElementId: "b", EndElementId: "a", Type: "LOCATED_IN"}
self := neo4j.Relationship{ElementId: "self", StartElementId: "a", EndElementId: "a", Type: "RELATED_TO"}
for _, tt := range []struct {
name string
records []*neo4j.Record
nodeCount int
firstNode string
relations [][3]string
}{
{"outgoing", []*neo4j.Record{graphTestRecord(a, b, r)}, 2, "a", [][3]string{{"r", "a", "b"}}},
{"incoming", []*neo4j.Record{graphTestRecord(b, a, r)}, 2, "b", [][3]string{{"r", "a", "b"}}},
{
"both seeds",
[]*neo4j.Record{graphTestRecord(b, a, r), graphTestRecord(a, b, r)},
2, "b",
[][3]string{{"r", "a", "b"}},
},
{
"bidirectional",
[]*neo4j.Record{graphTestRecord(a, b, r), graphTestRecord(a, b, reverse)},
2, "a",
[][3]string{{"r", "a", "b"}, {"reverse", "b", "a"}},
},
{
"self loop",
[]*neo4j.Record{graphTestRecord(a, a, self), graphTestRecord(a, a, self)},
1, "a",
[][3]string{{"self", "a", "a"}},
},
} {
t.Run(tt.name, func(t *testing.T) {
graph, err := decodeGraphSearchResult(context.Background(), &graphRecordResult{records: tt.records})
require.NoError(t, err)
require.Len(t, graph.Node, tt.nodeCount)
assert.Equal(t, tt.firstNode, graph.Node[0].ID, "seed evidence priority must not change")
require.Len(t, graph.Relation, len(tt.relations))
for i, want := range tt.relations {
got := graph.Relation[i]
assert.Equal(t, want, [3]string{got.ID, got.SourceID, got.TargetID})
byID := map[string]string{"a": "Acme", "b": "Shanghai"}
assert.Equal(t, byID[want[1]], got.Node1)
assert.Equal(t, byID[want[2]], got.Node2)
}
})
}
}
func TestDecodeGraphSearchPreservesSameNamedDocumentSources(t *testing.T) {
a1 := graphTestNode("a1", "Acme", "doc1", "c1", "doc1 attribute")
b1 := graphTestNode("b1", "Shanghai", "doc1", "c1")
a2 := graphTestNode("a2", "Acme", "doc2", "c2", "doc2 attribute")
b2 := graphTestNode("b2", "Shanghai", "doc2", "c2")
r1 := neo4j.Relationship{ElementId: "r1", StartElementId: "a1", EndElementId: "b1", Type: "LOCATED_IN"}
r2 := neo4j.Relationship{ElementId: "r2", StartElementId: "a2", EndElementId: "b2", Type: "LOCATED_IN"}
for _, records := range [][]*neo4j.Record{
{graphTestRecord(b1, a1, r1), graphTestRecord(b2, a2, r2), graphTestRecord(a1, b1, r1)},
{graphTestRecord(b2, a2, r2), graphTestRecord(b1, a1, r1), graphTestRecord(a2, b2, r2)},
} {
graph, err := decodeGraphSearchResult(context.Background(), &graphRecordResult{records: records})
require.NoError(t, err)
require.Len(t, graph.Node, 4)
require.Len(t, graph.Relation, 2, "same names and type do not make two document edges identical")
var sources, attributes []string
for _, node := range graph.Node {
if node.Name == "Acme" {
sources = append(sources, node.KnowledgeID+":"+node.Chunks[0])
attributes = append(attributes, node.Attributes...)
}
}
assert.ElementsMatch(t, []string{"doc1:c1", "doc2:c2"}, sources)
assert.ElementsMatch(t, []string{"doc1 attribute", "doc2 attribute"}, attributes)
}
}
func TestDecodeGraphSearchReportsInvalidRecordsAndStreamErrors(t *testing.T) {
a := graphTestNode("a", "Acme", "doc", "c")
b := graphTestNode("b", "Shanghai", "doc", "c")
r := neo4j.Relationship{ElementId: "r", StartElementId: "a", EndElementId: "b", Type: "LOCATED_IN"}
streamErr := errors.New("stream interrupted")
graph, err := decodeGraphSearchResult(context.Background(), &graphRecordResult{
records: []*neo4j.Record{graphTestRecord(a, b, r)}, err: streamErr,
})
assert.Nil(t, graph, "a failed stream must not return a successful partial graph")
assert.ErrorIs(t, err, streamErr)
missingName := neo4j.Node{ElementId: "a", Props: map[string]any{}}
missingID := graphTestNode("", "Acme", "doc", "c")
wrongEndpoint := r
wrongEndpoint.EndElementId = "elsewhere"
missingRelationID := r
missingRelationID.ElementId = ""
for _, record := range []*neo4j.Record{
nil,
{Keys: []string{"n"}, Values: []any{"not a node"}},
graphTestRecord(missingName, b, r),
graphTestRecord(missingID, b, r),
graphTestRecord(a, b, wrongEndpoint),
graphTestRecord(a, b, missingRelationID),
} {
result := &graphRecordResult{records: []*neo4j.Record{record}}
graph, err := decodeGraphSearchResult(context.Background(), result)
assert.Error(t, err)
assert.Nil(t, graph)
}
// Optional properties may be absent in legacy graph data.
delete(a.Props, "attributes")
graph, err = decodeGraphSearchResult(context.Background(), &graphRecordResult{records: []*neo4j.Record{
graphTestRecord(a, b, r),
}})
require.NoError(t, err)
assert.Empty(t, graph.Node[0].Attributes)
}
@@ -0,0 +1,94 @@
package neo4j
import (
"context"
"fmt"
"os"
"testing"
"time"
"academy/internal/types"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Run against a disposable Neo4j instance with authentication disabled:
// Set ACADEMY_NEO4J_TEST_URI=bolt://127.0.0.1:7687, then run:
// go test ./internal/application/repository/retriever/neo4j -run Integration
func TestSearchNodeIntegration(t *testing.T) {
uri := os.Getenv("ACADEMY_NEO4J_TEST_URI")
if uri == "" {
t.Skip("set ACADEMY_NEO4J_TEST_URI to run the live Neo4j regression")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
driver, err := neo4j.NewDriver(uri, neo4j.NoAuth())
require.NoError(t, err)
t.Cleanup(func() { assert.NoError(t, driver.Close(context.Background())) })
require.NoError(t, driver.VerifyConnectivity(ctx))
repo := NewNeo4jRepository(driver).(*Neo4jRepository)
namespace := types.NameSpace{KnowledgeBase: fmt.Sprintf("graph_regression_%d", time.Now().UnixNano())}
label := repo.Label(namespace)
t.Cleanup(func() {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cleanupCancel()
_, cleanupErr := neo4j.ExecuteQuery(cleanupCtx, driver, "MATCH (n:"+label+") DETACH DELETE n",
nil, neo4j.EagerResultTransformer)
assert.NoError(t, cleanupErr)
})
_, err = neo4j.ExecuteQuery(ctx, driver, `
CREATE (a1:`+label+` {name: 'Acme', kg: 'doc1', chunks: ['c1'], attributes: ['doc1 attribute']}),
(b1:`+label+` {name: 'Shanghai', kg: 'doc1', chunks: ['c1'], attributes: []}),
(a2:`+label+` {name: 'Acme', kg: 'doc2', chunks: ['c2'], attributes: ['doc2 attribute']}),
(b2:`+label+` {name: 'Shanghai', kg: 'doc2', chunks: ['c2'], attributes: []}),
(a1)-[:HEADQUARTERED_IN]->(b1), (a2)-[:HAS_BRANCH_IN]->(b2),
(b1)-[:RELATED_TO]->(a1), (a1)-[:SELF]->(a1)
`, nil, neo4j.EagerResultTransformer)
require.NoError(t, err)
t.Run("deduplicate before the row cap", func(t *testing.T) {
query, params := graphSearchCypher(label, []string{"Acme", "Shanghai"})
params["maxRows"] = 5 // Four stored edges; duplicate endpoint matches must not fill this fifth slot.
result, queryErr := neo4j.ExecuteQuery(ctx, driver, query, params, neo4j.EagerResultTransformer)
require.NoError(t, queryErr)
require.Len(t, result.Records, 4)
params["maxRows"] = 1
result, queryErr = neo4j.ExecuteQuery(ctx, driver, query, params, neo4j.EagerResultTransformer)
require.NoError(t, queryErr)
require.Len(t, result.Records, 1)
})
for _, seeds := range [][]string{{"Shanghai"}, {"Acme"}, {"Acme", "Shanghai"}} {
t.Run(fmt.Sprint(seeds), func(t *testing.T) {
graph, searchErr := repo.SearchNode(ctx, namespace, seeds)
require.NoError(t, searchErr)
require.Len(t, graph.Node, 4)
assert.Equal(t, seeds[0], graph.Node[0].Name, "the best seed still supplies evidence first")
var sources, attributes []string
for _, node := range graph.Node {
if node.Name == "Acme" {
sources = append(sources, node.KnowledgeID+":"+node.Chunks[0])
attributes = append(attributes, node.Attributes...)
}
}
assert.ElementsMatch(t, []string{"doc1:c1", "doc2:c2"}, sources)
assert.ElementsMatch(t, []string{"doc1 attribute", "doc2 attribute"}, attributes)
wantRelations := 4
if len(seeds) == 1 && seeds[0] == "Shanghai" {
wantRelations = 3 // The self-loop has no Shanghai endpoint.
}
require.Len(t, graph.Relation, wantRelations)
for _, relation := range graph.Relation {
switch relation.Type {
case "HEADQUARTERED_IN", "HAS_BRANCH_IN":
assert.Equal(t, "Acme", relation.Node1)
assert.Equal(t, "Shanghai", relation.Node2)
case "RELATED_TO":
assert.Equal(t, "Shanghai", relation.Node1)
assert.Equal(t, "Acme", relation.Node2)
case "SELF":
assert.Equal(t, relation.SourceID, relation.TargetID)
}
}
})
}
}
@@ -0,0 +1,50 @@
package opensearch
import "context"
// AuditSink receives audit events emitted from within the driver at the
// exact moment they occur (index provisioned, reindex executed). The driver
// owns this abstraction so it imports no service package — the dependency
// arrow stays one-way (service implements AuditSink; the driver only invokes
// it). A nil sink is a no-op, so tests and the env-path (no audit service)
// need no special casing.
type AuditSink interface {
// EmitIndexCreated fires once when the driver provisions a new k-NN
// index. alias is the per-dimension alias (or the keyword-only index
// name); dim is the embedding dimension (0 for the keyword-only index).
EmitIndexCreated(ctx context.Context, alias string, dim int)
// EmitReindexExecuted fires when CopyIndices finishes copying docs from
// one index to another.
EmitReindexExecuted(ctx context.Context, srcAlias, dstAlias string, docs int64)
}
// nopSink is the null-object used when no sink is configured, so emit call
// sites never need a nil check.
type nopSink struct{}
func (nopSink) EmitIndexCreated(context.Context, string, int) {}
func (nopSink) EmitReindexExecuted(context.Context, string, string, int64) {}
var _ AuditSink = nopSink{}
// Option configures a Repository at construction time.
type Option func(*Repository)
// WithAuditSink injects an audit sink. A nil sink is ignored (the Repository
// keeps its default no-op behavior).
func WithAuditSink(s AuditSink) Option {
return func(r *Repository) {
if s != nil {
r.sink = s
}
}
}
// auditSink returns the configured sink, or a no-op if none was set (e.g. a
// Repository built directly in tests, or constructed without WithAuditSink).
func (r *Repository) auditSink() AuditSink {
if r.sink == nil {
return nopSink{}
}
return r.sink
}
@@ -0,0 +1,153 @@
package opensearch
import (
"context"
"strings"
"sync"
"testing"
"academy/internal/types"
)
// spySink records audit events for assertions.
type spySink struct {
mu sync.Mutex
indexCreated []indexCreatedEvent
reindex []reindexEvent
}
type indexCreatedEvent struct {
alias string
dim int
}
type reindexEvent struct {
src, dst string
docs int64
}
func (s *spySink) EmitIndexCreated(_ context.Context, alias string, dim int) {
s.mu.Lock()
defer s.mu.Unlock()
s.indexCreated = append(s.indexCreated, indexCreatedEvent{alias, dim})
}
func (s *spySink) EmitReindexExecuted(_ context.Context, src, dst string, docs int64) {
s.mu.Lock()
defer s.mu.Unlock()
s.reindex = append(s.reindex, reindexEvent{src, dst, docs})
}
// TestBuildInternalCfg_ReadsHNSWFields verifies the HNSW IndexConfig fields
// flow into internalCfg, falling back to defaults when unset.
func TestBuildInternalCfg_ReadsHNSWFields(t *testing.T) {
t.Run("reads set fields", func(t *testing.T) {
cfg, err := buildInternalCfg(&types.IndexConfig{
HNSWM: 24,
HNSWEFConstruction: 200,
HNSWEFSearch: 128,
KNNEngine: "faiss",
NumberOfShards: 2,
})
if err != nil {
t.Fatal(err)
}
if cfg.hnswM != 24 || cfg.hnswEFConstruction != 200 || cfg.efSearch != 128 || cfg.knnEngine != "faiss" {
t.Errorf("HNSW not wired: %+v", cfg)
}
if cfg.shards != 2 {
t.Errorf("shards: want 2, got %d", cfg.shards)
}
})
t.Run("defaults when unset", func(t *testing.T) {
cfg, err := buildInternalCfg(&types.IndexConfig{})
if err != nil {
t.Fatal(err)
}
if cfg.hnswM != 16 || cfg.hnswEFConstruction != 100 || cfg.efSearch != 100 || cfg.knnEngine != "lucene" {
t.Errorf("defaults not applied: %+v", cfg)
}
})
t.Run("nil config is all defaults", func(t *testing.T) {
cfg, err := buildInternalCfg(nil)
if err != nil {
t.Fatal(err)
}
if cfg.knnEngine != "lucene" || cfg.hnswM != 16 {
t.Errorf("nil defaults wrong: %+v", cfg)
}
})
}
// TestBuildIndexMapping_ReflectsHNSWConfig verifies the end-to-end path
// IndexConfig → buildInternalCfg → buildIndexMapping carries the operator's
// HNSW values into the cluster mapping JSON (regression guard for the wire-
// through, since defaults coincide with common values).
func TestBuildIndexMapping_ReflectsHNSWConfig(t *testing.T) {
cfg, err := buildInternalCfg(&types.IndexConfig{
HNSWM: 24,
HNSWEFConstruction: 200,
HNSWEFSearch: 128,
KNNEngine: "faiss",
})
if err != nil {
t.Fatal(err)
}
body, err := buildIndexMapping(cfg, 768)
if err != nil {
t.Fatal(err)
}
s := string(body)
for _, want := range []string{`"m":24`, `"ef_construction":200`, `"engine":"faiss"`, `"knn.algo_param.ef_search":128`} {
if !strings.Contains(s, want) {
t.Errorf("mapping JSON missing %q\n%s", want, s)
}
}
}
// TestWithAuditSink_SetsAndNilSafe verifies the functional option.
func TestWithAuditSink_SetsAndNilSafe(t *testing.T) {
spy := &spySink{}
r := &Repository{}
WithAuditSink(spy)(r)
if r.sink != spy {
t.Fatal("WithAuditSink did not set the sink")
}
// nil must not clobber an already-set sink
WithAuditSink(nil)(r)
if r.sink != spy {
t.Fatal("WithAuditSink(nil) clobbered the sink")
}
}
// TestAuditSink_NopByDefault verifies a Repository with no sink does not panic
// when the audit accessor is used (nopSink fallback).
func TestAuditSink_NopByDefault(t *testing.T) {
var _ AuditSink = nopSink{} // compile-time assertion
r := &Repository{} // sink left nil
// Must not panic.
r.auditSink().EmitIndexCreated(context.Background(), "academy_768", 768)
r.auditSink().EmitReindexExecuted(context.Background(), "a", "b", 3)
}
// TestAuditSink_EmitIndexCreated_OnEnsureReady verifies createIndexAndAlias
// emits exactly one index-created event with the per-dim alias when a new
// index is provisioned.
func TestAuditSink_EmitIndexCreated_OnEnsureReady(t *testing.T) {
repo, ts := newTestRepo(t, (&indexLifecycleHandler{}).ServeHTTP)
defer ts.Close()
spy := &spySink{}
repo.sink = spy
if err := repo.ensureReady(context.Background(), 768); err != nil {
t.Fatalf("ensureReady: %v", err)
}
if len(spy.indexCreated) != 1 {
t.Fatalf("want 1 index_created event, got %d", len(spy.indexCreated))
}
got := spy.indexCreated[0]
if got.alias != "academy_test_768" || got.dim != 768 {
t.Errorf("event mismatch: %+v", got)
}
}
@@ -0,0 +1,107 @@
package opensearch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"sort"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
)
// BatchUpdateChunkEnabledStatus flips is_enabled for the given chunks. The
// status map is grouped by value into one _update_by_query per distinct value
// (mirrors the Qdrant grouping pattern), so the request body carries the
// chunk ids via a terms filter and the new value via bound script params —
// never per-chunk string interpolation.
//
// Targets the cross-dim <base>_* pattern: a chunk's embedding dimension is
// not known here, and the same chunk_id is unique across the store's dim
// indices + the keyword-only index.
func (r *Repository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
if len(chunkStatusMap) == 0 {
return nil
}
groups := map[bool][]string{}
for id, v := range chunkStatusMap {
groups[v] = append(groups[v], id)
}
// Deterministic order (false then true) for predictable behavior/tests.
for _, v := range []bool{false, true} {
ids := groups[v]
if len(ids) == 0 {
continue
}
sort.Strings(ids)
if err := r.updateByQueryScript(ctx, ids,
"ctx._source.is_enabled = params.v", map[string]any{"v": v}); err != nil {
return err
}
}
return nil
}
// BatchUpdateChunkTagID sets tag_id for the given chunks, grouped by tag.
func (r *Repository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
if len(chunkTagMap) == 0 {
return nil
}
groups := map[string][]string{}
for id, tag := range chunkTagMap {
groups[tag] = append(groups[tag], id)
}
tags := make([]string, 0, len(groups))
for tag := range groups {
tags = append(tags, tag)
}
sort.Strings(tags)
for _, tag := range tags {
ids := groups[tag]
sort.Strings(ids)
if err := r.updateByQueryScript(ctx, ids,
"ctx._source.tag_id = params.v", map[string]any{"v": tag}); err != nil {
return err
}
}
return nil
}
// updateByQueryScript runs an _update_by_query over the cross-dim <base>_*
// pattern, matching the given chunk ids via a terms filter and applying a
// constant Painless source with caller values flowing only through bound
// params (Painless-injection-safe).
func (r *Repository) updateByQueryScript(
ctx context.Context, chunkIDs []string, source string, params map[string]any,
) error {
body, err := json.Marshal(map[string]any{
"query": map[string]any{
"terms": map[string]any{"chunk_id": chunkIDs},
},
"script": map[string]any{
"lang": "painless",
"source": source,
"params": params,
},
})
if err != nil {
return fmt.Errorf("opensearch: marshal update_by_query body: %w", err)
}
// Q2: UpdateByQueryParams.Refresh is *bool — the wire value "wait_for" is
// not expressible via the typed SDK, so we force an immediate refresh.
refresh := true
resp, err := r.client.UpdateByQuery(ctx, osapi.UpdateByQueryReq{
Indices: []string{r.baseIndex + "_*"},
Body: bytes.NewReader(body),
Params: osapi.UpdateByQueryParams{Refresh: &refresh},
})
if err != nil {
return wrapTransport(err)
}
if resp == nil {
return nil
}
defer drainAndClose(resp.Inspect().Response.Body)
return inspectByQueryResponse(io.LimitReader(resp.Inspect().Response.Body, 16<<20))
}
@@ -0,0 +1,65 @@
package opensearch
import (
"context"
"encoding/json"
"fmt"
"io"
"strings"
"academy/internal/logger"
)
// inspectByQueryResponse parses an _update_by_query / _delete_by_query
// response and surfaces partial failures without leaking cluster-side reason
// strings (which may embed document content). Mirrors inspectBulkResponse:
// the full reason goes to the debug log only; the returned error carries the
// bounded id + type. A non-zero version_conflicts count with no hard failures
// is logged as a warning but not treated as an error.
func inspectByQueryResponse(body io.Reader) error {
return inspectByQueryResult(body, false)
}
func inspectByQueryResult(body io.Reader, requireComplete bool) error {
var r struct {
Total *int64 `json:"total"`
Updated *int64 `json:"updated"`
TimedOut bool `json:"timed_out"`
VersionConflicts int `json:"version_conflicts"`
Failures []struct {
ID string `json:"id"`
Cause struct {
Type string `json:"type"`
Reason string `json:"reason"`
} `json:"cause"`
} `json:"failures"`
}
if err := json.NewDecoder(body).Decode(&r); err != nil {
return fmt.Errorf("opensearch: parse by-query response: %w", ErrTransport)
}
if requireComplete && (r.TimedOut || r.VersionConflicts != 0) {
return fmt.Errorf("opensearch: incomplete move (timed_out=%t, version_conflicts=%d): %w",
r.TimedOut, r.VersionConflicts, ErrTransport)
}
if requireComplete && (r.Total == nil || r.Updated == nil || *r.Total < 0 || *r.Updated != *r.Total) {
return fmt.Errorf("opensearch: incomplete move document counts: %w", ErrTransport)
}
log := logger.GetLogger(context.Background())
if len(r.Failures) == 0 {
if r.VersionConflicts > 0 {
log.Warnf("[OpenSearch] by-query had %d version conflicts (proceeded)", r.VersionConflicts)
}
return nil
}
var msgs []string
for _, f := range r.Failures {
// Full reason → debug log only (may contain document content).
log.Debugf("[OpenSearch] by-query failure: id=%s type=%s reason=%s",
f.ID, f.Cause.Type, f.Cause.Reason)
if len(msgs) < 5 {
msgs = append(msgs, fmt.Sprintf("[%s] %s", f.ID, f.Cause.Type))
}
}
return fmt.Errorf("opensearch: by-query partial failure (%d failed, first 5: %s): %w",
len(r.Failures), strings.Join(msgs, "; "), ErrTransport)
}
@@ -0,0 +1,58 @@
package opensearch
import "academy/internal/types"
// internalCfg is the driver-internal, immutable view of IndexConfig.
// Defaults are chosen so the env-path (no IndexConfig) and DB-store path
// (with IndexConfig) produce identical mappings.
type internalCfg struct {
shards int
replicas int
knnEngine string // "lucene" | "faiss"
hnswM int
hnswEFConstruction int
efSearch int
}
// buildInternalCfg projects IndexConfig to the driver-internal view,
// substituting defaults for unset (zero / empty) fields. Validation of value
// ranges (e.g. hnsw_m / ef_construction caps) is a service-layer concern
// handled elsewhere (validateOpenSearchIndexConfig at CreateStore); this
// function applies defaults only and never rejects. The env-path bypasses
// service validation entirely, so the defaults below are its safety net.
//
// The OpenSearch-specific HNSW fields (knn_engine, hnsw_m,
// hnsw_ef_construction, hnsw_ef_search) are read here. They are omitempty on
// IndexConfig, so they do not affect other drivers' serialized config.
func buildInternalCfg(c *types.IndexConfig) (internalCfg, error) {
cfg := internalCfg{
shards: 4, // matches the keyword-index default upstream
replicas: 1, // assumes >= 2-node cluster
knnEngine: "lucene", // OS default; Faiss preferred only at >= 10M docs
hnswM: 16, // OS official default
hnswEFConstruction: 100, // OS official default
efSearch: 100, // OS default
}
if c == nil {
return cfg, nil
}
if c.NumberOfShards > 0 {
cfg.shards = c.NumberOfShards
}
if c.NumberOfReplicas > 0 {
cfg.replicas = c.NumberOfReplicas
}
if c.KNNEngine != "" {
cfg.knnEngine = c.KNNEngine
}
if c.HNSWM > 0 {
cfg.hnswM = c.HNSWM
}
if c.HNSWEFConstruction > 0 {
cfg.hnswEFConstruction = c.HNSWEFConstruction
}
if c.HNSWEFSearch > 0 {
cfg.efSearch = c.HNSWEFSearch
}
return cfg, nil
}
@@ -0,0 +1,194 @@
package opensearch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"github.com/google/uuid"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"academy/internal/logger"
"academy/internal/types"
)
// copyBatchSize is the pagination size for the source scan. Kept under the
// BatchSave per-call cap so each copied page is a single bulk request.
const copyBatchSize = 500
// copySourceDoc is the full _source read during CopyIndices — it includes the
// embedding vector and is_recommended, which the retrieve-path hit struct
// omits because retrieval does not need them.
type copySourceDoc struct {
Content string `json:"content"`
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"`
IsEnabled bool `json:"is_enabled"`
IsRecommended bool `json:"is_recommended"`
Embedding []float32 `json:"embedding"`
}
// transformSourceID mirrors the sibling drivers' source_id remap:
// - regular chunk (source_id == chunk_id) → target chunk id
// - generated question (source_id == "<chunk>-<q>") → "<targetChunk>-<q>"
// - anything else → a fresh uuid
func transformSourceID(sourceID, chunkID, targetChunkID string) string {
switch {
case sourceID == chunkID:
return targetChunkID
case strings.HasPrefix(sourceID, chunkID+"-"):
return targetChunkID + "-" + strings.TrimPrefix(sourceID, chunkID+"-")
default:
return uuid.New().String()
}
}
// CopyIndices copies all docs of one knowledge base into another (within the
// same store) by scanning the source and re-saving via BatchSave — mirroring
// the Elasticsearch / Qdrant drivers (search→BatchSave), which yields the
// source_id transformation and dim/keyword routing for free. Runs
// synchronously and paginates; the large-batch background-task path is a
// later change.
//
// NOTE: from/size pagination is bounded by the index's max_result_window
// (default 10000). Copies larger than that require the scroll-based async
// path (a later change).
func (r *Repository) CopyIndices(
ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string, // keyed by source knowledge_id (mirrors sibling drivers)
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
knowledgeType string,
) error {
log := logger.GetLogger(ctx)
if len(sourceToTargetChunkIDMap) == 0 {
log.Warn("[OpenSearch] CopyIndices: empty chunk mapping, skipping")
return nil
}
if dimension <= 0 {
return fmt.Errorf("opensearch: CopyIndices requires dim > 0, got %d: %w",
dimension, ErrDimensionMismatch)
}
if err := r.ensureReady(ctx, dimension); err != nil {
return err
}
alias := r.indexAlias(dimension)
var total int64
for from := 0; ; from += copyBatchSize {
docs, err := r.copyScanBatch(ctx, alias, sourceKnowledgeBaseID, from, copyBatchSize)
if err != nil {
return err
}
if len(docs) == 0 {
break
}
infos := make([]*types.IndexInfo, 0, len(docs))
embMap := make(map[string][]float32, len(docs))
enabledMap := make(map[string]bool, len(docs))
for i := range docs {
d := &docs[i]
targetChunkID, ok := sourceToTargetChunkIDMap[d.ChunkID]
if !ok {
log.Warnf("[OpenSearch] CopyIndices: source chunk %s not mapped, skipping", d.ChunkID)
continue
}
targetKnowledgeID, ok := sourceToTargetKBIDMap[d.KnowledgeID]
if !ok {
log.Warnf("[OpenSearch] CopyIndices: source knowledge %s not mapped, skipping", d.KnowledgeID)
continue
}
targetSourceID := transformSourceID(d.SourceID, d.ChunkID, targetChunkID)
if len(d.Embedding) > 0 {
// BatchSave looks up embeddings by SourceID (lookupEmbedding),
// so key by the target source id — not the chunk id, which is
// the Elasticsearch driver's convention.
embMap[targetSourceID] = d.Embedding
}
enabledMap[targetChunkID] = d.IsEnabled
infos = append(infos, &types.IndexInfo{
Content: d.Content,
SourceID: targetSourceID,
SourceType: types.SourceType(d.SourceType),
ChunkID: targetChunkID,
KnowledgeID: targetKnowledgeID,
KnowledgeBaseID: targetKnowledgeBaseID,
KnowledgeType: knowledgeType,
TagID: d.TagID,
IsEnabled: d.IsEnabled,
IsRecommended: d.IsRecommended,
})
}
if len(infos) > 0 {
params := map[string]any{
"embedding": embMap,
"chunk_enabled": enabledMap,
}
if err := r.BatchSave(ctx, infos, params); err != nil {
return fmt.Errorf("opensearch: CopyIndices batch save: %w", err)
}
total += int64(len(infos))
}
if len(docs) < copyBatchSize {
break
}
}
log.Infof("[OpenSearch] CopyIndices: copied %d docs (KB %s → %s, dim=%d)",
total, sourceKnowledgeBaseID, targetKnowledgeBaseID, dimension)
r.auditSink().EmitReindexExecuted(ctx, alias, alias, total)
return nil
}
// copyScanBatch reads one page of docs belonging to sourceKB from the per-dim
// index, decoding the full _source (including the embedding vector).
func (r *Repository) copyScanBatch(
ctx context.Context, index, sourceKB string, from, size int,
) ([]copySourceDoc, error) {
body, err := json.Marshal(map[string]any{
"from": from,
"size": size,
"query": map[string]any{
"bool": map[string]any{
"filter": []any{
map[string]any{"term": map[string]any{"knowledge_base_id": sourceKB}},
},
},
},
})
if err != nil {
return nil, fmt.Errorf("opensearch: marshal copy scan body: %w", err)
}
req := osapi.SearchReq{Indices: []string{index}, Body: bytes.NewReader(body)}
resp, err := r.client.Search(ctx, &req)
if err != nil {
if isNotFound(err) {
return nil, fmt.Errorf("opensearch: index %s missing: %w", index, ErrIndexNotFound)
}
return nil, wrapTransport(err)
}
defer drainAndClose(resp.Inspect().Response.Body)
var parsed struct {
Hits struct {
Hits []struct {
Source copySourceDoc `json:"_source"`
} `json:"hits"`
} `json:"hits"`
}
if err := json.NewDecoder(io.LimitReader(resp.Inspect().Response.Body, 64<<20)).Decode(&parsed); err != nil {
return nil, fmt.Errorf("opensearch: parse copy scan response: %w", ErrTransport)
}
out := make([]copySourceDoc, len(parsed.Hits.Hits))
for i, h := range parsed.Hits.Hits {
out[i] = h.Source
}
return out, nil
}
@@ -0,0 +1,193 @@
package opensearch
import (
"context"
"io"
"net/http"
"strings"
"sync"
"testing"
)
// TestTransformSourceID covers the generated-question / regular / fallback
// branches that CopyIndices uses to remap source_id.
func TestTransformSourceID(t *testing.T) {
t.Run("regular chunk uses target chunk id", func(t *testing.T) {
if got := transformSourceID("chunk1", "chunk1", "tgt1"); got != "tgt1" {
t.Errorf("want tgt1, got %s", got)
}
})
t.Run("generated question preserves question id", func(t *testing.T) {
if got := transformSourceID("chunk1-q7", "chunk1", "tgt1"); got != "tgt1-q7" {
t.Errorf("want tgt1-q7, got %s", got)
}
})
t.Run("unrelated source id gets fresh uuid", func(t *testing.T) {
got := transformSourceID("totally-different", "chunk1", "tgt1")
if got == "totally-different" || got == "tgt1" || len(got) != 36 {
t.Errorf("want fresh uuid, got %q", got)
}
})
}
// TestCopyIndices_EmptyMapping_NoOp verifies an empty chunk map short-circuits
// before any HTTP call.
func TestCopyIndices_EmptyMapping_NoOp(t *testing.T) {
repo, ts := newTestRepo(t, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("unexpected HTTP call: %s %s", r.Method, r.URL.Path)
})
defer ts.Close()
err := repo.CopyIndices(context.Background(), "kbSrc", map[string]string{}, map[string]string{}, "kbDst", 768, "manual")
if err != nil {
t.Fatalf("want nil, got %v", err)
}
}
// TestCopyIndices_ScanThenBatchSave verifies the search→BatchSave path:
// remaps IDs, keys the embedding by the *target source id* (OpenSearch
// BatchSave's lookup key), and emits one reindex audit event.
func TestCopyIndices_ScanThenBatchSave(t *testing.T) {
var (
mu sync.Mutex
bulkBody string
searchCnt int
)
handler := func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodHead:
w.WriteHeader(http.StatusOK) // alias exists → ensureReady no-op
case strings.Contains(r.URL.Path, "_search"):
mu.Lock()
searchCnt++
first := searchCnt == 1
mu.Unlock()
if first {
_, _ = w.Write([]byte(`{"hits":{"hits":[
{"_source":{"content":"c","source_id":"srcChunk","source_type":1,"chunk_id":"srcChunk","knowledge_id":"srcKnow","knowledge_base_id":"kbSrc","tag_id":"t","is_enabled":true,"is_recommended":false,"embedding":[0.1,0.2,0.3]}}
]}}`))
} else {
_, _ = w.Write([]byte(`{"hits":{"hits":[]}}`))
}
case strings.HasSuffix(r.URL.Path, "/_bulk"):
b, _ := io.ReadAll(r.Body)
mu.Lock()
bulkBody = string(b)
mu.Unlock()
_, _ = w.Write([]byte(`{"errors":false,"items":[]}`))
default:
_, _ = w.Write([]byte(`{}`))
}
}
repo, ts := newTestRepo(t, handler)
defer ts.Close()
spy := &spySink{}
repo.sink = spy
err := repo.CopyIndices(context.Background(), "kbSrc",
map[string]string{"srcKnow": "tgtKnow"}, // knowledge_id remap (sourceToTargetKBIDMap is keyed by knowledge_id, mirroring ES)
map[string]string{"srcChunk": "tgtChunk"},
"kbDst", 768, "manual")
if err != nil {
t.Fatalf("CopyIndices: %v", err)
}
mu.Lock()
defer mu.Unlock()
if bulkBody == "" {
t.Fatal("no bulk request captured")
}
// Target IDs present, source IDs gone from the written doc.
for _, want := range []string{`"chunk_id":"tgtChunk"`, `"knowledge_id":"tgtKnow"`, `"knowledge_base_id":"kbDst"`, `"source_id":"tgtChunk"`} {
if !strings.Contains(bulkBody, want) {
t.Errorf("bulk body missing %q\n%s", want, bulkBody)
}
}
if strings.Contains(bulkBody, `"knowledge_base_id":"kbSrc"`) {
t.Errorf("bulk body leaked source KB id\n%s", bulkBody)
}
// Embedding written (keyed by target source id internally).
if !strings.Contains(bulkBody, "0.1") {
t.Errorf("embedding not written\n%s", bulkBody)
}
if len(spy.reindex) != 1 || spy.reindex[0].docs != 1 {
t.Errorf("want 1 reindex event with docs=1, got %+v", spy.reindex)
}
}
// TestBatchUpdateChunkEnabledStatus_GroupedUpdateByQuery verifies the status
// map is grouped by value into one _update_by_query per distinct value, each
// passing chunk ids via terms + the new value via bound script params.
func TestBatchUpdateChunkEnabledStatus_GroupedUpdateByQuery(t *testing.T) {
var (
mu sync.Mutex
bodies []string
)
handler := func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "_update_by_query") {
b, _ := io.ReadAll(r.Body)
mu.Lock()
bodies = append(bodies, string(b))
mu.Unlock()
_, _ = w.Write([]byte(`{"updated":1,"version_conflicts":0,"failures":[]}`))
return
}
_, _ = w.Write([]byte(`{}`))
}
repo, ts := newTestRepo(t, handler)
defer ts.Close()
err := repo.BatchUpdateChunkEnabledStatus(context.Background(), map[string]bool{
"c1": true, "c2": false, "c3": true,
})
if err != nil {
t.Fatalf("BatchUpdateChunkEnabledStatus: %v", err)
}
mu.Lock()
defer mu.Unlock()
if len(bodies) != 2 {
t.Fatalf("want 2 grouped update_by_query calls (true/false), got %d: %v", len(bodies), bodies)
}
joined := strings.Join(bodies, "\n")
for _, want := range []string{"c1", "c2", "c3", "is_enabled", "params"} {
if !strings.Contains(joined, want) {
t.Errorf("update_by_query bodies missing %q\n%s", want, joined)
}
}
}
func TestBatchUpdateChunkEnabledStatus_Empty_NoOp(t *testing.T) {
repo, ts := newTestRepo(t, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("unexpected HTTP call: %s %s", r.Method, r.URL.Path)
})
defer ts.Close()
if err := repo.BatchUpdateChunkEnabledStatus(context.Background(), map[string]bool{}); err != nil {
t.Fatalf("want nil, got %v", err)
}
}
// TestInspectByQueryResponse covers the success path and the failure path,
// asserting cluster-side reason text is NOT surfaced in the returned error.
func TestInspectByQueryResponse(t *testing.T) {
t.Run("clean response", func(t *testing.T) {
body := strings.NewReader(`{"updated":5,"version_conflicts":0,"failures":[]}`)
if err := inspectByQueryResponse(body); err != nil {
t.Fatalf("want nil, got %v", err)
}
})
t.Run("failures do not leak reason", func(t *testing.T) {
body := strings.NewReader(`{"updated":1,"version_conflicts":0,"failures":[
{"id":"c9","cause":{"type":"version_conflict_engine_exception","reason":"SECRET document body leaked here"}}
]}`)
err := inspectByQueryResponse(body)
if err == nil {
t.Fatal("want error for failures, got nil")
}
if strings.Contains(err.Error(), "SECRET") {
t.Errorf("error leaked cluster reason: %v", err)
}
if !strings.Contains(err.Error(), "version_conflict_engine_exception") {
t.Errorf("error should surface bounded type: %v", err)
}
})
}
@@ -0,0 +1,405 @@
package opensearch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"academy/internal/logger"
"academy/internal/types"
)
// additionalParams contract (verified against
// elasticsearch/structs.go:ToDBVectorEmbedding and
// keywords_vector_hybrid_indexer.go:concurrentBatchSave on
// upstream/main):
//
// additionalParams["embedding"] map[string][]float32 // keyed by IndexInfo.SourceID
// additionalParams["chunk_enabled"] map[string]bool // keyed by IndexInfo.ChunkID
//
// Both keys may be absent. Missing "embedding" → keyword-only path
// (vector field omitted from the OpenSearch document, routed to the
// dim-less keywords index). Missing "chunk_enabled" → IndexInfo's own
// IsEnabled field is used as-is.
// Save indexes a single chunk. Idempotent: _id is set to chunk_id so
// re-indexing the same chunk overwrites instead of creating a duplicate.
func (r *Repository) Save(
ctx context.Context,
info *types.IndexInfo,
params map[string]any,
) error {
emb := lookupEmbedding(params, info.SourceID)
enabled := lookupChunkEnabled(params, info.ChunkID, info.IsEnabled)
dim := len(emb)
var targetIndex string
if dim > 0 {
if err := r.ensureReady(ctx, dim); err != nil {
return err
}
targetIndex = r.indexAlias(dim)
} else {
// Keyword-only path: no embedding supplied. Route to the
// dim-less <base>_keywords index.
if err := r.ensureKeywordsIndex(ctx); err != nil {
return err
}
targetIndex = r.keywordsIndex()
}
doc, err := json.Marshal(toDoc(info, emb, enabled))
if err != nil {
return fmt.Errorf("opensearch: marshal doc: %w", err)
}
req := osapi.IndexReq{
Index: targetIndex,
DocumentID: info.ChunkID, // _id = chunk_id (idempotent)
Body: bytes.NewReader(doc),
}
resp, err := r.client.Index(ctx, req)
if err != nil {
return wrapTransport(err)
}
if resp != nil {
drainAndClose(resp.Inspect().Response.Body)
}
return nil
}
// BatchSave NDJSON-bulk-indexes chunks. Inspects per-item errors and
// returns a typed error if ANY item fails.
//
// Dim-aware pre-marshal size cap: estimateBulkBodyBytes predicts NDJSON
// size before allocating; over-cap callers get ErrBatchTooLarge instead
// of a 50MB allocation that's then rejected. The service layer is
// responsible for dim-aware sub-batching above this.
func (r *Repository) BatchSave(
ctx context.Context,
infos []*types.IndexInfo,
params map[string]any,
) error {
if len(infos) == 0 {
return nil
}
emb, dim, err := extractBatchEmbeddings(params, infos)
if err != nil {
return err
}
// Pre-marshal size + count check.
if estimated := estimateBulkBodyBytes(len(infos), dim); estimated > 10*1024*1024 {
return fmt.Errorf(
"opensearch: estimated bulk body %dB exceeds 10MB cap (n=%d, dim=%d): %w",
estimated, len(infos), dim, ErrBatchTooLarge,
)
}
if len(infos) > 1000 {
return fmt.Errorf("opensearch: bulk n=%d exceeds 1000-doc cap: %w",
len(infos), ErrBatchTooLarge)
}
// Route by dim: dim==0 means the entire batch is keyword-only
// (concurrentBatchSaveNoEmbedding path), use the dim-less index.
var alias string
if dim == 0 {
if err := r.ensureKeywordsIndex(ctx); err != nil {
return err
}
alias = r.keywordsIndex()
} else {
if err := r.ensureReady(ctx, dim); err != nil {
return err
}
alias = r.indexAlias(dim)
}
body, err := buildBulkBody(alias, infos, emb, params)
if err != nil {
return err
}
req := osapi.BulkReq{Body: bytes.NewReader(body)}
resp, err := r.client.Bulk(ctx, req)
if err != nil {
return wrapTransport(err)
}
if resp != nil {
defer drainAndClose(resp.Inspect().Response.Body)
}
// Cap response body at 64MB (bulks of 1000 items are ~1-2MB success,
// can balloon with full per-item errors).
return inspectBulkResponse(io.LimitReader(resp.Inspect().Response.Body, 64<<20))
}
// estimateBulkBodyBytes returns a rough NDJSON size in bytes. Slight
// overestimate so the cap fires before real allocation. Per-item:
// - action header `{"index":{"_index":"...","_id":"..."}}\n` ≈ 100B
// - doc body: dim*5 (float ASCII) + ~700B metadata + content ≈ 1024B
func estimateBulkBodyBytes(n, dim int) int {
return n * (100 + dim*5 + 1024)
}
// buildBulkBody constructs the NDJSON request body. emb[i] may be nil/
// empty — toDoc handles the keyword-only case by omitting the
// "embedding" field. chunk_enabled lookup also happens per-doc.
func buildBulkBody(alias string, infos []*types.IndexInfo, emb [][]float32, params map[string]any) ([]byte, error) {
var buf bytes.Buffer
for i, info := range infos {
action := map[string]any{
"index": map[string]any{
"_index": alias,
"_id": info.ChunkID,
},
}
actionJSON, err := json.Marshal(action)
if err != nil {
return nil, fmt.Errorf("opensearch: marshal bulk action %d: %w", i, err)
}
buf.Write(actionJSON)
buf.WriteByte('\n')
enabled := lookupChunkEnabled(params, info.ChunkID, info.IsEnabled)
docJSON, err := json.Marshal(toDoc(info, emb[i], enabled))
if err != nil {
return nil, fmt.Errorf("opensearch: marshal doc %d: %w", i, err)
}
buf.Write(docJSON)
buf.WriteByte('\n')
}
return buf.Bytes(), nil
}
// inspectBulkResponse parses OpenSearch bulk response, returns a typed
// error if any item has a per-item .error. Surfaces up to 5 distinct
// error messages + total count for operator diagnosis.
//
// Does NOT include det.Error.Reason in the wrapped public error
// (Reason can contain document content fragments). Only ID + bounded
// enum Type is included. Full per-item Reason goes to log.Debug.
func inspectBulkResponse(body io.Reader) error {
var r struct {
Errors bool `json:"errors"`
Items []map[string]struct {
ID string `json:"_id"`
Status int `json:"status"`
Error *struct {
Type string `json:"type"`
Reason string `json:"reason"`
} `json:"error,omitempty"`
} `json:"items"`
}
if err := json.NewDecoder(body).Decode(&r); err != nil {
return fmt.Errorf("opensearch: parse bulk response: %w", ErrTransport)
}
if !r.Errors {
return nil
}
log := logger.GetLogger(context.Background())
var msgs []string
total := 0
for _, item := range r.Items {
for op, det := range item { // {"index": {...}}
if det.Error == nil {
continue
}
total++
// Full reason → debug log only (may contain doc content).
log.Debugf("[OpenSearch] bulk item err: op=%s id=%s type=%s reason=%s",
op, det.ID, det.Error.Type, det.Error.Reason)
if len(msgs) < 5 {
// Public message: ID (operator-meaningful) + Type (bounded enum).
msgs = append(msgs, fmt.Sprintf("[%s %s] %s", op, det.ID, det.Error.Type))
}
}
}
if total == 0 {
return nil // shouldn't happen if r.Errors=true, but defensive
}
return fmt.Errorf("opensearch: bulk partial failure (%d items failed, first 5: %s): %w",
total, strings.Join(msgs, "; "), ErrTransport)
}
// toDoc projects IndexInfo + embedding to the OpenSearch document
// shape. source_type is `int` (not stringified) — mapping declared as
// `integer` field for stable cross-enum-extension behavior. Omits the
// "embedding" field entirely when emb is empty (keyword-only doc, no
// k-NN graph entry).
func toDoc(info *types.IndexInfo, emb []float32, enabled bool) map[string]any {
doc := map[string]any{
"chunk_id": info.ChunkID,
"knowledge_id": info.KnowledgeID,
"knowledge_base_id": info.KnowledgeBaseID,
"source_id": info.SourceID,
"source_type": int(info.SourceType),
"tag_id": info.TagID,
"content": info.Content,
"is_enabled": enabled,
"is_recommended": info.IsRecommended,
}
if len(emb) > 0 {
doc["embedding"] = emb
}
return doc
}
// lookupEmbedding returns the embedding vector for info.SourceID.
// Empty slice (not nil) indicates "no embedding provided" — caller
// MUST check len(emb) before calling ensureReady.
//
// Defense in depth: tolerates the wrong shape rather than crash. The
// service layer is responsible for getting params right; we degrade
// to keyword-only for this doc and log a warning instead of panicking
// downstream.
func lookupEmbedding(params map[string]any, sourceID string) []float32 {
if params == nil {
return nil
}
raw, ok := params["embedding"]
if !ok {
return nil
}
embMap, ok := raw.(map[string][]float32)
if !ok {
logger.GetLogger(context.Background()).Warnf(
"[OpenSearch] additionalParams[\"embedding\"] is %T, want map[string][]float32", raw)
return nil
}
return embMap[sourceID] // nil/empty if SourceID not in map
}
// lookupChunkEnabled overlays the chunk_enabled map on top of
// info.IsEnabled. Returns the overlay value if present, else the
// default (info.IsEnabled).
func lookupChunkEnabled(params map[string]any, chunkID string, def bool) bool {
if params == nil {
return def
}
raw, ok := params["chunk_enabled"]
if !ok {
return def
}
enMap, ok := raw.(map[string]bool)
if !ok {
return def
}
if v, present := enMap[chunkID]; present {
return v
}
return def
}
// extractBatchEmbeddings projects the params["embedding"] map onto the
// info list, returning per-info embeddings (some may be empty) and the
// dimension inferred from the first non-empty entry. Returns dim=0 if
// no info has an embedding — caller routes to the keywords-only path.
//
// Defense in depth: all non-empty embeddings MUST share the same
// dimension. Mixed-dim → ErrDimensionMismatch.
func extractBatchEmbeddings(params map[string]any, infos []*types.IndexInfo) ([][]float32, int, error) {
out := make([][]float32, len(infos))
dim := 0
for i, info := range infos {
emb := lookupEmbedding(params, info.SourceID)
out[i] = emb
if len(emb) > 0 {
if dim == 0 {
dim = len(emb)
} else if len(emb) != dim {
return nil, 0, fmt.Errorf(
"opensearch: embedding[%s] dim=%d != first non-empty dim=%d: %w",
info.SourceID, len(emb), dim, ErrDimensionMismatch,
)
}
}
}
return out, dim, nil
}
// DeleteByChunkIDList runs _delete_by_query with a terms filter on
// chunk_id. Sync only — large batches (>1000) are rejected with
// ErrBatchTooLarge; the async task path that lifts the cap arrives in
// a later change.
//
// Refresh policy: opensearch-go v4's typed Params.Refresh is *bool, so
// the wire-level "wait_for" value documented in the OpenSearch REST
// API is not directly expressible. Refresh:&true forces immediate
// segment flush (read-your-writes guaranteed, but expensive at scale).
// A follow-up can revisit via a custom raw request if telemetry shows
// the cost is material at production batch frequencies.
func (r *Repository) DeleteByChunkIDList(
ctx context.Context, chunkIDs []string, dim int, _ string,
) error {
return r.deleteByList(ctx, chunkIDs, dim, "chunk_id")
}
func (r *Repository) DeleteBySourceIDList(
ctx context.Context, sourceIDs []string, dim int, _ string,
) error {
return r.deleteByList(ctx, sourceIDs, dim, "source_id")
}
func (r *Repository) DeleteByKnowledgeIDList(
ctx context.Context, knowledgeIDs []string, dim int, _ string,
) error {
return r.deleteByList(ctx, knowledgeIDs, dim, "knowledge_id")
}
// deleteByList factors the common cap / empty / ensureReady / dispatch
// logic out of the three DeleteBy* methods. dim==0 routes to the
// dim-less keywords index.
func (r *Repository) deleteByList(
ctx context.Context, ids []string, dim int, field string,
) error {
if len(ids) == 0 {
return nil
}
if len(ids) > 1000 {
return fmt.Errorf("opensearch: %s-delete batch %d > 1000 cap: %w",
field, len(ids), ErrBatchTooLarge)
}
var index string
if dim == 0 {
if err := r.ensureKeywordsIndex(ctx); err != nil {
return err
}
index = r.keywordsIndex()
} else {
if err := r.ensureReady(ctx, dim); err != nil {
return err
}
index = r.indexAlias(dim)
}
return r.deleteByTerms(ctx, index, field, ids)
}
func (r *Repository) deleteByTerms(
ctx context.Context, index, field string, values []string,
) error {
body, err := json.Marshal(map[string]any{
"query": map[string]any{
"terms": map[string]any{field: values},
},
})
if err != nil {
return fmt.Errorf("opensearch: marshal delete body: %w", err)
}
refresh := true
req := osapi.DocumentDeleteByQueryReq{
Indices: []string{index},
Body: bytes.NewReader(body),
Params: osapi.DocumentDeleteByQueryParams{Refresh: &refresh},
}
resp, err := r.client.Document.DeleteByQuery(ctx, req)
if err != nil {
return wrapTransport(err)
}
if resp != nil {
drainAndClose(resp.Inspect().Response.Body)
}
return nil
}
@@ -0,0 +1,62 @@
// Package opensearch implements the RetrieveEngineRepository interface
// for OpenSearch k-NN native vector search.
package opensearch
import "errors"
// Sentinel errors returned by Repository. The service-layer factory wraps
// these into typed AppError values (2200/2201) — the repository itself
// never imports internal/errors. The boundary is intentional (directional
// dependency).
var (
// ErrIndexNotFound — alias / underlying index missing. Search and
// delete-by-query operations return this when the per-dim alias has
// not been created yet (no Save has been issued for that dim).
ErrIndexNotFound = errors.New("opensearch: index not found")
// ErrDimensionMismatch — embedding dimension violates the per-dim
// invariant (e.g. dim <= 0, dim > 16000, or embeddings within a
// single batch disagree).
ErrDimensionMismatch = errors.New("opensearch: embedding dimension mismatch")
// ErrAuth — cluster returned 401 / 403. Distinguished from ErrTransport
// so the service layer can map to a clean 4xx instead of 503.
ErrAuth = errors.New("opensearch: authentication failed")
// ErrTransport — network / 5xx / opaque cluster error. Classified as
// transient: ensureReady does NOT persist this in initErr, so the next
// caller will retry.
ErrTransport = errors.New("opensearch: transport error")
// ErrVersionUnsupported — cluster is not OpenSearch, is OS 1.x, or is
// OS 2.0~2.3 (pre-Lucene-HNSW-GA). probeVersion enforces.
ErrVersionUnsupported = errors.New("opensearch: cluster version unsupported")
// ErrConfigInvalid — IndexConfig / storeID / sanitizeIndexName guard
// failed, or the k-NN plugin is missing on one or more cluster nodes.
ErrConfigInvalid = errors.New("opensearch: invalid index config")
// ErrFeatureNotEnabled — stubs.go returns this from methods whose real
// implementation has not landed yet (CopyIndices / BatchUpdateChunk* /
// swapToVersion, plus the read/write methods that a follow-up commit
// will replace with production code).
ErrFeatureNotEnabled = errors.New("opensearch: feature not enabled in this build")
// ErrBatchTooLarge — Save / Delete batch exceeded the driver's sync
// cap. Distinct from ErrFeatureNotEnabled so the service layer can
// chunk + retry rather than treat the failure as "waiting on a future
// implementation."
ErrBatchTooLarge = errors.New("opensearch: batch size exceeds driver cap")
// ErrCircuitBreaker — OpenSearch k-NN circuit breaker returned 429
// (knn_circuit_breaker_exception). Classified as transient so the
// caller can retry after the operator scales the cluster.
ErrCircuitBreaker = errors.New("opensearch: knn circuit breaker open")
)
// isTransientErr classifies sentinel errors. Transient errors do not get
// persisted in ensureReady's initErr cache — they can be retried by the
// next caller after the underlying cause clears.
func isTransientErr(err error) bool {
return errors.Is(err, ErrTransport) || errors.Is(err, ErrCircuitBreaker)
}
@@ -0,0 +1,23 @@
package opensearch
import (
"context"
"academy/internal/types"
)
// TestConnection verifies an OpenSearch cluster is reachable, runs a
// supported version, and has the k-NN plugin installed on every node. It is
// the connectivity probe used by the VectorStore service's CreateStore
// health-check (the driver's unexported probes are reused here). Returns a
// wrapped sentinel error on failure; nil on success.
func TestConnection(ctx context.Context, cfg *types.ConnectionConfig) error {
client, err := NewOpenSearchClient(cfg)
if err != nil {
return err
}
if err := probeVersion(ctx, client); err != nil {
return err
}
return probeKNNPlugin(ctx, client)
}
@@ -0,0 +1,50 @@
package opensearch
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"academy/internal/types"
)
// clusterHandler serves both GET / (version info) and /_cat/plugins, so the
// full TestConnection probe (version + k-NN plugin) can run end to end.
func clusterHandler(distribution, number string, plugins []osapi.CatPluginResp) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/_cat/plugins" {
_ = json.NewEncoder(w).Encode(plugins)
return
}
_, _ = w.Write([]byte(`{"version":{"distribution":"` + distribution + `","number":"` + number + `"}}`))
}
}
func TestTestConnection_Success(t *testing.T) {
ts := httptest.NewServer(clusterHandler("opensearch", "3.3.2", []osapi.CatPluginResp{
{Name: "node-1", Component: "opensearch-knn"},
}))
defer ts.Close()
if err := TestConnection(context.Background(), &types.ConnectionConfig{Addr: ts.URL}); err != nil {
t.Errorf("healthy cluster: want nil, got %v", err)
}
}
func TestTestConnection_RejectsElasticsearch(t *testing.T) {
ts := httptest.NewServer(clusterHandler("elasticsearch", "8.10.4", nil))
defer ts.Close()
if err := TestConnection(context.Background(), &types.ConnectionConfig{Addr: ts.URL}); err == nil {
t.Error("elasticsearch cluster should be rejected")
}
}
func TestTestConnection_EmptyAddr(t *testing.T) {
if err := TestConnection(context.Background(), &types.ConnectionConfig{}); err == nil {
t.Error("empty addr should be rejected")
}
}
@@ -0,0 +1,420 @@
package opensearch
import (
"bytes"
"context"
"encoding/json"
"fmt"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"academy/internal/logger"
)
// createIndexAndAlias creates "<alias>_v1" with the full k-NN mapping
// and then aliases "<alias>" → "<alias>_v1". Idempotent: returns nil if
// the alias already exists (so concurrent NewRepository calls in
// different processes don't race the PUT).
//
// Orphan cleanup: if aliasPut fails after a successful indicesCreate,
// the function attempts best-effort DELETE of the orphan _v1 index.
// Cleanup failure is logged but does not mask the original aliasPut
// error.
//
// Mapping-drift detection: if indicesCreate returns
// resource_already_exists_exception (cross-process race), the existing
// mapping's structural fingerprint is checked against the expected
// fingerprint. Drift returns ErrConfigInvalid wrapping a clear "manual
// reindex required" message instead of silently overlaying a foreign
// mapping.
func (r *Repository) createIndexAndAlias(ctx context.Context, dim int) error {
log := logger.GetLogger(ctx)
alias := r.indexAlias(dim)
realIndex := alias + "_v1"
exists, err := r.aliasExists(ctx, alias)
if err != nil {
return fmt.Errorf("alias check %s: %w", alias, err)
}
if exists {
return nil // another writer already set it up
}
body, err := buildIndexMapping(r.cfg, dim)
if err != nil {
return fmt.Errorf("build mapping for dim=%d: %w", dim, err)
}
indexCreated := false
if err := r.indicesCreate(ctx, realIndex, body); err != nil {
if isAlreadyExistsError(err) {
// Cross-process race or stale orphan. Verify the existing
// mapping matches what we expected; drift → ErrConfigInvalid.
if driftErr := r.verifyMappingMatches(ctx, realIndex, body); driftErr != nil {
return fmt.Errorf(
"mapping drift on %s: existing index has incompatible mapping; "+
"manual reindex required: %w",
realIndex, driftErr,
)
}
// Mapping matches → safe to proceed with alias setup.
} else {
return fmt.Errorf("create index %s: %w", realIndex, err)
}
} else {
indexCreated = true
}
if err := r.aliasPut(ctx, realIndex, alias); err != nil {
// Best-effort orphan cleanup so future retries find a clean slate.
if indexCreated {
if delErr := r.indicesDelete(ctx, realIndex); delErr != nil {
log.Warnf("[OpenSearch] orphan cleanup failed for %s: %v "+
"(operator must DELETE manually)", realIndex, delErr)
} else {
log.Infof("[OpenSearch] cleaned up orphan %s after aliasPut failure", realIndex)
}
}
return fmt.Errorf("put alias %s → %s: %w", alias, realIndex, err)
}
if indexCreated {
// Emit only when we actually provisioned the index (not when a
// concurrent writer / existing index short-circuited above).
r.auditSink().EmitIndexCreated(ctx, alias, dim)
}
return nil
}
// buildIndexMapping returns the full mapping JSON for a new OpenSearch
// k-NN index. content uses the standard analyzer (BM25 default); all
// *_id fields are explicit keyword sub-fields so DeleteByQuery / terms
// filters hit them without the ES v8 "useKeywordSuffix" auto-detection
// dance.
//
// match_type is intentionally NOT in the mapping — it's a per-result
// classification derived from RetrieverType at parse time. source_type
// is stored as `integer` (not stringified) so the wire format remains
// stable across SourceType enum extension.
//
// Pure function — no IO, no logging. Easy to unit-test (byte-exact diff).
func buildIndexMapping(cfg internalCfg, dim int) ([]byte, error) {
type mapping struct {
Settings struct {
Index struct {
Knn bool `json:"knn"`
NumberOfShards int `json:"number_of_shards"`
NumberOfReplicas int `json:"number_of_replicas"`
RefreshInterval string `json:"refresh_interval"`
KnnAlgoParamEFSearch int `json:"knn.algo_param.ef_search"`
} `json:"index"`
} `json:"settings"`
Mappings struct {
Properties map[string]any `json:"properties"`
} `json:"mappings"`
}
var m mapping
m.Settings.Index.Knn = true
m.Settings.Index.NumberOfShards = cfg.shards
m.Settings.Index.NumberOfReplicas = cfg.replicas
m.Settings.Index.RefreshInterval = "1s"
m.Settings.Index.KnnAlgoParamEFSearch = cfg.efSearch
m.Mappings.Properties = map[string]any{
"embedding": map[string]any{
"type": "knn_vector",
"dimension": dim,
"method": map[string]any{
"name": "hnsw",
"space_type": "cosinesimil",
"engine": cfg.knnEngine,
"parameters": map[string]any{
"m": cfg.hnswM,
"ef_construction": cfg.hnswEFConstruction,
},
},
},
"content": map[string]any{"type": "text", "analyzer": "standard"},
"chunk_id": map[string]any{"type": "keyword"},
"knowledge_id": map[string]any{"type": "keyword"},
"knowledge_base_id": map[string]any{"type": "keyword"},
"tag_id": map[string]any{"type": "keyword"},
"source_id": map[string]any{"type": "keyword"},
"source_type": map[string]any{"type": "integer"},
"is_enabled": map[string]any{"type": "boolean"},
"is_recommended": map[string]any{"type": "boolean"},
}
out, err := json.Marshal(&m)
if err != nil {
// Cannot happen for our internal struct, but propagate for symmetry
// with the other JSON builders in the package.
return nil, fmt.Errorf("marshal mapping: %w", err)
}
return out, nil
}
// buildKeywordsMapping returns the mapping for the dim-less keyword-only
// index. Same as buildIndexMapping but with the embedding field omitted
// — used by the no-embedding save path (the service layer dispatches
// there when the knowledge base has vector indexing disabled).
func buildKeywordsMapping(cfg internalCfg) ([]byte, error) {
type mapping struct {
Settings struct {
Index struct {
NumberOfShards int `json:"number_of_shards"`
NumberOfReplicas int `json:"number_of_replicas"`
RefreshInterval string `json:"refresh_interval"`
} `json:"index"`
} `json:"settings"`
Mappings struct {
Properties map[string]any `json:"properties"`
} `json:"mappings"`
}
var m mapping
m.Settings.Index.NumberOfShards = cfg.shards
m.Settings.Index.NumberOfReplicas = cfg.replicas
m.Settings.Index.RefreshInterval = "1s"
m.Mappings.Properties = map[string]any{
"content": map[string]any{"type": "text", "analyzer": "standard"},
"chunk_id": map[string]any{"type": "keyword"},
"knowledge_id": map[string]any{"type": "keyword"},
"knowledge_base_id": map[string]any{"type": "keyword"},
"tag_id": map[string]any{"type": "keyword"},
"source_id": map[string]any{"type": "keyword"},
"source_type": map[string]any{"type": "integer"},
"is_enabled": map[string]any{"type": "boolean"},
"is_recommended": map[string]any{"type": "boolean"},
}
out, err := json.Marshal(&m)
if err != nil {
return nil, fmt.Errorf("marshal keywords mapping: %w", err)
}
return out, nil
}
// ensureKeywordsIndex creates the dim-less keyword-only index used by
// the no-embedding save path. mutex + flag pattern so transient
// failures can be retried by the next caller (sync.Once cannot be
// reset).
func (r *Repository) ensureKeywordsIndex(ctx context.Context) error {
r.keywordsMu.Lock()
defer r.keywordsMu.Unlock()
if r.keywordsReady {
return nil
}
if r.keywordsErr != nil && !isTransientErr(r.keywordsErr) {
// Permanent failure — don't retry, surface the same error.
return r.keywordsErr
}
name := r.keywordsIndex()
exists, err := r.aliasExists(ctx, name) // returns true if index exists too
if err != nil {
r.keywordsErr = err
return err
}
if exists {
r.keywordsReady = true
r.keywordsErr = nil
return nil
}
body, err := buildKeywordsMapping(r.cfg)
if err != nil {
r.keywordsErr = err
return err
}
created := false
if err := r.indicesCreate(ctx, name, body); err != nil {
if !isAlreadyExistsError(err) {
r.keywordsErr = err
return err
}
// resource_already_exists_exception — race with concurrent process,
// treat as success.
} else {
created = true
}
r.keywordsReady = true
r.keywordsErr = nil
if created {
// dim=0 marks the dim-less keyword-only index.
r.auditSink().EmitIndexCreated(ctx, name, 0)
}
return nil
}
// indicesCreate is the low-level wrapper around Indices.Create. Body is
// the JSON mapping produced by buildIndexMapping.
func (r *Repository) indicesCreate(ctx context.Context, name string, body []byte) error {
req := osapi.IndicesCreateReq{Index: name, Body: bytes.NewReader(body)}
resp, err := r.client.Indices.Create(ctx, req)
if err != nil {
return wrapTransport(err)
}
if resp != nil {
drainAndClose(resp.Inspect().Response.Body)
}
return nil
}
// indicesDelete is used by createIndexAndAlias's orphan cleanup path.
// Caller decides what to do with the error.
func (r *Repository) indicesDelete(ctx context.Context, name string) error {
req := osapi.IndicesDeleteReq{Indices: []string{name}}
resp, err := r.client.Indices.Delete(ctx, req)
if err != nil {
return wrapTransport(err)
}
if resp != nil {
drainAndClose(resp.Inspect().Response.Body)
}
return nil
}
// aliasExists uses HEAD /_alias/<name> (Indices.Alias.Exists) — returns
// true on 200, false on 404, error on 5xx / transport.
//
// SDK quirk (opensearch-go v4.6.0): the Exists method passes
// dataPointer=nil to its internal do(), which means non-2xx responses
// come back as a plain *errors.errorString ("status: 404 Not Found")
// rather than as a *opensearch.StructError. We therefore inspect
// resp.StatusCode directly (resp is always returned even when err is
// non-nil) and only fall back to wrapTransport for the "no response at
// all" case (true network failure).
func (r *Repository) aliasExists(ctx context.Context, alias string) (bool, error) {
req := osapi.AliasExistsReq{Alias: []string{alias}}
resp, err := r.client.Indices.Alias.Exists(ctx, req)
if resp != nil {
statusCode := resp.StatusCode
drainAndClose(resp.Body)
switch statusCode {
case 200:
return true, nil
case 404:
return false, nil
}
// Unexpected status (5xx) — fall through to the err path so
// wrapTransport can classify (and so the test handler's
// errBody is logged for diagnosis).
}
if err != nil {
return false, wrapTransport(err)
}
return false, nil
}
// aliasPut creates an alias pointing at index. Single add operation
// (rolling-reindex atomic swap is deferred to a follow-up PR — see
// stubs.go swapToVersion).
func (r *Repository) aliasPut(ctx context.Context, index, alias string) error {
req := osapi.AliasPutReq{
Indices: []string{index},
Alias: alias,
}
resp, err := r.client.Indices.Alias.Put(ctx, req)
if err != nil {
return wrapTransport(err)
}
if resp != nil {
drainAndClose(resp.Inspect().Response.Body)
}
return nil
}
// verifyMappingMatches GETs the existing index's mapping and compares
// the embedding field's structural fingerprint (dimension, HNSW
// parameters, engine) against the expected. A full field-by-field diff
// would be ideal but expensive; we check only the parts that matter for
// query correctness.
func (r *Repository) verifyMappingMatches(ctx context.Context, index string, expected []byte) error {
req := osapi.MappingGetReq{Indices: []string{index}}
resp, err := r.client.Indices.Mapping.Get(ctx, &req)
if err != nil {
return fmt.Errorf("get mapping %s: %w", index, wrapTransport(err))
}
if resp != nil {
drainAndClose(resp.Inspect().Response.Body)
}
// Both fingerprints are derived from the mapping's embedding-field
// HNSW parameters: dimension, m, ef_construction, engine, space_type.
// We parse the expected (our own JSON) and the actual (cluster
// response) and compare just those bits.
expectedFP, err := extractEmbeddingFingerprint(expected)
if err != nil {
return fmt.Errorf("parse expected fingerprint: %w", err)
}
actualFP, err := extractMappingFingerprintFromResp(resp, index)
if err != nil {
return fmt.Errorf("parse actual fingerprint: %w", err)
}
if expectedFP != actualFP {
return fmt.Errorf("mapping fingerprint mismatch: expected %+v, got %+v: %w",
expectedFP, actualFP, ErrConfigInvalid)
}
return nil
}
// embFingerprint is the minimal set of HNSW parameters that uniquely
// determine query semantics for a k-NN index. If any of these differ
// between create-time and an existing index, retrieval is incorrect.
type embFingerprint struct {
Dimension int
M int
EFConstruction int
Engine string
SpaceType string
}
// extractEmbeddingFingerprint parses our own mapping JSON (produced by
// buildIndexMapping) to pull out the HNSW parameters.
func extractEmbeddingFingerprint(body []byte) (embFingerprint, error) {
var m struct {
Mappings struct {
Properties map[string]any `json:"properties"`
} `json:"mappings"`
}
if err := json.Unmarshal(body, &m); err != nil {
return embFingerprint{}, err
}
return extractFingerprintFromProps(m.Mappings.Properties)
}
// extractMappingFingerprintFromResp parses the cluster's GET-mapping
// response and pulls out the embedding-field HNSW fingerprint for the
// given index.
func extractMappingFingerprintFromResp(resp *osapi.MappingGetResp, index string) (embFingerprint, error) {
indexMapping, ok := resp.Indices[index]
if !ok {
return embFingerprint{}, fmt.Errorf("index %s not in mapping response", index)
}
// MappingGetResp.Indices[index].Mappings is a json.RawMessage in
// the SDK — we decode the inner properties shape ourselves.
var m struct {
Properties map[string]any `json:"properties"`
}
if err := json.Unmarshal(indexMapping.Mappings, &m); err != nil {
return embFingerprint{}, err
}
return extractFingerprintFromProps(m.Properties)
}
func extractFingerprintFromProps(props map[string]any) (embFingerprint, error) {
emb, ok := props["embedding"].(map[string]any)
if !ok {
return embFingerprint{}, fmt.Errorf("embedding field missing or wrong type")
}
dim, _ := emb["dimension"].(float64) // json.Unmarshal produces float64 for numbers
method, _ := emb["method"].(map[string]any)
engine, _ := method["engine"].(string)
spaceType, _ := method["space_type"].(string)
params, _ := method["parameters"].(map[string]any)
m, _ := params["m"].(float64)
efc, _ := params["ef_construction"].(float64)
return embFingerprint{
Dimension: int(dim),
M: int(m),
EFConstruction: int(efc),
Engine: engine,
SpaceType: spaceType,
}, nil
}
@@ -0,0 +1,49 @@
package opensearch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
)
// MoveKnowledgeIndices changes every vector for the source document, including
// historical vectors whose chunks no longer exist, while preserving vector IDs.
func (r *Repository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
_ int,
_ string,
) error {
body, err := json.Marshal(map[string]any{
"query": map[string]any{"bool": map[string]any{"filter": []any{
map[string]any{"term": map[string]any{"knowledge_base_id": sourceKB}},
map[string]any{"term": map[string]any{"knowledge_id": knowledgeID}},
}}},
"script": map[string]any{
"lang": "painless",
"source": "ctx._source.knowledge_base_id = params.target; ctx._source.tag_id = '';",
"params": map[string]any{"target": targetKB},
},
})
if err != nil {
return fmt.Errorf("opensearch: marshal move: %w", err)
}
refresh := true
resp, err := r.client.UpdateByQuery(ctx, osapi.UpdateByQueryReq{
Indices: []string{r.baseIndex + "_*"}, Body: bytes.NewReader(body),
Params: osapi.UpdateByQueryParams{Refresh: &refresh},
})
if err != nil {
return wrapTransport(err)
}
if resp == nil {
return fmt.Errorf("opensearch: missing move response: %w", ErrTransport)
}
defer drainAndClose(resp.Inspect().Response.Body)
return inspectByQueryResult(io.LimitReader(resp.Inspect().Response.Body, 16<<20), true)
}
@@ -0,0 +1,61 @@
package opensearch
import (
"context"
"encoding/json"
"net/http"
"testing"
"github.com/stretchr/testify/require"
)
func TestMoveIndicesRequiresCompleteResult(t *testing.T) {
for _, tt := range []struct {
name, response string
fails bool
}{
{"complete", `{"total":2,"updated":2,"version_conflicts":0,"failures":[]}`, false},
{"partial", `{"total":100,"updated":40,"failures":[]}`, true},
{"empty", `{"total":0,"updated":0,"failures":[]}`, false},
{"missing counts", `{"failures":[]}`, true},
{"missing total", `{"updated":2,"failures":[]}`, true},
{"missing updated", `{"total":2,"failures":[]}`, true},
{"negative", `{"total":-1,"updated":-1,"failures":[]}`, true},
{"conflict", `{"updated":1,"version_conflicts":1,"failures":[]}`, true},
{"timeout", `{"timed_out":true,"version_conflicts":0,"failures":[]}`, true},
{"failure", `{"failures":[{"id":"doc","cause":{"type":"unavailable"}}]}`, true},
} {
t.Run(tt.name, func(t *testing.T) {
repo, server := newTestRepo(t, func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(tt.response))
})
defer server.Close()
err := repo.MoveKnowledgeIndices(
context.Background(), "source", "target", "doc", []string{"chunk"}, 1, "file",
)
if tt.fails {
require.ErrorIs(t, err, ErrTransport)
} else {
require.NoError(t, err)
}
})
}
}
func TestMoveIndicesIncludesOrphansEvenWithoutDatabaseChunks(t *testing.T) {
var body map[string]any
repo, server := newTestRepo(t, func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Errorf("decode move request: %v", err)
}
_, _ = w.Write([]byte(`{"total":1,"updated":1,"failures":[]}`))
})
defer server.Close()
require.NoError(t, repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 1, "file"))
want := `{"bool":{"filter":[{"term":{"knowledge_base_id":"source"}},{"term":{"knowledge_id":"doc"}}]}}`
query, err := json.Marshal(body["query"])
require.NoError(t, err)
require.JSONEq(t, want, string(query), "all vectors for this exact source document must be selected")
script := body["script"].(map[string]any)
require.Equal(t, map[string]any{"target": "target"}, script["params"])
}
@@ -0,0 +1,168 @@
package opensearch
import (
"encoding/json"
"fmt"
"academy/internal/types"
)
// retrieveFilters is the typed shape of OpenSearch query filter
// clauses. It is the ONLY way callers (Retrieve) can constrain a
// query — there is no JSON-fragment escape hatch. This prevents the
// "map[string]interface{} injection" failure mode where a hostile
// chunk_id like {"$or":[...]} would otherwise be inlined as JSON DSL.
//
// All slice fields are interpreted as IN-set membership (OS terms
// query). Empty slice = no constraint on that dimension.
//
// IncludeDisabled controls the implicit is_enabled = true clause:
// - false (default) — appends is_enabled term, hiding disabled chunks
// - true — omits the clause; admin / audit callers can
// observe disabled chunks. Service layer pins false for user-facing
// APIs.
type retrieveFilters struct {
KBIDs []string
KnowledgeIDs []string
TagIDs []string
ExcludeChunkIDs []string
ExcludeKnowledgeIDs []string
IncludeDisabled bool
}
// fromParams projects RetrieveParams to retrieveFilters, applying the
// multi-KB input from the service-layer dispatcher as terms.
// ExcludeKnowledgeIDs is included so the OpenSearch driver matches the
// behaviour of the Qdrant / pgvector drivers.
func fromParams(p types.RetrieveParams) *retrieveFilters {
return &retrieveFilters{
KBIDs: p.KnowledgeBaseIDs,
KnowledgeIDs: p.KnowledgeIDs,
TagIDs: p.TagIDs,
ExcludeChunkIDs: p.ExcludeChunkIDs,
ExcludeKnowledgeIDs: p.ExcludeKnowledgeIDs,
// IncludeDisabled stays false — set explicitly by admin callers
// only. Driver receives this from a typed field, not from
// AdditionalParams, so the contract is checked at compile time.
}
}
// toBoolMust emits the OpenSearch bool.must clause list for this
// filter. Returns a freshly allocated slice each call so callers can
// safely append additional clauses (e.g. the keyword match clause in
// buildKeywordQuery) without aliasing.
func (f *retrieveFilters) toBoolMust() []map[string]any {
var must []map[string]any
if len(f.KBIDs) > 0 {
must = append(must, map[string]any{
"terms": map[string]any{"knowledge_base_id": f.KBIDs},
})
}
if len(f.KnowledgeIDs) > 0 {
must = append(must, map[string]any{
"terms": map[string]any{"knowledge_id": f.KnowledgeIDs},
})
}
if len(f.TagIDs) > 0 {
must = append(must, map[string]any{
"terms": map[string]any{"tag_id": f.TagIDs},
})
}
if len(f.ExcludeChunkIDs) > 0 {
must = append(must, map[string]any{
"bool": map[string]any{
"must_not": map[string]any{
"terms": map[string]any{"chunk_id": f.ExcludeChunkIDs},
},
},
})
}
if len(f.ExcludeKnowledgeIDs) > 0 {
must = append(must, map[string]any{
"bool": map[string]any{
"must_not": map[string]any{
"terms": map[string]any{"knowledge_id": f.ExcludeKnowledgeIDs},
},
},
})
}
if !f.IncludeDisabled {
must = append(must, map[string]any{
"term": map[string]any{"is_enabled": true},
})
}
return must
}
// buildKNNQuery composes a pure k-NN ANN query with caller filters. No
// hybrid pipeline — native hybrid is out of scope for this PR; fusion
// stays in the service-layer RRF.
//
// Applies `min_score` when threshold > 0. The OpenSearch k-NN plugin's
// SpaceType.COSINESIMIL.scoreTranslation produces (1 + cos) / 2 ∈ [0, 1]
// at the client, while callers pass a cosine-similarity threshold (the
// scale every other engine uses), so the threshold is mapped onto the
// plugin's scale; wrapResults maps scores back.
//
// Signature returns ([]byte, error) so callers can propagate
// json.Marshal failures (reachable for NaN / +/-Inf in embedding).
func buildKNNQuery(embedding []float32, topK int, threshold float64, f *retrieveFilters) ([]byte, error) {
knn := map[string]any{
"embedding": map[string]any{
"vector": embedding,
"k": topK,
"filter": map[string]any{
"bool": map[string]any{"must": f.toBoolMust()},
},
},
}
body := map[string]any{
"size": topK,
"query": map[string]any{"knn": knn},
}
if threshold > 0 {
body["min_score"] = cosineToKNNScore(threshold)
}
out, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal knn query: %w", err)
}
return out, nil
}
// buildKeywordQuery composes a BM25 match query against the content
// field with caller filters. Score range is OpenSearch BM25 native (no
// upper bound) — the normalizer keyword-passthrough rule treats keyword
// retrievers as rank-based for RRF, so the score scale does not need
// normalization here. min_score still applied if requested.
func buildKeywordQuery(queryText string, topK int, threshold float64, f *retrieveFilters) ([]byte, error) {
must := f.toBoolMust()
must = append(must, map[string]any{
"match": map[string]any{"content": queryText},
})
body := map[string]any{
"size": topK,
"query": map[string]any{"bool": map[string]any{"must": must}},
}
if threshold > 0 {
body["min_score"] = threshold
}
out, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal keyword query: %w", err)
}
return out, nil
}
// cosineToKNNScore maps a cosine similarity onto the k-NN plugin's
// cosinesimil score, (1 + cos) / 2.
func cosineToKNNScore(cos float64) float64 {
return (1 + cos) / 2
}
// knnScoreToCosine inverts cosineToKNNScore. Vector scores leave the driver
// as cosine similarity so they compare with the other engines' scores and
// with thresholds; the raw (1 + cos) / 2 put a 0.5 threshold at cos >= 0.
func knnScoreToCosine(score float64) float64 {
return 2*score - 1
}
@@ -0,0 +1,456 @@
package opensearch
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"github.com/opensearch-project/opensearch-go/v4"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// EngineAwareNormalizer applies the documented per-engine cosine-score
// formula. (Repository implements interfaces.RetrieveEngineRepository for
// OpenSearch k-NN. Safe for concurrent use after construction: all fields
// except the once / initErr maps are read-only after NewRepository returns;
// per-dimension index initialization is guarded by sync.Once.
//
// Lifecycle: NewRepository validates connectivity + cluster version +
// k-NN plugin, but does NOT create any index. Index creation happens
// lazily on first Save / BatchSave / Retrieve once the embedding
// dimension is known (see ensureReady — per-dimension index naming).
//
// Concurrency: A single Repository instance is shared across N goroutines
// concurrently retrieving from the same store (the multi-store fan-out
// dispatcher in the service layer). The struct is therefore designed to
// be allocation-stable after construction; the only mutable state is the
// sync.Once + initErr maps, each guarded by its own mutex.
//
// CRITICAL INVARIANT: initErr[dim] = err must be written INSIDE the
// once.Do closure — moving it outside opens a TOCTOU where a concurrent
// caller reads zero before the first caller persists.
type Repository struct {
client *osapi.Client
baseIndex string // pre-suffix base name, e.g. "academy_abcdef012345"
cfg internalCfg // immutable after construction (value, not pointer)
// Per-dimension lazy initialization. ensureReady(ctx, dim) inserts an
// entry the first time dim is seen, runs the create-index work inside
// sync.Once, and persists any permanent error so subsequent callers
// see the same failure without re-attempting the PUT. Transient
// errors (ErrTransport, ErrCircuitBreaker) are NOT persisted — the
// next caller retries.
onceMu sync.Mutex
once map[int]*sync.Once
initMu sync.Mutex
initErr map[int]error
// Lazy init state for the dim-less keyword-only index used by the
// no-embedding path (concurrentBatchSaveNoEmbedding in the service
// layer). Mutex + flag pattern (rather than sync.Once) so transient
// failures can be retried by the next caller — sync.Once does not
// support reset.
keywordsMu sync.Mutex
keywordsReady bool
keywordsErr error
// sink receives audit events (index created / reindex executed). nil
// means no auditing; use r.auditSink() to get a non-nil sink. Set via
// WithAuditSink at construction.
sink AuditSink
}
// Compile-time interface satisfaction (Go best practice — keeps the build
// red if the interface drifts and our implementation lags).
var _ interfaces.RetrieveEngineRepository = (*Repository)(nil)
// NewRepository builds a new OpenSearch k-NN repository and verifies the
// backing cluster is reachable + version-compatible + has the k-NN
// plugin installed on every cluster node. It does NOT create any index —
// callers (Save / Retrieve) trigger lazy per-dimension creation via
// ensureReady on first use.
//
// storeID is the VectorStore.ID owning this repository instance. It is
// folded into the base index name so multiple OpenSearch VectorStores
// pointing at the same cluster do not collide:
// - storeID == "" — env-path; no prefix, base index = "academy".
// - len(storeID) >= 16 — DB-store path; prefix = storeID[:12]
// (48-bit collision space).
// - 1..15 chars — rejected with ErrConfigInvalid.
//
// indexCfg is optional — pass nil to use env var (OPENSEARCH_INDEX) or
// default ("academy") values.
//
// Optional behavior is configured via functional options (e.g.
// WithAuditSink). Passing no options keeps audit emission as a no-op, so the
// env-path and tests need no extra wiring.
//
// Returns a typed sentinel error wrapped with %w; callers translate to
// AppError at the engine-factory boundary.
func NewRepository(
ctx context.Context,
client *osapi.Client,
storeID string,
indexCfg *types.IndexConfig,
opts ...Option,
) (interfaces.RetrieveEngineRepository, error) {
log := logger.GetLogger(ctx)
if storeID != "" && len(storeID) < 16 {
return nil, fmt.Errorf(
"opensearch: storeID must be empty or >=16 chars, got %d: %w",
len(storeID), ErrConfigInvalid,
)
}
base := types.ResolveIndexName(indexCfg, "OPENSEARCH_INDEX", "academy")
if storeID != "" {
// 12 hex chars → 48-bit collision space (UUID is 32 chars; using
// half gives strong-enough collision avoidance for the realistic
// "two OpenSearch VectorStores on the same cluster" case).
base = fmt.Sprintf("%s_%s", base, storeID[:12])
}
base, err := sanitizeIndexName(base)
if err != nil {
return nil, fmt.Errorf("opensearch: invalid index base name: %w", err)
}
icfg, err := buildInternalCfg(indexCfg)
if err != nil {
return nil, fmt.Errorf("opensearch: invalid index config: %w", err)
}
if err := probeVersion(ctx, client); err != nil {
return nil, err // already wraps ErrVersionUnsupported / ErrTransport
}
if err := probeKNNPlugin(ctx, client); err != nil {
return nil, err // already wraps ErrConfigInvalid / ErrTransport
}
r := &Repository{
client: client,
baseIndex: base,
cfg: icfg,
once: make(map[int]*sync.Once),
initErr: make(map[int]error),
}
for _, opt := range opts {
opt(r)
}
log.Infof("[OpenSearch] repository ready (baseIndex=%s, knn_engine=%s, hnsw_m=%d)",
base, icfg.knnEngine, icfg.hnswM)
return r, nil
}
// ensureReady creates the per-dimension index (alias-backed) the first
// time a given embedding dimension is seen. Concurrent callers for the
// same dim block on the same sync.Once.
//
// Transient vs permanent error handling:
// - PERMANENT failures (ErrConfigInvalid, ErrAuth, ErrVersionUnsupported,
// ErrDimensionMismatch) are persisted in initErr[dim] and re-served to
// all future callers without retry — caller must restart or fix config.
// - TRANSIENT failures (ErrTransport, ErrCircuitBreaker) are NOT
// persisted; the sync.Once is reset for that dim so the next caller
// can retry. This prevents a single cluster blip from permanently
// locking out a dim.
//
// Caller MUST pass a real ctx; nil is rejected. dim must be in (0, 16000]
// (OpenSearch knn_vector hard limit).
//
// CRITICAL INVARIANT: initErr[dim] = err is written INSIDE the once.Do
// closure. Moving it outside opens a TOCTOU where a concurrent caller
// reads zero before the first caller persists.
func (r *Repository) ensureReady(ctx context.Context, dim int) error {
if ctx == nil {
return fmt.Errorf("opensearch: ensureReady requires non-nil ctx")
}
if dim <= 0 || dim > 16000 {
return fmt.Errorf("opensearch: dim %d out of range (1..16000): %w",
dim, ErrDimensionMismatch)
}
r.onceMu.Lock()
once, ok := r.once[dim]
if !ok {
once = &sync.Once{}
r.once[dim] = once
}
r.onceMu.Unlock()
once.Do(func() {
err := r.createIndexAndAlias(ctx, dim)
if err != nil && isTransientErr(err) {
// Do NOT persist transient errors. Reset the sync.Once so
// the next caller retries (requires once map mutation).
r.onceMu.Lock()
delete(r.once, dim)
r.onceMu.Unlock()
// Fall through — caller still sees this attempt's err.
}
r.initMu.Lock()
if err == nil || !isTransientErr(err) {
r.initErr[dim] = err // nil on success, persist permanent failures
}
r.initMu.Unlock()
})
r.initMu.Lock()
err := r.initErr[dim]
r.initMu.Unlock()
return err
}
// indexAlias returns the alias name for a given dimension. All reads /
// writes target the alias; the alias points at the actual <alias>_v1
// index, enabling future rolling-reindex swap workflows (the swap path
// itself is deferred to a follow-up PR; see stubs.go swapToVersion).
func (r *Repository) indexAlias(dim int) string {
return fmt.Sprintf("%s_%d", r.baseIndex, dim)
}
// keywordsIndex returns the name of the dim-less keyword-only index used
// by the no-embedding save path (the service layer dispatches there when
// the knowledge base has vector indexing disabled). The mapping is the
// same as the per-dim index minus the knn_vector field.
func (r *Repository) keywordsIndex() string {
return r.baseIndex + "_keywords"
}
// EngineType returns the engine constant for OpenSearch. Used by the
// fan-out normalizer to route to the [0, 1] passthrough group.
func (r *Repository) EngineType() types.RetrieverEngineType {
return types.OpenSearchRetrieverEngineType
}
// Support reports the retrieval modes this driver implements. OpenSearch
// k-NN supports both ANN (vector) and BM25 (keyword) within a single
// document; the keyword-only index keeps BM25 functional for callers
// that omit the embedding map.
func (r *Repository) Support() []types.RetrieverType {
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
}
// probeVersion sends GET / and validates the cluster is OpenSearch in
// a supported version range:
// - Reject: ES (any), OS 1.x, OS 2.0~2.3 (Lucene HNSW preview).
// - Warn-but-accept: OS 2.4~2.10 (Lucene HNSW GA, pre-LTS).
// - Clean-accept: OS 2.11+, OS 3.x (primary tested: 3.3.2).
func probeVersion(ctx context.Context, client *osapi.Client) error {
resp, err := client.Info(ctx, nil)
if err != nil {
return fmt.Errorf("opensearch: cluster info: %w", wrapTransport(err))
}
distribution := resp.Version.Distribution
number := resp.Version.Number
if distribution != "opensearch" {
return fmt.Errorf("opensearch: unsupported distribution %q: %w",
distribution, ErrVersionUnsupported)
}
maj, min := parseMajorMinor(number)
switch {
case maj == 1:
return fmt.Errorf("opensearch: 1.x EOL: %w", ErrVersionUnsupported)
case maj == 2 && min >= 0 && min <= 3:
return fmt.Errorf("opensearch: %s lacks Lucene HNSW GA (need 2.4+): %w",
number, ErrVersionUnsupported)
case maj == 2 && min >= 4 && min <= 10:
logger.GetLogger(ctx).Warnf(
"[OpenSearch] using pre-2.11 cluster %s; recommend 2.11+ LTS", number)
return nil
case maj == 2 || maj == 3:
return nil
default:
return fmt.Errorf("opensearch: unsupported version %s: %w",
number, ErrVersionUnsupported)
}
}
// parseMajorMinor extracts (major, minor) from a semver string such as
// "3.3.2", "2.10.0-SNAPSHOT", "2.10". Returns (0, 0) for unparseable
// input. Robust to pre-release suffixes (strips after '-') and missing
// patch component (e.g. "2.10").
func parseMajorMinor(num string) (major, minor int) {
base := strings.SplitN(num, "-", 2)[0]
parts := strings.Split(base, ".")
if len(parts) < 2 {
return 0, 0
}
m1, err1 := strconv.Atoi(parts[0])
m2, err2 := strconv.Atoi(parts[1])
if err1 != nil || err2 != nil {
return 0, 0
}
return m1, m2
}
// probeKNNPlugin verifies the OpenSearch cluster has the opensearch-knn
// plugin installed on EVERY node. Without it on at least one node,
// knn_vector queries that route a shard to that node fail with opaque
// shard-failure errors — we surface this as a clear "plugin missing on
// N nodes" message at registration.
//
// Implementation: _cat/plugins returns one row per (node, plugin) pair.
// We group by node name and verify every distinct node has the
// opensearch-knn component.
func probeKNNPlugin(ctx context.Context, client *osapi.Client) error {
// CatPluginsReq's Params struct has no Format field — the SDK
// negotiates JSON via Accept header and returns a typed
// CatPluginsResp with .Plugins []CatPluginResp already parsed.
resp, err := client.Cat.Plugins(ctx, &osapi.CatPluginsReq{})
if err != nil {
return fmt.Errorf("opensearch: cat plugins: %w", wrapTransport(err))
}
// Group by node, verify every distinct node has opensearch-knn.
nodes := make(map[string]bool) // nodeName -> hasKNN
for _, p := range resp.Plugins {
if p.Name == "" {
continue
}
if _, seen := nodes[p.Name]; !seen {
nodes[p.Name] = false
}
if p.Component == "opensearch-knn" {
nodes[p.Name] = true
}
}
if len(nodes) == 0 {
return fmt.Errorf("opensearch: _cat/plugins returned no rows: %w", ErrConfigInvalid)
}
var missing []string
for node, hasKNN := range nodes {
if !hasKNN {
missing = append(missing, node)
}
}
if len(missing) > 0 {
return fmt.Errorf(
"opensearch: opensearch-knn plugin missing on %d/%d nodes (%v): %w",
len(missing), len(nodes), missing, ErrConfigInvalid,
)
}
return nil
}
// wrapTransport classifies a raw transport error into one of the
// driver's sentinel errors based on HTTP status ONLY. The cluster-side
// error message (err.Error()) is intentionally NOT included in the
// wrapped public error — it may contain internal index names, shard
// IDs, node hostnames, or document content snippets. The full SDK
// error is routed to log.Debug for operator forensics.
//
// Classification:
// - 401 / 403 → ErrAuth
// - 404 → caller decides (use isNotFound separately for index ops)
// - 429 + knn_circuit_breaker_exception → ErrCircuitBreaker
// - 5xx / network / timeout → ErrTransport
//
// This is the ONE place in the package that maps wire errors to
// sentinels; downstream functions just propagate.
func wrapTransport(err error) error {
if err == nil {
return nil
}
// Route the verbose SDK message to debug log (operator-visible, not
// user-visible). Background ctx is intentional — wrapTransport may
// be invoked from any caller including the constructor.
logger.GetLogger(context.Background()).Debugf("[OpenSearch] transport err: %v", err)
var se *opensearch.StructError
if errors.As(err, &se) {
switch se.Status {
case http.StatusUnauthorized, http.StatusForbidden:
return fmt.Errorf("authentication failed: %w", ErrAuth)
case http.StatusTooManyRequests:
if se.Err.Type == "knn_circuit_breaker_exception" {
return fmt.Errorf("circuit breaker open: %w", ErrCircuitBreaker)
}
}
}
return fmt.Errorf("transport error: %w", ErrTransport)
}
// isNotFound returns true if err carries an HTTP 404. Used by index /
// search code paths that want to distinguish "missing alias" from
// "transport problem".
func isNotFound(err error) bool {
var se *opensearch.StructError
return errors.As(err, &se) && se.Status == http.StatusNotFound
}
// isAlreadyExistsError returns true if err is a 400 with OpenSearch's
// resource_already_exists_exception type. Used by createIndexAndAlias
// to handle the cross-process race where two replicas try to create
// the same per-dim index simultaneously.
func isAlreadyExistsError(err error) bool {
if err == nil {
return false
}
var se *opensearch.StructError
if !errors.As(err, &se) {
return false
}
return se.Status == http.StatusBadRequest &&
se.Err.Type == "resource_already_exists_exception"
}
// sanitizeRe enforces the OpenSearch index-name contract:
// - lowercase ASCII letters, digits, underscore, hyphen only
// - must start with [a-z0-9]
// - length 1..255
var sanitizeRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,254}$`)
// sanitizeIndexName rejects names that violate the OpenSearch index-name
// rules. Any non-conforming input returns ErrConfigInvalid — the driver
// does NOT silently rewrite invalid input so operators get a clear
// error at registration.
func sanitizeIndexName(name string) (string, error) {
if name == "" {
return "", fmt.Errorf("empty index name: %w", ErrConfigInvalid)
}
// Explicit reject of OpenSearch-reserved wildcards / separators /
// control characters. Some of these would already be caught by the
// regexp below, but a dedicated check keeps the error message
// specific.
if strings.ContainsAny(name, "*?,\n\r\t/\\") {
return "", fmt.Errorf("invalid char in %q: %w", name, ErrConfigInvalid)
}
if !sanitizeRe.MatchString(name) {
return "", fmt.Errorf("name %q must match %s: %w",
name, sanitizeRe.String(), ErrConfigInvalid)
}
return name, nil
}
// drainAndClose closes the response body after draining unread bytes —
// required for HTTP keep-alive connection reuse. opensearch-go does NOT
// drain the body for us; failing to drain on every response will starve
// the per-host connection pool under load.
func drainAndClose(body io.ReadCloser) {
if body == nil {
return
}
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}
// limitedDecode wraps json.NewDecoder with an io.LimitReader so a
// pathological or malicious cluster response cannot exhaust process
// memory. Callers pass the documented per-endpoint cap (e.g. 64MB for
// bulk, 16MB for search, 1MB for plugin probe).
func limitedDecode(body io.Reader, maxBytes int64, v any) error {
return json.NewDecoder(io.LimitReader(body, maxBytes)).Decode(v)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,209 @@
package opensearch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"academy/internal/logger"
"academy/internal/types"
)
// Retrieve dispatches to vectorRetrieve or keywordsRetrieve based on
// params.RetrieverType. Returns exactly one *RetrieveResult — the
// service-layer multi-store dispatcher depends on this one-bundle-per-
// driver protocol. Score in result is RAW [0, 1] passthrough (the
// OpenSearch k-NN plugin's SpaceType.COSINESIMIL.scoreTranslation has
// already mapped to (1 + cos) / 2 before the score reaches us).
//
// Dim resolution order:
// 1. params.AdditionalParams["dim"] if present and positive
// 2. len(params.Embedding) if positive
// 3. cross-dim multi-index search for keyword-only paths via
// "<base>_*" wildcard pattern
//
// Vector retrieve always requires a positive dim (it's intrinsic to k-NN).
func (r *Repository) Retrieve(
ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
dim, multiIndex := resolveDim(params)
switch params.RetrieverType {
case types.VectorRetrieverType:
if dim == 0 {
return nil, fmt.Errorf(
"opensearch: vector retrieve requires embedding or AdditionalParams[\"dim\"]: %w",
ErrDimensionMismatch)
}
if err := r.ensureReady(ctx, dim); err != nil {
return nil, err
}
return r.vectorRetrieve(ctx, params, dim)
case types.KeywordsRetrieverType:
if multiIndex {
// BM25-only path without dim — search across "<base>_*"
// wildcard pattern. Slower than a single-index search but
// correct for admin / keyword-only callers.
return r.keywordsRetrieve(ctx, params, r.baseIndex+"_*")
}
if err := r.ensureReady(ctx, dim); err != nil {
return nil, err
}
return r.keywordsRetrieve(ctx, params, r.indexAlias(dim))
default:
return nil, fmt.Errorf("opensearch: unsupported retriever type %q", params.RetrieverType)
}
}
// resolveDim returns (dim, multiIndex). multiIndex=true means dim is
// unknown and the caller should use a wildcard alias pattern (keyword
// path only — vector retrieve cannot be dim-less).
func resolveDim(p types.RetrieveParams) (int, bool) {
if p.AdditionalParams != nil {
if v, ok := p.AdditionalParams["dim"].(int); ok && v > 0 {
return v, false
}
}
if len(p.Embedding) > 0 {
return len(p.Embedding), false
}
return 0, true // unknown — multi-index fallback for keyword
}
func (r *Repository) vectorRetrieve(
ctx context.Context, p types.RetrieveParams, dim int,
) ([]*types.RetrieveResult, error) {
body, err := buildKNNQuery(p.Embedding, effectiveTopK(ctx, p), p.Threshold, fromParams(p))
if err != nil {
return nil, err
}
hits, err := r.search(ctx, r.indexAlias(dim), body)
if err != nil {
return nil, err
}
return wrapResults(ctx, hits, types.VectorRetrieverType, types.MatchTypeEmbedding), nil
}
func (r *Repository) keywordsRetrieve(
ctx context.Context, p types.RetrieveParams, indexPattern string,
) ([]*types.RetrieveResult, error) {
body, err := buildKeywordQuery(p.Query, effectiveTopK(ctx, p), p.Threshold, fromParams(p))
if err != nil {
return nil, err
}
hits, err := r.search(ctx, indexPattern, body)
if err != nil {
return nil, err
}
return wrapResults(ctx, hits, types.KeywordsRetrieverType, types.MatchTypeKeywords), nil
}
// effectiveTopK returns the caller's TopK or 10 if unset. The 10 is a
// defensive default — every real caller sets TopK, so a TopK=10 in
// production logs indicates a caller bug. Caps at 10000 to stay below
// OpenSearch's index.max_result_window default.
func effectiveTopK(ctx context.Context, p types.RetrieveParams) int {
if p.TopK <= 0 {
logger.GetLogger(ctx).Warnf("[OpenSearch] Retrieve called with TopK<=0; defaulting to 10 (caller bug?)")
return 10
}
if p.TopK > 10000 {
return 10000
}
return p.TopK
}
func (r *Repository) search(ctx context.Context, indexPattern string, body []byte) ([]hit, error) {
req := osapi.SearchReq{Indices: []string{indexPattern}, Body: bytes.NewReader(body)}
resp, err := r.client.Search(ctx, &req)
if err != nil {
if isNotFound(err) {
return nil, fmt.Errorf("opensearch: index %s missing: %w", indexPattern, ErrIndexNotFound)
}
return nil, wrapTransport(err)
}
defer func() {
if resp != nil {
drainAndClose(resp.Inspect().Response.Body)
}
}()
// Cap response body at 16MB (search results bounded by max_result_window * doc_size).
return parseSearchHits(io.LimitReader(resp.Inspect().Response.Body, 16<<20))
}
// hit is the structural shape we pull from each OpenSearch search hit.
// Field-by-field decode (vs map[string]any) keeps the JSON shape
// pinned at compile time.
type hit struct {
ID string `json:"_id"` // equals chunk_id per the indexing invariant
Score float64 `json:"_score"`
Source struct {
Content string `json:"content"`
ChunkID string `json:"chunk_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
SourceID string `json:"source_id"`
SourceType int `json:"source_type"` // integer, not stringified
TagID string `json:"tag_id"`
IsEnabled bool `json:"is_enabled"`
} `json:"_source"`
}
func parseSearchHits(body io.Reader) ([]hit, error) {
var resp struct {
Hits struct {
Hits []hit `json:"hits"`
} `json:"hits"`
}
if err := json.NewDecoder(body).Decode(&resp); err != nil {
return nil, fmt.Errorf("opensearch: parse search response: %w", ErrTransport)
}
return resp.Hits.Hits, nil
}
// wrapResults converts OpenSearch hits to the upstream IndexWithScore
// shape. Always returns exactly one *RetrieveResult — the service-layer
// multi-store dispatcher depends on this "one engine result per driver"
// contract.
//
// Defensive: warns if hit._id != _source.chunk_id (we set _id=chunk_id
// on every write, so a mismatch means external tooling has been writing
// into the index) but does not fail the query — the result is still
// usable for ranking, just suspicious.
func wrapResults(ctx context.Context, hits []hit, rt types.RetrieverType, mt types.MatchType) []*types.RetrieveResult {
log := logger.GetLogger(ctx)
out := make([]*types.IndexWithScore, 0, len(hits))
for _, h := range hits {
score := h.Score
if rt == types.VectorRetrieverType {
score = knnScoreToCosine(score)
}
if h.ID != h.Source.ChunkID {
log.Warnf("[OpenSearch] hit._id=%q != _source.chunk_id=%q (D12 invariant violation)",
h.ID, h.Source.ChunkID)
}
out = append(out, &types.IndexWithScore{
ID: h.ID,
ChunkID: h.Source.ChunkID,
KnowledgeID: h.Source.KnowledgeID,
KnowledgeBaseID: h.Source.KnowledgeBaseID,
SourceID: h.Source.SourceID,
SourceType: types.SourceType(h.Source.SourceType),
TagID: h.Source.TagID,
Content: h.Source.Content,
Score: score,
MatchType: mt,
IsEnabled: h.Source.IsEnabled,
})
}
return []*types.RetrieveResult{{
Results: out,
RetrieverEngineType: types.OpenSearchRetrieverEngineType,
RetrieverType: rt,
}}
}
@@ -0,0 +1,25 @@
package opensearch
import (
"context"
"testing"
"academy/internal/types"
)
// The k-NN plugin reports (1 + cos) / 2; vector hits leave the driver as
// cosine similarity, keyword hits keep their BM25 score.
func TestWrapResultsReportsCosineForVectorHits(t *testing.T) {
t.Parallel()
hits := []hit{{ID: "c1", Score: 0.9}}
hits[0].Source.ChunkID = "c1"
vector := wrapResults(context.Background(), hits, types.VectorRetrieverType, types.MatchTypeEmbedding)
if got := vector[0].Results[0].Score; got < 0.8-1e-9 || got > 0.8+1e-9 {
t.Fatalf("vector score = %v, want cosine 0.8", got)
}
keyword := wrapResults(context.Background(), hits, types.KeywordsRetrieverType, types.MatchTypeKeywords)
if got := keyword[0].Results[0].Score; got != 0.9 {
t.Fatalf("keyword score = %v, want 0.9 unchanged", got)
}
}
@@ -0,0 +1,16 @@
package opensearch
import (
"os"
"testing"
secutils "academy/internal/utils"
)
func TestMain(m *testing.M) {
// End-to-end repository tests intentionally use loopback httptest servers.
secutils.SetSSRFWhitelistFromRaw("127.0.0.1,::1,localhost,opensearch.example.com")
code := m.Run()
secutils.SetSSRFWhitelistFromRaw("")
os.Exit(code)
}
@@ -0,0 +1,52 @@
package opensearch
import (
"context"
"academy/internal/types"
)
// This file holds the remaining stubs for methods whose real implementation
// has not landed yet — the rolling-reindex swap (swapToVersion) and the
// precise storage estimate. CopyIndices (copy.go), BatchUpdateChunkEnabledStatus
// and BatchUpdateChunkTagID (bulk_update.go) are now implemented. Each
// remaining stub returns ErrFeatureNotEnabled (or, for EstimateStorageSize, a
// conservative lower-bound) so any accidental invocation surfaces loudly.
// EstimateStorageSize: the real implementation that reads cluster
// `_stats` for the per-dim alias arrives in a later change. For now we
// return a conservative lower-bound estimate using the HNSW memory
// formula so the upstream KB-delete guard fails-closed (treats non-empty
// KBs as "may free non-trivial storage, force confirmation") rather than
// failing open.
//
// Formula: N * (1024 content bytes + 4*dimGuess float + 128 HNSW M=16 overhead)
// dimGuess = 768 (common embedding size; the real implementation reads
// the actual dim from the cluster).
func (r *Repository) EstimateStorageSize(
_ context.Context,
indexInfoList []*types.IndexInfo,
_ map[string]any,
) int64 {
if len(indexInfoList) == 0 {
return 0
}
const (
contentBytes = 1024 // average chunk content
embDimGuess = 768 // common embedding size
hnswOverhead = 128 // M=16 → 8*M = 128 bytes/vector
)
return int64(len(indexInfoList)) * int64(contentBytes+4*embDimGuess+hnswOverhead)
}
// swapToVersion is a stub for the future rolling-reindex swap path.
// Calling it is illegal at this stage — alias is fixed at "_v1" and only
// a follow-up change ships the swap orchestration. The surface exists so
// the future API contract is reviewable now.
//
// Unexported because it is not part of the public
// RetrieveEngineRepository interface — exposing it would require an
// interface widening in internal/types/interfaces.
func (r *Repository) swapToVersion(_ context.Context, _ int, _ int) error {
return ErrFeatureNotEnabled
}
@@ -0,0 +1,80 @@
package opensearch
import (
"crypto/tls"
"fmt"
"net/http"
"time"
"github.com/opensearch-project/opensearch-go/v4"
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"academy/internal/types"
secutils "academy/internal/utils"
)
// NewOpenSearchClient builds a TLS-hardened, pool-tuned *osapi.Client for
// the OpenSearch driver. The caller wires it into the registry from the
// env path (container) and the DB-store path (engine factory); the
// Repository constructor itself receives the pre-built client.
//
// TLS posture:
// - MinVersion: TLS 1.2 (TLS 1.3 negotiated when both ends support).
// - InsecureSkipVerify: opt-in via ConnectionConfig.InsecureSkipVerify.
// Default false. Operators set true ONLY for self-signed dev clusters.
// - CipherSuites: explicit forward-secrecy-only list. TLS 1.2's default
// cipher list includes TLS_RSA_* (no forward secrecy); we drop them.
// TLS 1.3 cipher selection is automatic and safe.
//
// Transport tuning:
// - MaxIdleConnsPerHost: 32 (Go default 2 is too low when callers
// dispatch concurrent queries across multiple knowledge bases)
// - IdleConnTimeout: 90s (typical LB keep-alive)
// - ResponseHeaderTimeout: 30s (per-request safety net)
// - ExpectContinueTimeout: 1s
func NewOpenSearchClient(cfg *types.ConnectionConfig) (*osapi.Client, error) {
if cfg == nil || cfg.Addr == "" {
return nil, fmt.Errorf("opensearch: ConnectionConfig.Addr required: %w", ErrConfigInvalid)
}
if err := secutils.ValidateURLForSSRF(cfg.Addr); err != nil {
return nil, fmt.Errorf("opensearch: address failed SSRF validation: %w", err)
}
transport := buildHTTPTransport(cfg.InsecureSkipVerify)
return osapi.NewClient(osapi.Config{
Client: opensearch.Config{
Addresses: []string{cfg.Addr},
Username: cfg.Username,
Password: cfg.Password,
Transport: &secutils.SSRFValidatingRoundTripper{Base: transport},
},
})
}
// buildHTTPTransport constructs the TLS-hardened, pool-tuned
// *http.Transport used by every OpenSearch client this driver creates.
// Extracted from newOpenSearchClient so unit tests can pin the TLS
// posture directly (the opensearch-go SDK wraps the transport in an
// internal interface, making reflection-based introspection of the
// final client fragile across SDK versions).
func buildHTTPTransport(insecureSkipVerify bool) *http.Transport {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: secutils.SSRFSafeDialContext,
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: insecureSkipVerify, //nolint:gosec — operator opt-in flag
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
},
},
MaxIdleConnsPerHost: 32,
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
}
@@ -0,0 +1,137 @@
package opensearch
import (
"crypto/tls"
"errors"
"testing"
"academy/internal/types"
)
// TestNewOpenSearchClient_RejectsEmptyAddr verifies the constructor
// refuses an empty Addr — operators who forget to set OPENSEARCH_ADDR
// get a clear ErrConfigInvalid at registration instead of a cryptic
// transport error later.
func TestNewOpenSearchClient_RejectsEmptyAddr(t *testing.T) {
t.Parallel()
_, err := NewOpenSearchClient(&types.ConnectionConfig{Addr: ""})
if !errors.Is(err, ErrConfigInvalid) {
t.Fatalf("empty addr: want ErrConfigInvalid, got %v", err)
}
_, err = NewOpenSearchClient(nil)
if !errors.Is(err, ErrConfigInvalid) {
t.Fatalf("nil cfg: want ErrConfigInvalid, got %v", err)
}
}
// TestNewOpenSearchClient_Succeeds_OnValidAddr is a smoke test for the
// happy path — a non-empty Addr must produce a non-nil *osapi.Client.
// We don't probe the cluster (no network), just verify the constructor
// returns successfully.
func TestNewOpenSearchClient_Succeeds_OnValidAddr(t *testing.T) {
t.Parallel()
client, err := NewOpenSearchClient(&types.ConnectionConfig{
Addr: "https://opensearch.example.com:9200",
Username: "admin",
Password: "secret", // not a real password — wire-format only
})
if err != nil {
t.Fatalf("NewOpenSearchClient: %v", err)
}
if client == nil {
t.Fatal("client must be non-nil on success")
}
}
// TestBuildHTTPTransport_DefaultsToSecureTLS pins the default
// InsecureSkipVerify=false. Operators who don't opt in MUST get a
// strict-verify HTTPS client.
func TestBuildHTTPTransport_DefaultsToSecureTLS(t *testing.T) {
t.Parallel()
tr := buildHTTPTransport(false)
if tr.TLSClientConfig == nil {
t.Fatal("TLSClientConfig must be set")
}
if tr.TLSClientConfig.InsecureSkipVerify {
t.Fatal("default InsecureSkipVerify must be false (secure)")
}
}
// TestBuildHTTPTransport_InsecureSkipVerifyOptIn confirms the flag
// flows through to tls.Config. Self-signed dev clusters can opt in;
// production deployments MUST leave it false.
func TestBuildHTTPTransport_InsecureSkipVerifyOptIn(t *testing.T) {
t.Parallel()
tr := buildHTTPTransport(true)
if tr.TLSClientConfig == nil {
t.Fatal("TLSClientConfig must be set")
}
if !tr.TLSClientConfig.InsecureSkipVerify {
t.Fatal("InsecureSkipVerify=true must propagate to tls.Config")
}
}
// TestBuildHTTPTransport_TLS12MinVersion pins the TLS 1.2 hard floor.
// TLS 1.3 negotiates automatically when both ends support it; 1.0 / 1.1
// must be rejected at handshake time.
func TestBuildHTTPTransport_TLS12MinVersion(t *testing.T) {
t.Parallel()
tr := buildHTTPTransport(false)
if tr.TLSClientConfig.MinVersion != tls.VersionTLS12 {
t.Fatalf("MinVersion: want tls.VersionTLS12 (0x%x), got 0x%x",
tls.VersionTLS12, tr.TLSClientConfig.MinVersion)
}
}
// TestBuildHTTPTransport_CipherSuitesExcludeNonECDHE pins the explicit
// cipher list to forward-secrecy-only ECDHE suites. TLS 1.2's default
// list includes TLS_RSA_* (no forward secrecy); we drop them. TLS 1.3
// cipher selection is automatic so this only matters for the 1.2 path.
func TestBuildHTTPTransport_CipherSuitesExcludeNonECDHE(t *testing.T) {
t.Parallel()
tr := buildHTTPTransport(false)
cs := tr.TLSClientConfig.CipherSuites
if len(cs) == 0 {
t.Fatal("CipherSuites must be explicitly pinned (got empty)")
}
allowed := map[uint16]bool{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: true,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: true,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: true,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: true,
}
for _, suite := range cs {
if !allowed[suite] {
t.Fatalf("cipher suite 0x%x is not in the forward-secrecy whitelist", suite)
}
}
// Spot-check that a known-weak non-ECDHE cipher is NOT in the list.
for _, suite := range cs {
if suite == tls.TLS_RSA_WITH_AES_128_GCM_SHA256 {
t.Fatal("TLS_RSA_WITH_AES_128_GCM_SHA256 must NOT be present (no forward secrecy)")
}
}
}
// TestBuildHTTPTransport_PoolTuning pins the connection-pool settings.
// The Go default MaxIdleConnsPerHost is 2, which is too low for concurrent
// queries across multiple knowledge bases.
func TestBuildHTTPTransport_PoolTuning(t *testing.T) {
t.Parallel()
tr := buildHTTPTransport(false)
if tr.MaxIdleConnsPerHost < 32 {
t.Errorf("MaxIdleConnsPerHost: want >=32 for concurrent KB queries, got %d",
tr.MaxIdleConnsPerHost)
}
if tr.IdleConnTimeout == 0 {
t.Error("IdleConnTimeout must be set (Go default of 0 leaks idle conns)")
}
if tr.ResponseHeaderTimeout == 0 {
t.Error("ResponseHeaderTimeout must be set (Go default of 0 means unbounded)")
}
if tr.ExpectContinueTimeout == 0 {
t.Error("ExpectContinueTimeout must be set (avoids 100-continue stalls)")
}
}
@@ -0,0 +1,104 @@
package postgres
import (
"context"
"os"
"testing"
"github.com/stretchr/testify/require"
gormpostgres "gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// TestKeywordScoreCatalogCompatibility checks the actual PostgreSQL catalog
// query, including preference and signatures, rather than mocking its result.
// Set ACADEMY_RETRIEVER_TEST_POSTGRES_DSN to a disposable PostgreSQL database
// without pg_search installed. Fixtures are rolled back after each subtest;
// existing scoring schemas are never replaced or dropped.
func TestKeywordScoreCatalogCompatibility(t *testing.T) {
dsn := os.Getenv("ACADEMY_RETRIEVER_TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("set ACADEMY_RETRIEVER_TEST_POSTGRES_DSN to run PostgreSQL catalog tests")
}
db, err := gorm.Open(gormpostgres.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { _ = sqlDB.Close() })
var existing int
require.NoError(t, db.Raw(`SELECT count(*) FROM pg_catalog.pg_namespace
WHERE nspname IN ('paradedb', 'pgsearch', 'unrelated_score_test')`).Scan(&existing).Error)
require.Zero(t, existing, "use a disposable database without existing scoring schemas")
paradedb := "CREATE FUNCTION paradedb.score(anyelement) RETURNS real LANGUAGE sql AS 'SELECT 1::real'"
pgsearch := "CREATE FUNCTION pgsearch.score(anyelement) RETURNS real LANGUAGE sql AS 'SELECT 1::real'"
for _, tc := range []struct {
name string
functions []string
want string
}{
{name: "ParadeDB", functions: []string{paradedb}, want: "paradedb.score"},
{name: "PolarDB_layout", functions: []string{pgsearch}, want: "pgsearch.score"},
{name: "prefer_ParadeDB", functions: []string{pgsearch, paradedb}, want: "paradedb.score"},
{name: "missing_functions"},
{
name: "incompatible_argument_falls_back",
functions: []string{
"CREATE FUNCTION paradedb.score(integer) RETURNS real LANGUAGE sql AS 'SELECT 1::real'",
pgsearch,
},
want: "pgsearch.score",
},
{
name: "incompatible_result_falls_back",
functions: []string{
"CREATE FUNCTION paradedb.score(anyelement) RETURNS double precision LANGUAGE sql AS 'SELECT 1::real'",
pgsearch,
},
want: "pgsearch.score",
},
{
name: "reject_wrong_arity",
functions: []string{
"CREATE FUNCTION pgsearch.score(anyelement, integer) RETURNS real LANGUAGE sql AS 'SELECT 1::real'",
},
},
{
name: "reject_unlisted_schema",
functions: []string{
"CREATE FUNCTION unrelated_score_test.score(anyelement) RETURNS real LANGUAGE sql AS 'SELECT 1::real'",
},
},
{
name: "reject_wrong_result",
functions: []string{
"CREATE FUNCTION pgsearch.score(anyelement) RETURNS double precision LANGUAGE sql AS 'SELECT 1::real'",
},
},
} {
t.Run(tc.name, func(t *testing.T) {
tx := db.Begin()
require.NoError(t, tx.Error)
t.Cleanup(func() { require.NoError(t, tx.Rollback().Error) })
for _, schema := range []string{"paradedb", "pgsearch", "unrelated_score_test"} {
require.NoError(t, tx.Exec("CREATE SCHEMA "+schema).Error)
}
for _, ddl := range tc.functions {
require.NoError(t, tx.Exec(ddl).Error)
}
repo := &pgRepository{db: tx}
function, err := repo.resolveKeywordScoreFunction(context.Background())
if tc.want == "" {
require.ErrorContains(t, err, "check pg_search extension compatibility")
require.Empty(t, function)
return
}
require.NoError(t, err)
require.Equal(t, tc.want, function)
})
}
}
@@ -0,0 +1,193 @@
package postgres
import (
"context"
"errors"
"regexp"
"sync"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"academy/internal/types"
"github.com/stretchr/testify/require"
gormpostgres "gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func newKeywordTestRepository(t *testing.T) (*pgRepository, sqlmock.Sqlmock) {
t.Helper()
db, mock, err := sqlmock.New()
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, mock.ExpectationsWereMet()); _ = db.Close() })
gdb, err := gorm.Open(gormpostgres.New(gormpostgres.Config{Conn: db}), &gorm.Config{
DisableAutomaticPing: true,
Logger: logger.Default.LogMode(logger.Silent),
})
require.NoError(t, err)
return NewPostgresRetrieveEngineRepository(gdb).(*pgRepository), mock
}
// Exercise the actual query path for both backends, including scope filters,
// bound query text, score mapping, and reuse of the per-connection detection.
func TestKeywordsRetrieveScoreFunctionCompatibility(t *testing.T) {
for _, scoreFunction := range []string{"paradedb.score", "pgsearch.score"} {
t.Run(scoreFunction, func(t *testing.T) {
repo, mock := newKeywordTestRepository(t)
mock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL)).
WillReturnRows(sqlmock.NewRows([]string{"score_function"}).AddRow(scoreFunction))
params := types.RetrieveParams{
RetrieverType: types.KeywordsRetrieverType,
Query: "关键词测试 ' OR 1=1 --", TopK: 5,
KnowledgeBaseIDs: []string{"kb-test"}, KnowledgeIDs: []string{"doc-test"},
TagIDs: []string{"tag-test"},
}
query := `SELECT ` + regexp.QuoteMeta(scoreFunction) + `\(id\) as score,.*` +
`FROM "embeddings" WHERE "knowledge_base_id" = \$1.*` +
`"knowledge_id" = \$2.*"tag_id" = \$3.*` +
`content \|\|\| \$4.*is_enabled IS NULL OR is_enabled = \$5.*` +
`ORDER BY "score" DESC LIMIT \$6`
for range 2 {
mock.ExpectQuery(query).
WithArgs("kb-test", "doc-test", "tag-test", params.Query, true, 5).
WillReturnRows(sqlmock.NewRows([]string{
"id", "chunk_id", "knowledge_id", "knowledge_base_id", "tag_id", "score",
}).
AddRow(1, "chunk-test", "doc-test", "kb-test", "tag-test", 31.15))
results, err := repo.Retrieve(context.Background(), params)
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 1)
require.Equal(t, "chunk-test", results[0].Results[0].ChunkID)
require.Equal(t, 31.15, results[0].Results[0].Score)
require.Equal(t, types.MatchTypeKeywords, results[0].Results[0].MatchType)
}
})
}
}
func TestKeywordScoreDetectionFailuresDoNotPoisonCache(t *testing.T) {
for _, kind := range []string{"missing", "unexpected", "database_error"} {
t.Run(kind, func(t *testing.T) {
repo, mock := newKeywordTestRepository(t)
probe := mock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL))
cause := errors.New("catalog unavailable")
switch kind {
case "missing":
probe.WillReturnRows(sqlmock.NewRows([]string{"score_function"}))
case "unexpected":
probe.WillReturnRows(sqlmock.NewRows([]string{"score_function"}).AddRow("untrusted.score"))
default:
probe.WillReturnError(cause)
}
results, err := repo.KeywordsRetrieve(context.Background(), types.RetrieveParams{Query: "关键词测试", TopK: 5})
require.Nil(t, results)
if kind == "database_error" {
require.ErrorIs(t, err, cause)
} else {
require.ErrorContains(t, err, "check pg_search extension compatibility")
}
mock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL)).
WillReturnRows(sqlmock.NewRows([]string{"score_function"}).AddRow("pgsearch.score"))
function, err := repo.resolveKeywordScoreFunction(context.Background())
require.NoError(t, err)
require.Equal(t, "pgsearch.score", function)
})
}
}
func TestKeywordScoreDetectionConcurrentAndPerRepository(t *testing.T) {
repo, mock := newKeywordTestRepository(t)
mock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL)).
WillReturnRows(sqlmock.NewRows([]string{"score_function"}).AddRow("paradedb.score"))
var wg sync.WaitGroup
for range 16 {
wg.Go(func() {
function, err := repo.resolveKeywordScoreFunction(context.Background())
if err != nil || function != "paradedb.score" {
t.Errorf("resolve score function = %q, %v", function, err)
}
})
}
wg.Wait()
other, otherMock := newKeywordTestRepository(t)
otherMock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL)).
WillReturnRows(sqlmock.NewRows([]string{"score_function"}).AddRow("pgsearch.score"))
function, err := other.resolveKeywordScoreFunction(context.Background())
require.NoError(t, err)
require.Equal(t, "pgsearch.score", function)
}
func TestKeywordScoreDetectionCanceledContextCanRetry(t *testing.T) {
repo, mock := newKeywordTestRepository(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
// A canceled caller must not cache a failed detection or block later calls.
_, err := repo.resolveKeywordScoreFunction(ctx)
require.ErrorIs(t, err, context.Canceled)
mock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL)).
WillReturnRows(sqlmock.NewRows([]string{"score_function"}).AddRow("paradedb.score"))
function, err := repo.resolveKeywordScoreFunction(context.Background())
require.NoError(t, err)
require.Equal(t, "paradedb.score", function)
}
func TestKeywordsRetrieveQueryFailurePreservesResolvedFunction(t *testing.T) {
repo, mock := newKeywordTestRepository(t)
mock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL)).
WillReturnRows(sqlmock.NewRows([]string{"score_function"}).AddRow("pgsearch.score"))
query := `SELECT pgsearch\.score\(id\) as score,.*FROM "embeddings".*`
cause := errors.New("keyword index unavailable")
mock.ExpectQuery(query).WithArgs("关键词测试", true, 5).WillReturnError(cause)
params := types.RetrieveParams{Query: "关键词测试", TopK: 5}
results, err := repo.KeywordsRetrieve(context.Background(), params)
require.Nil(t, results)
require.ErrorIs(t, err, cause)
// The catalog probe succeeded: retry only the retrieval, not detection.
mock.ExpectQuery(query).WithArgs("关键词测试", true, 5).
WillReturnRows(sqlmock.NewRows([]string{"id", "score"}))
results, err = repo.KeywordsRetrieve(context.Background(), params)
require.NoError(t, err)
require.Len(t, results, 1)
require.Empty(t, results[0].Results)
}
func TestVectorRetrieveDoesNotRequireKeywordScoreFunction(t *testing.T) {
for _, keywordFailed := range []bool{false, true} {
name := "without_keyword_probe"
if keywordFailed {
name = "after_unsupported_keyword_probe"
}
t.Run(name, func(t *testing.T) {
repo, mock := newKeywordTestRepository(t)
if keywordFailed {
mock.ExpectQuery(regexp.QuoteMeta(keywordScoreFunctionSQL)).
WillReturnRows(sqlmock.NewRows([]string{"score_function"}))
_, err := repo.KeywordsRetrieve(context.Background(), types.RetrieveParams{Query: "关键词测试", TopK: 5})
require.Error(t, err)
}
// Expect only vector SQL: any score-function probe fails this test.
mock.ExpectBegin()
mock.ExpectExec("SET LOCAL hnsw.ef_search = 100").WillReturnResult(sqlmock.NewResult(0, 0))
mock.ExpectExec("SET LOCAL hnsw.iterative_scan = strict_order").WillReturnResult(sqlmock.NewResult(0, 0))
mock.ExpectQuery(`SELECT .*FROM embeddings.*`).
WithArgs(sqlmock.AnyArg(), 2, true, 100, 0.5, 3).
WillReturnRows(sqlmock.NewRows([]string{"id", "chunk_id", "score"}).AddRow(1, "vector-chunk", 0.9))
mock.ExpectCommit()
results, err := repo.Retrieve(context.Background(), types.RetrieveParams{
RetrieverType: types.VectorRetrieverType,
Embedding: []float32{0.1, 0.2},
Threshold: 0.5,
TopK: 3,
})
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 1)
require.Equal(t, "vector-chunk", results[0].Results[0].ChunkID)
require.Equal(t, types.MatchTypeEmbedding, results[0].Results[0].MatchType)
})
}
}
@@ -0,0 +1,16 @@
// Package postgres implements retrieval against its configured vector backend.
package postgres
import "context"
func (g *pgRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
_ int,
_ string,
) error {
return g.db.WithContext(ctx).Model(&pgVector{}).
Where("knowledge_base_id = ? AND knowledge_id = ?", sourceKB, knowledgeID).
Updates(map[string]any{"knowledge_base_id": targetKB, "tag_id": ""}).Error
}
@@ -0,0 +1,775 @@
package postgres
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"academy/internal/common"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/google/uuid"
"github.com/pgvector/pgvector-go"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// pgRepository implements PostgreSQL-based retrieval operations
type pgRepository struct {
db *gorm.DB // Database connection
keywordScoreMu sync.Mutex
keywordScoreFunction string
}
// NewPostgresRetrieveEngineRepository creates a new PostgreSQL retriever repository
func NewPostgresRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRepository {
logger.GetLogger(context.Background()).Info("[Postgres] Initializing PostgreSQL retriever engine repository")
return &pgRepository{db: db}
}
// keywordScoreFunctionSQL only selects fixed, schema-qualified function names.
// Some PolarDB pg_search builds expose pgsearch.score instead of paradedb.score.
const keywordScoreFunctionSQL = `SELECT n.nspname || '.score' AS score_function
FROM pg_catalog.pg_proc p
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname IN ('paradedb', 'pgsearch')
AND p.proname = 'score' AND p.prokind = 'f' AND p.pronargs = 1
AND p.proargtypes[0] = 'pg_catalog.anyelement'::regtype
AND p.prorettype = 'pg_catalog.float4'::regtype
ORDER BY CASE n.nspname WHEN 'paradedb' THEN 0 ELSE 1 END
LIMIT 1`
// resolveKeywordScoreFunction probes lazily so vector-only stores remain usable.
// Cache successes per repository/database; transient failures can be retried.
func (g *pgRepository) resolveKeywordScoreFunction(ctx context.Context) (string, error) {
g.keywordScoreMu.Lock()
defer g.keywordScoreMu.Unlock()
if g.keywordScoreFunction != "" {
return g.keywordScoreFunction, nil
}
var row struct{ ScoreFunction string }
if err := g.db.WithContext(ctx).Raw(keywordScoreFunctionSQL).Scan(&row).Error; err != nil {
return "", fmt.Errorf("detect PostgreSQL keyword score function: %w", err)
}
if row.ScoreFunction != "paradedb.score" && row.ScoreFunction != "pgsearch.score" {
return "", errors.New("PostgreSQL keyword retrieval requires paradedb.score(anyelement) or " +
"pgsearch.score(anyelement); check pg_search extension compatibility")
}
g.keywordScoreFunction = row.ScoreFunction
return g.keywordScoreFunction, nil
}
// EngineType returns the retriever engine type (PostgreSQL)
func (r *pgRepository) EngineType() types.RetrieverEngineType {
return types.PostgresRetrieverEngineType
}
// Support returns supported retriever types (keywords and vector)
func (r *pgRepository) Support() []types.RetrieverType {
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
}
// calculateIndexStorageSize calculates storage size for a single index entry
func (g *pgRepository) calculateIndexStorageSize(embeddingDB *pgVector) int64 {
// 1. Text content size
contentSizeBytes := int64(len(embeddingDB.Content))
// 2. Vector storage size (2 bytes per dimension for half-precision float)
var vectorSizeBytes int64 = 0
if embeddingDB.Dimension > 0 {
vectorSizeBytes = int64(embeddingDB.Dimension * 2)
}
// 3. Metadata size (fixed overhead for IDs, timestamps etc.)
metadataSizeBytes := int64(200)
// 4. Index overhead (HNSW index is ~2x vector size)
indexOverheadBytes := vectorSizeBytes * 2
// Total size in bytes
totalSizeBytes := contentSizeBytes + vectorSizeBytes + metadataSizeBytes + indexOverheadBytes
return totalSizeBytes
}
// EstimateStorageSize estimates total storage size for multiple indices
func (g *pgRepository) EstimateStorageSize(
ctx context.Context, indexInfoList []*types.IndexInfo, additionalParams map[string]any,
) int64 {
var totalStorageSize int64 = 0
for _, indexInfo := range indexInfoList {
embeddingDB := toDBVectorEmbedding(indexInfo, additionalParams)
totalStorageSize += g.calculateIndexStorageSize(embeddingDB)
}
logger.GetLogger(ctx).Infof(
"[Postgres] Estimated storage size for %d indices: %d bytes",
len(indexInfoList), totalStorageSize,
)
return totalStorageSize
}
// upsertBySource makes a re-index of an existing (source_id, source_type)
// replace the stored row. Callers such as FAQ edits re-index under the old
// source ID and rely on the new content winning; DO NOTHING kept the stale
// content and vector.
var upsertBySource = clause.OnConflict{
Columns: []clause.Column{{Name: "source_id"}, {Name: "source_type"}},
DoUpdates: clause.AssignmentColumns([]string{
"chunk_id", "knowledge_id", "knowledge_base_id", "tag_id",
"content", "dimension", "embedding", "is_enabled", "updated_at",
}),
}
// Save stores a single index entry
func (g *pgRepository) Save(ctx context.Context, indexInfo *types.IndexInfo, additionalParams map[string]any) error {
logger.GetLogger(ctx).Debugf("[Postgres] Saving index for source ID: %s", indexInfo.SourceID)
embeddingDB := toDBVectorEmbedding(indexInfo, additionalParams)
err := g.db.WithContext(ctx).Clauses(upsertBySource).Create(embeddingDB).Error
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to save index: %v", err)
return err
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully saved index for source ID: %s", indexInfo.SourceID)
return nil
}
// BatchSave stores multiple index entries in batch
func (g *pgRepository) BatchSave(
ctx context.Context, indexInfoList []*types.IndexInfo, additionalParams map[string]any,
) error {
logger.GetLogger(ctx).Infof("[Postgres] Batch saving %d indices", len(indexInfoList))
// ON CONFLICT DO UPDATE rejects a statement that touches the same row
// twice, so a source repeated in one batch keeps only its last entry.
type sourceKey struct {
id string
typ int
}
positions := make(map[sourceKey]int, len(indexInfoList))
indexInfoDBList := make([]*pgVector, 0, len(indexInfoList))
for _, indexInfo := range indexInfoList {
row := toDBVectorEmbedding(indexInfo, additionalParams)
key := sourceKey{id: row.SourceID, typ: row.SourceType}
if i, ok := positions[key]; ok {
indexInfoDBList[i] = row
continue
}
positions[key] = len(indexInfoDBList)
indexInfoDBList = append(indexInfoDBList, row)
}
err := g.db.WithContext(ctx).Clauses(upsertBySource).Create(indexInfoDBList).Error
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Batch save failed: %v", err)
return err
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully batch saved %d indices", len(indexInfoList))
return nil
}
// DeleteByChunkIDList deletes indices by chunk IDs
func (g *pgRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int, knowledgeType string) error {
logger.GetLogger(ctx).Infof("[Postgres] Deleting indices by chunk IDs, count: %d", len(chunkIDList))
result := g.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Delete(&pgVector{})
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to delete indices by chunk IDs: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully deleted %d indices by chunk IDs", result.RowsAffected)
return nil
}
// DeleteBySourceIDList deletes indices by source IDs
func (g *pgRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int, knowledgeType string) error {
if len(sourceIDList) == 0 {
return nil
}
logger.GetLogger(ctx).Infof("[Postgres] Deleting indices by source IDs, count: %d", len(sourceIDList))
result := g.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Delete(&pgVector{})
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to delete indices by source IDs: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully deleted %d indices by source IDs", result.RowsAffected)
return nil
}
// DeleteByKnowledgeIDList deletes indices by knowledge IDs
func (g *pgRepository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int, knowledgeType string) error {
logger.GetLogger(ctx).Infof("[Postgres] Deleting indices by knowledge IDs, count: %d", len(knowledgeIDList))
result := g.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Delete(&pgVector{})
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to delete indices by knowledge IDs: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully deleted %d indices by knowledge IDs", result.RowsAffected)
return nil
}
// Retrieve handles retrieval requests and routes to appropriate method
func (g *pgRepository) Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
logger.GetLogger(ctx).Debugf("[Postgres] Processing retrieval request of type: %s", params.RetrieverType)
switch params.RetrieverType {
case types.KeywordsRetrieverType:
return g.KeywordsRetrieve(ctx, params)
case types.VectorRetrieverType:
return g.VectorRetrieve(ctx, params)
}
err := errors.New("invalid retriever type")
logger.GetLogger(ctx).Errorf("[Postgres] %v: %s", err, params.RetrieverType)
return nil, err
}
// KeywordsRetrieve performs keyword-based search using PostgreSQL full-text search
func (g *pgRepository) KeywordsRetrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
logger.GetLogger(ctx).Infof("[Postgres] Keywords retrieval: query=%s, topK=%d", params.Query, params.TopK)
scoreFunction, err := g.resolveKeywordScoreFunction(ctx)
if err != nil {
return nil, err
}
conds := make([]clause.Expression, 0)
// KnowledgeBaseIDs and KnowledgeIDs use AND logic
// - If only KnowledgeBaseIDs: search entire knowledge bases
// - If only KnowledgeIDs: search specific documents
// - If both: search specific documents within the knowledge bases (AND)
if len(params.KnowledgeBaseIDs) > 0 {
logger.GetLogger(ctx).Debugf("[Postgres] Filtering by knowledge base IDs: %v", params.KnowledgeBaseIDs)
conds = append(conds, clause.IN{
Column: "knowledge_base_id",
Values: common.ToInterfaceSlice(params.KnowledgeBaseIDs),
})
}
if len(params.KnowledgeIDs) > 0 {
logger.GetLogger(ctx).Debugf("[Postgres] Filtering by knowledge IDs: %v", params.KnowledgeIDs)
conds = append(conds, clause.IN{
Column: "knowledge_id",
Values: common.ToInterfaceSlice(params.KnowledgeIDs),
})
}
// Filter by tag IDs if specified
if len(params.TagIDs) > 0 {
logger.GetLogger(ctx).Debugf("[Postgres] Filtering by tag IDs: %v", params.TagIDs)
conds = append(conds, clause.IN{
Column: "tag_id",
Values: common.ToInterfaceSlice(params.TagIDs),
})
}
// Use ParadeDB's ||| operator for matching any token
conds = append(conds, clause.Expr{
SQL: "content ||| ?",
Vars: []interface{}{params.Query},
})
// Filter by is_enabled = true or NULL (NULL means enabled for historical data)
conds = append(conds, clause.Expr{
SQL: "(is_enabled IS NULL OR is_enabled = ?)",
Vars: []interface{}{true},
})
conds = append(conds, clause.OrderBy{Columns: []clause.OrderByColumn{
{Column: clause.Column{Name: "score"}, Desc: true},
}})
var embeddingDBList []pgVectorWithScore
err = g.db.WithContext(ctx).Clauses(conds...).
Select([]string{
scoreFunction + "(id) as score",
"id",
"content",
"source_id",
"source_type",
"chunk_id",
"knowledge_id",
"knowledge_base_id",
"tag_id",
}).
Limit(int(params.TopK)).
Find(&embeddingDBList).Error
if err == gorm.ErrRecordNotFound {
logger.GetLogger(ctx).Warnf("[Postgres] No records found for keywords query: %s", params.Query)
return nil, nil
}
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Keywords retrieval failed: %v", err)
return nil, err
}
logger.GetLogger(ctx).Infof("[Postgres] Keywords retrieval found %d results", len(embeddingDBList))
results := make([]*types.IndexWithScore, len(embeddingDBList))
const maxKeywordResultLog = 8
for i := range embeddingDBList {
results[i] = fromDBVectorEmbeddingWithScore(&embeddingDBList[i], types.MatchTypeKeywords)
if i < maxKeywordResultLog {
logger.GetLogger(ctx).Debugf("[Postgres] Keywords result %d: chunk=%s, score=%f",
i, results[i].ChunkID, results[i].Score)
}
}
if len(results) > maxKeywordResultLog {
logger.GetLogger(ctx).Debugf(
"[Postgres] Keywords result summary: total=%d logged=%d truncated=%d",
len(results), maxKeywordResultLog, len(results)-maxKeywordResultLog,
)
}
return []*types.RetrieveResult{
{
Results: results,
RetrieverEngineType: types.PostgresRetrieverEngineType,
RetrieverType: types.KeywordsRetrieverType,
Error: nil,
},
}, nil
}
// VectorRetrieve performs vector similarity search using pgvector
// Optimized to use HNSW index efficiently and avoid recalculating vector distance
func (g *pgRepository) VectorRetrieve(ctx context.Context,
params types.RetrieveParams,
) ([]*types.RetrieveResult, error) {
logger.GetLogger(ctx).Infof("[Postgres] Vector retrieval: dim=%d, topK=%d, threshold=%.4f",
len(params.Embedding), params.TopK, params.Threshold)
dimension := len(params.Embedding)
queryVector := pgvector.NewHalfVector(params.Embedding)
// Build WHERE conditions for filtering
whereParts := make([]string, 0)
allVars := make([]interface{}, 0)
// Add query vector first (used in ORDER BY for HNSW index)
allVars = append(allVars, queryVector)
// Dimension filter (required for HNSW index WHERE clause)
whereParts = append(whereParts, fmt.Sprintf("dimension = $%d", len(allVars)+1))
allVars = append(allVars, dimension)
// KnowledgeBaseIDs and KnowledgeIDs use AND logic
// - If only KnowledgeBaseIDs: search entire knowledge bases
// - If only KnowledgeIDs: search specific documents
// - If both: search specific documents within the knowledge bases (AND)
if len(params.KnowledgeBaseIDs) > 0 {
logger.GetLogger(ctx).Debugf(
"[Postgres] Filtering vector search by knowledge base IDs: %v",
params.KnowledgeBaseIDs,
)
placeholders := make([]string, len(params.KnowledgeBaseIDs))
paramStart := len(allVars) + 1
for i := range params.KnowledgeBaseIDs {
placeholders[i] = fmt.Sprintf("$%d", paramStart+i)
allVars = append(allVars, params.KnowledgeBaseIDs[i])
}
whereParts = append(whereParts, fmt.Sprintf("knowledge_base_id IN (%s)",
strings.Join(placeholders, ", ")))
}
if len(params.KnowledgeIDs) > 0 {
logger.GetLogger(ctx).Debugf(
"[Postgres] Filtering vector search by knowledge IDs: %v",
params.KnowledgeIDs,
)
placeholders := make([]string, len(params.KnowledgeIDs))
paramStart := len(allVars) + 1
for i := range params.KnowledgeIDs {
placeholders[i] = fmt.Sprintf("$%d", paramStart+i)
allVars = append(allVars, params.KnowledgeIDs[i])
}
whereParts = append(whereParts, fmt.Sprintf("knowledge_id IN (%s)",
strings.Join(placeholders, ", ")))
}
// Filter by tag IDs if specified
if len(params.TagIDs) > 0 {
logger.GetLogger(ctx).Debugf(
"[Postgres] Filtering vector search by tag IDs: %v",
params.TagIDs,
)
placeholders := make([]string, len(params.TagIDs))
paramStart := len(allVars) + 1
for i := range params.TagIDs {
placeholders[i] = fmt.Sprintf("$%d", paramStart+i)
allVars = append(allVars, params.TagIDs[i])
}
whereParts = append(whereParts, fmt.Sprintf("tag_id IN (%s)",
strings.Join(placeholders, ", ")))
}
// is_enabled filter
whereParts = append(whereParts, fmt.Sprintf("(is_enabled IS NULL OR is_enabled = $%d)", len(allVars)+1))
allVars = append(allVars, true)
// Build WHERE clause string
whereClause := ""
if len(whereParts) > 0 {
whereClause = "WHERE " + strings.Join(whereParts, " AND ")
}
// Expand TopK to get more candidates before threshold filtering.
//
// HNSW requires `ef_search >= LIMIT`, and a very large LIMIT (e.g. 1000)
// forces HNSW to walk a near-exhaustive portion of the graph, often making
// it slower than a sequential scan and pushing the planner to pick Seq Scan
// even when an index exists. 200 is a good sweet spot: it gives enough
// headroom for threshold/filter post-processing without ballooning ef_search.
expandedTopK := params.TopK * 2
if expandedTopK < 100 {
expandedTopK = 100 // Minimum 100 candidates
}
if expandedTopK > 200 {
expandedTopK = 200 // Maximum 200 candidates (keeps HNSW efficient)
}
if expandedTopK < params.TopK {
expandedTopK = params.TopK // Ensure subquery limit is at least final limit
}
// Optimized query: Use subquery to calculate distance once.
//
// IMPORTANT: The HNSW index in this project is built on the EXPRESSION
// (embedding::halfvec(<dim>)) halfvec_cosine_ops
// because the `embedding` column itself is `halfvec` without a fixed dimension
// (so the table can store multiple embedding sizes such as 798 / 3584 / ...).
//
// pgvector requires the ORDER BY expression to match the indexed expression
// EXACTLY, otherwise the planner falls back to a sequential scan. The
// `embedding::halfvec(%d)` cast on both sides of `<=>` is therefore NOT
// redundant — it is the only way to make the HNSW index get used at all.
// See: pgvector issues #702, #835 and ParadeDB "indexing-expressions" docs.
subqueryLimitParam := len(allVars) + 1
thresholdParam := len(allVars) + 2
finalLimitParam := len(allVars) + 3
querySQL := fmt.Sprintf(`
SELECT
id, content, source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id,
(1 - distance) as score
FROM (
SELECT
id, content, source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id,
embedding::halfvec(%[1]d) <=> $1::halfvec(%[1]d) as distance
FROM embeddings
%[2]s
ORDER BY embedding::halfvec(%[1]d) <=> $1::halfvec(%[1]d)
LIMIT $%[3]d
) AS candidates
WHERE distance <= $%[4]d
ORDER BY distance ASC
LIMIT $%[5]d
`, dimension, whereClause, subqueryLimitParam, thresholdParam, finalLimitParam)
allVars = append(allVars, expandedTopK) // LIMIT in subquery
allVars = append(allVars, 1-params.Threshold) // Distance threshold
allVars = append(allVars, params.TopK) // Final LIMIT
// HNSW's `ef_search` defaults to 40, which is much smaller than our
// `expandedTopK` budget (up to 1000). Without raising it, HNSW would only
// return ~40 candidates per scan and our outer threshold/filter step would
// silently lose recall. `SET LOCAL` requires a transaction so we wrap the
// query in one. We never write inside this transaction, so the cost is
// negligible.
efSearch := expandedTopK
if efSearch < 40 {
efSearch = 40
}
var embeddingDBList []pgVectorWithScore
err := g.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Exec(fmt.Sprintf("SET LOCAL hnsw.ef_search = %d", efSearch)).Error; err != nil {
// Treat as non-fatal: pgvector should always expose this GUC, but if
// for any reason it does not we still want the query to run (just
// with default recall). We must rollback first because a failed
// statement aborts the transaction in PostgreSQL.
logger.GetLogger(ctx).Warnf("[Postgres] Failed to set hnsw.ef_search=%d: %v", efSearch, err)
return err
}
// pgvector >= 0.8 supports iterative scan, which keeps pulling more
// candidates from HNSW until the post-filter (knowledge_base_id /
// knowledge_id / tag_id / is_enabled) yields enough rows. Without it,
// HNSW returns at most ef_search candidates and the outer filter may
// silently lose recall when the filter is selective.
// Best-effort: ignore failure on older pgvector versions.
if err := tx.Exec("SET LOCAL hnsw.iterative_scan = strict_order").Error; err != nil {
logger.GetLogger(ctx).Debugf("[Postgres] hnsw.iterative_scan not available: %v", err)
// abort transaction and let the fallback path below handle it.
return err
}
return tx.Raw(querySQL, allVars...).Scan(&embeddingDBList).Error
})
// Fallback: if the transaction failed because of an unsupported GUC (e.g.
// older pgvector that doesn't have hnsw.ef_search or hnsw.iterative_scan),
// retry the query without the SETs so we still return results.
if err != nil && len(embeddingDBList) == 0 &&
(strings.Contains(err.Error(), "hnsw.ef_search") ||
strings.Contains(err.Error(), "hnsw.iterative_scan")) {
logger.GetLogger(ctx).Warnf("[Postgres] Retrying vector query without HNSW GUC overrides: %v", err)
err = g.db.WithContext(ctx).Raw(querySQL, allVars...).Scan(&embeddingDBList).Error
}
if err == gorm.ErrRecordNotFound {
logger.GetLogger(ctx).Warnf("[Postgres] No vector matches found that meet threshold %.4f", params.Threshold)
return nil, nil
}
if err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Vector retrieval failed: %v", err)
return nil, err
}
// Apply final TopK limit (in case we got more results than needed)
if len(embeddingDBList) > int(params.TopK) {
embeddingDBList = embeddingDBList[:params.TopK]
}
logger.GetLogger(ctx).Infof("[Postgres] Vector retrieval found %d results", len(embeddingDBList))
results := make([]*types.IndexWithScore, len(embeddingDBList))
const maxVectorResultLog = 8
for i := range embeddingDBList {
results[i] = fromDBVectorEmbeddingWithScore(&embeddingDBList[i], types.MatchTypeEmbedding)
if i < maxVectorResultLog {
logger.GetLogger(ctx).Debugf("[Postgres] Vector search result %d: chunk_id %s, score %.4f",
i, results[i].ChunkID, results[i].Score)
}
}
if len(results) > maxVectorResultLog {
logger.GetLogger(ctx).Debugf(
"[Postgres] Vector search result summary: total=%d logged=%d truncated=%d",
len(results), maxVectorResultLog, len(results)-maxVectorResultLog,
)
}
return []*types.RetrieveResult{
{
Results: results,
RetrieverEngineType: types.PostgresRetrieverEngineType,
RetrieverType: types.VectorRetrieverType,
Error: nil,
},
}, nil
}
// CopyIndices copies index data
func (g *pgRepository) CopyIndices(ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
knowledgeType string,
) error {
logger.GetLogger(ctx).Infof(
"[Postgres] Copying indices, source knowledge base: %s, target knowledge base: %s, mapping count: %d",
sourceKnowledgeBaseID, targetKnowledgeBaseID, len(sourceToTargetChunkIDMap),
)
if len(sourceToTargetChunkIDMap) == 0 {
logger.GetLogger(ctx).Warnf("[Postgres] Mapping is empty, no need to copy")
return nil
}
// Only the mapped knowledge is copied (callers clone one document at a
// time), so filter on it instead of paging the whole source knowledge
// base. Keyset pagination on id keeps pages stable; OFFSET without an
// ORDER BY could skip or repeat rows.
sourceKnowledgeIDs := make([]string, 0, len(sourceToTargetKBIDMap))
for sourceKnowledgeID := range sourceToTargetKBIDMap {
sourceKnowledgeIDs = append(sourceKnowledgeIDs, sourceKnowledgeID)
}
// Batch processing parameters
batchSize := 500 // Number of records to process per batch
var lastID uint // Keyset cursor
totalCopied := 0 // Total number of copied records
for {
// Paginated query for source data
var sourceVectors []*pgVector
if err := g.db.WithContext(ctx).
Where("knowledge_base_id = ? AND knowledge_id IN ? AND id > ?",
sourceKnowledgeBaseID, sourceKnowledgeIDs, lastID).
Order("id").
Limit(batchSize).
Find(&sourceVectors).Error; err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to query source index data: %v", err)
return err
}
// If no more data, exit the loop
if len(sourceVectors) == 0 {
if lastID == 0 {
logger.GetLogger(ctx).Warnf("[Postgres] No source index data found")
}
break
}
batchCount := len(sourceVectors)
logger.GetLogger(ctx).Infof(
"[Postgres] Found %d source index data, batch start after id: %d",
batchCount, lastID,
)
// Create target vector index
targetVectors := make([]*pgVector, 0, batchCount)
for _, sourceVector := range sourceVectors {
// Get the mapped target chunk ID
targetChunkID, ok := sourceToTargetChunkIDMap[sourceVector.ChunkID]
if !ok {
logger.GetLogger(ctx).Warnf(
"[Postgres] Source chunk %s not found in target chunk mapping, skipping",
sourceVector.ChunkID,
)
continue
}
// Get the mapped target knowledge ID
targetKnowledgeID, ok := sourceToTargetKBIDMap[sourceVector.KnowledgeID]
if !ok {
logger.GetLogger(ctx).Warnf(
"[Postgres] Source knowledge %s not found in target knowledge mapping, skipping",
sourceVector.KnowledgeID,
)
continue
}
// Handle SourceID transformation for generated questions
// Generated questions have SourceID format: {chunkID}-{questionID}
// Regular chunks have SourceID == ChunkID
var targetSourceID string
if sourceVector.SourceID == sourceVector.ChunkID {
// Regular chunk, use targetChunkID as SourceID
targetSourceID = targetChunkID
} else if strings.HasPrefix(sourceVector.SourceID, sourceVector.ChunkID+"-") {
// This is a generated question, preserve the questionID part
questionID := strings.TrimPrefix(sourceVector.SourceID, sourceVector.ChunkID+"-")
targetSourceID = fmt.Sprintf("%s-%s", targetChunkID, questionID)
} else {
// For other complex scenarios, generate new unique SourceID
targetSourceID = uuid.New().String()
}
// Create new vector index, copy the content and vector of the source index
targetVector := &pgVector{
Content: sourceVector.Content,
SourceID: targetSourceID, // Handle SourceID transformation properly
SourceType: sourceVector.SourceType,
ChunkID: targetChunkID, // Update to target chunk ID
KnowledgeID: targetKnowledgeID, // Update to target knowledge ID
KnowledgeBaseID: targetKnowledgeBaseID, // Update to target knowledge base ID
Dimension: sourceVector.Dimension,
Embedding: sourceVector.Embedding, // Copy the vector embedding directly, avoid recalculation
IsEnabled: sourceVector.IsEnabled,
}
targetVectors = append(targetVectors, targetVector)
}
// Batch insert target vector index
if len(targetVectors) > 0 {
if err := g.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).Create(targetVectors).Error; err != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to batch create target index: %v", err)
return err
}
totalCopied += len(targetVectors)
logger.GetLogger(ctx).Infof(
"[Postgres] Successfully copied batch data, batch size: %d, total copied: %d",
len(targetVectors),
totalCopied,
)
}
// Move to the next batch
lastID = sourceVectors[batchCount-1].ID
// If the number of returned records is less than the requested size, it means the last page has been reached
if batchCount < batchSize {
break
}
}
logger.GetLogger(ctx).Infof("[Postgres] Index copying completed, total copied: %d", totalCopied)
return nil
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (g *pgRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
if len(chunkStatusMap) == 0 {
logger.GetLogger(ctx).Warnf("[Postgres] Chunk status map is empty, skipping update")
return nil
}
logger.GetLogger(ctx).Infof("[Postgres] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
// Group chunks by enabled status for batch updates
enabledChunkIDs := make([]string, 0)
disabledChunkIDs := make([]string, 0)
for chunkID, enabled := range chunkStatusMap {
if enabled {
enabledChunkIDs = append(enabledChunkIDs, chunkID)
} else {
disabledChunkIDs = append(disabledChunkIDs, chunkID)
}
}
// Batch update enabled chunks
if len(enabledChunkIDs) > 0 {
result := g.db.WithContext(ctx).Model(&pgVector{}).
Where("chunk_id IN ?", enabledChunkIDs).
Update("is_enabled", true)
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to update enabled chunks: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).
Infof("[Postgres] Updated %d chunks to enabled, rows affected: %d", len(enabledChunkIDs), result.RowsAffected)
}
// Batch update disabled chunks
if len(disabledChunkIDs) > 0 {
result := g.db.WithContext(ctx).Model(&pgVector{}).
Where("chunk_id IN ?", disabledChunkIDs).
Update("is_enabled", false)
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to update disabled chunks: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).
Infof("[Postgres] Updated %d chunks to disabled, rows affected: %d", len(disabledChunkIDs), result.RowsAffected)
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully batch updated chunk enabled status")
return nil
}
// BatchUpdateChunkTagID updates the tag ID of chunks in batch
func (g *pgRepository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
if len(chunkTagMap) == 0 {
logger.GetLogger(ctx).Warnf("[Postgres] Chunk tag map is empty, skipping update")
return nil
}
logger.GetLogger(ctx).Infof("[Postgres] Batch updating chunk tag ID, count: %d", len(chunkTagMap))
// Group chunks by tag ID for batch updates
tagGroups := make(map[string][]string)
for chunkID, tagID := range chunkTagMap {
tagGroups[tagID] = append(tagGroups[tagID], chunkID)
}
// Batch update chunks for each tag ID
for tagID, chunkIDs := range tagGroups {
result := g.db.WithContext(ctx).Model(&pgVector{}).
Where("chunk_id IN ?", chunkIDs).
Update("tag_id", tagID)
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to update chunks with tag_id %s: %v", tagID, result.Error)
return result.Error
}
logger.GetLogger(ctx).
Infof("[Postgres] Updated %d chunks to tag_id=%s, rows affected: %d", len(chunkIDs), tagID, result.RowsAffected)
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully batch updated chunk tag ID")
return nil
}
@@ -0,0 +1,105 @@
package postgres
import (
"maps"
"slices"
"strconv"
"time"
"academy/internal/common"
"academy/internal/types"
"github.com/pgvector/pgvector-go"
)
// pgVector defines the database model for vector embeddings storage
type pgVector struct {
ID uint `json:"id" gorm:"primarykey"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"`
TagID string `json:"tag_id" gorm:"column:tag_id;index"`
Content string `json:"content" gorm:"column:content;not null"`
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
// No GORM default tag: GORM swaps a zero bool for the tag's default on
// insert, which indexed disabled chunks as enabled. Writers always set it.
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;index"`
}
// pgVectorWithScore extends pgVector with similarity score field
type pgVectorWithScore struct {
ID uint `json:"id" gorm:"primarykey"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
SourceID string `json:"source_id" gorm:"column:source_id;not null"`
SourceType int `json:"source_type" gorm:"column:source_type;not null"`
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"`
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"`
TagID string `json:"tag_id" gorm:"column:tag_id;index"`
Content string `json:"content" gorm:"column:content;not null"`
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`
Score float64 `json:"score" gorm:"column:score"`
}
// TableName specifies the database table name for pgVectorWithScore
func (pgVectorWithScore) TableName() string {
return "embeddings"
}
// TableName specifies the database table name for pgVector
func (pgVector) TableName() string {
return "embeddings"
}
// toDBVectorEmbedding converts IndexInfo to pgVector database model
func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[string]any) *pgVector {
pgVector := &pgVector{
SourceID: indexInfo.SourceID,
SourceType: int(indexInfo.SourceType),
ChunkID: indexInfo.ChunkID,
KnowledgeID: indexInfo.KnowledgeID,
KnowledgeBaseID: indexInfo.KnowledgeBaseID,
TagID: indexInfo.TagID,
Content: common.CleanInvalidUTF8(indexInfo.Content),
IsEnabled: indexInfo.IsEnabled,
}
// Add embedding data if available in additionalParams
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
if embeddingMap, ok := additionalParams["embedding"].(map[string][]float32); ok {
pgVector.Embedding = pgvector.NewHalfVector(embeddingMap[indexInfo.SourceID])
pgVector.Dimension = len(pgVector.Embedding.Slice())
}
}
// Get is_enabled from additionalParams if available
if additionalParams != nil {
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
if enabled, exists := chunkEnabledMap[indexInfo.ChunkID]; exists {
pgVector.IsEnabled = enabled
}
}
}
return pgVector
}
// fromDBVectorEmbeddingWithScore converts pgVectorWithScore to IndexWithScore domain model
func fromDBVectorEmbeddingWithScore(embedding *pgVectorWithScore, matchType types.MatchType) *types.IndexWithScore {
return &types.IndexWithScore{
ID: strconv.FormatInt(int64(embedding.ID), 10),
SourceID: embedding.SourceID,
SourceType: types.SourceType(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
TagID: embedding.TagID,
Content: embedding.Content,
Score: embedding.Score,
MatchType: matchType,
}
}
@@ -0,0 +1,231 @@
package qdrant
import (
"context"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/qdrant/go-client/qdrant"
"google.golang.org/grpc"
)
// copyTestRecordLimit bounds how many target chunk ids the fake keeps, so a run
// that writes the same page over and over cannot grow without limit.
const copyTestRecordLimit = 4096
// copyTestServer answers the RPCs CopyIndices makes and emulates the scroll
// cursor of a real Qdrant server: `offset` is inclusive (the returned page
// starts at that id), so the id the next request has to start at is the first
// point that was *not* returned - and the server hands that id back in
// next_page_offset.
type copyTestServer struct {
mu sync.Mutex
source []*qdrant.RetrievedPoint
target []string
scrolls int
upserts int
written int
// stuck answers every scroll with the same page and the same cursor, which
// is what a server that never moves the cursor on looks like.
stuck bool
}
func copyTestUUID(i int) string {
return fmt.Sprintf("00000000-0000-0000-0000-%012d", i)
}
// copyTestVectors builds the dense vector a stored point carries.
func copyTestVectors() *qdrant.VectorsOutput {
return &qdrant.VectorsOutput{
VectorsOptions: &qdrant.VectorsOutput_Vector{
Vector: &qdrant.VectorOutput{
Vector: &qdrant.VectorOutput_Dense{
Dense: &qdrant.DenseVector{Data: []float32{0.1, 0.2, 0.3, 0.4}},
},
},
},
}
}
func copyTestSourcePoint(i int) *qdrant.RetrievedPoint {
chunk := fmt.Sprintf("chunk-%d", i)
return &qdrant.RetrievedPoint{
Id: qdrant.NewID(copyTestUUID(i)),
Payload: newQdrantValueMap(map[string]any{
fieldContent: "content of " + chunk,
fieldSourceID: chunk,
fieldSourceType: int64(1),
fieldChunkID: chunk,
fieldKnowledgeID: "know-1",
fieldKnowledgeBaseID: "kb-src",
fieldTagID: "",
fieldIsEnabled: true,
}),
Vectors: copyTestVectors(),
}
}
// page answers one scroll the way the emulated server would.
func (s *copyTestServer) page(req *qdrant.ScrollPoints) ([]*qdrant.RetrievedPoint, *qdrant.PointId) {
limit := int(req.GetLimit())
if s.stuck {
if limit > len(s.source) {
limit = len(s.source)
}
return s.source[:limit], s.source[0].Id
}
start := 0
if offset := req.GetOffset(); offset != nil {
for start < len(s.source) && s.source[start].Id.GetUuid() < offset.GetUuid() {
start++
}
}
end := min(start+limit, len(s.source))
if end >= len(s.source) {
return s.source[start:end], nil
}
return s.source[start:end], s.source[end].Id
}
// repository returns a repository whose client is answered by this fake, plus
// the chunk mapping CopyIndices is called with for `count` source chunks.
func (s *copyTestServer) repository(t *testing.T, count int) (*qdrantRepository, map[string]string) {
t.Helper()
for i := range count {
s.source = append(s.source, copyTestSourcePoint(i))
}
chunkMap := make(map[string]string, count)
for i := range count {
chunkMap[fmt.Sprintf("chunk-%d", i)] = fmt.Sprintf("target-chunk-%d", i)
}
client := newInterceptedQdrantClient(t, func(
ctx context.Context, method string, req, reply any, _ *grpc.ClientConn,
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
) error {
// A live server stops answering once the caller's deadline passes.
if err := ctx.Err(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
switch request := req.(type) {
case *qdrant.CollectionExistsRequest:
reply.(*qdrant.CollectionExistsResponse).Result = &qdrant.CollectionExists{Exists: true}
return nil
case *qdrant.ScrollPoints:
s.scrolls++
response := reply.(*qdrant.ScrollResponse)
response.Result, response.NextPageOffset = s.page(request)
return nil
case *qdrant.UpsertPoints:
s.upserts++
s.written += len(request.Points)
for _, point := range request.Points {
if len(s.target) >= copyTestRecordLimit {
break
}
s.target = append(s.target, point.Payload[fieldChunkID].GetStringValue())
}
reply.(*qdrant.PointsOperationResponse).Result = &qdrant.UpdateResult{
Status: qdrant.UpdateStatus_Completed,
}
return nil
default:
return fmt.Errorf("unexpected RPC %s", method)
}
})
return &qdrantRepository{client: client, collectionBaseName: "Copy"}, chunkMap
}
func (s *copyTestServer) counts() (scrolls, upserts, written int) {
s.mu.Lock()
defer s.mu.Unlock()
return s.scrolls, s.upserts, s.written
}
// repeatedTargetChunks returns the recorded target chunk ids that were written
// more than once, and how many extra copies they account for.
func (s *copyTestServer) repeatedTargetChunks() (chunks []string, extra int) {
s.mu.Lock()
defer s.mu.Unlock()
counts := make(map[string]int, len(s.target))
for _, chunk := range s.target {
counts[chunk]++
}
for chunk, n := range counts {
if n > 1 {
chunks = append(chunks, chunk)
extra += n - 1
}
}
return chunks, extra
}
func (s *copyTestServer) summary() string {
scrolls, upserts, written := s.counts()
repeated, extra := s.repeatedTargetChunks()
return fmt.Sprintf(
"scrolls=%d upserts=%d points written=%d recorded=%d chunks written twice=%v duplicate copies=%d",
scrolls, upserts, written, len(s.target), repeated, extra)
}
func runCopyTest(repo *qdrantRepository, chunkMap map[string]string, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return repo.CopyIndices(ctx, "kb-src", map[string]string{"know-1": "know-2"},
chunkMap, "kb-dst", 64, "doc")
}
// Qdrant's scroll offset is inclusive, so the last id of a page is not the
// cursor for the next page; the server returns that cursor in
// next_page_offset. Deriving the cursor from the page instead makes every page
// after the first re-read its last point and copy it into the target again.
func TestCopyIndicesCopiesEachSourceChunkOnce(t *testing.T) {
const sourceCount = 150
server := &copyTestServer{}
repo, chunkMap := server.repository(t, sourceCount)
defer func() { t.Log("copy run: " + server.summary()) }()
if err := runCopyTest(repo, chunkMap, 30*time.Second); err != nil {
t.Fatalf("CopyIndices: %v", err)
}
scrolls, upserts, written := server.counts()
if repeated, extra := server.repeatedTargetChunks(); len(repeated) > 0 {
t.Errorf("target chunks %v were copied again (%d extra copies)", repeated, extra)
}
// 150 chunks at 64 per page: 64 + 64 + 22, so three pages and three writes.
if scrolls != 3 || upserts != 3 {
t.Errorf("scrolls = %d, upserts = %d, want 3 and 3", scrolls, upserts)
}
if written != sourceCount {
t.Errorf("target points = %d, want %d", written, sourceCount)
}
}
// A source that never moves its cursor on must fail loudly instead of writing
// the same page into the target until the task deadline.
func TestCopyIndicesRejectsANonAdvancingCursor(t *testing.T) {
const sourceCount = 64
server := &copyTestServer{stuck: true}
repo, chunkMap := server.repository(t, sourceCount)
defer func() { t.Log("copy run: " + server.summary()) }()
err := runCopyTest(repo, chunkMap, 5*time.Second)
if err == nil || !strings.Contains(err.Error(), "made no progress") {
t.Fatalf("CopyIndices error = %v, want one about a cursor that made no progress", err)
}
scrolls, upserts, written := server.counts()
if scrolls != 2 {
t.Errorf("scrolls = %d, want 2 (stop on the first repeated cursor)", scrolls)
}
if upserts != 1 || written != sourceCount {
t.Errorf("upserts = %d writing %d points, want 1 writing %d", upserts, written, sourceCount)
}
}
@@ -0,0 +1,26 @@
// Package qdrant implements vector retrieval and metadata updates in Qdrant.
package qdrant
import (
"context"
"github.com/qdrant/go-client/qdrant"
)
func (q *qdrantRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
dimension int,
_ string,
) error {
wait := true
_, err := q.client.SetPayload(ctx, &qdrant.SetPayloadPoints{
CollectionName: q.getCollectionName(dimension), Wait: &wait,
Payload: newQdrantValueMap(map[string]any{fieldKnowledgeBaseID: targetKB, fieldTagID: ""}),
PointsSelector: qdrant.NewPointsSelectorFilter(&qdrant.Filter{Must: []*qdrant.Condition{
qdrant.NewMatch(fieldKnowledgeBaseID, sourceKB), qdrant.NewMatch(fieldKnowledgeID, knowledgeID),
}}),
})
return err
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,942 @@
package qdrant
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"slices"
"strings"
"testing"
"time"
"unicode/utf8"
"academy/internal/logger"
"academy/internal/types"
"github.com/qdrant/go-client/qdrant"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestNewQdrantValueMapSanitizesInvalidUTF8AndNUL(t *testing.T) {
malformed := "prefix" + string([]byte{0xff}) + "\x00suffix"
payload := newQdrantValueMap(map[string]any{
fieldContent: malformed,
fieldSourceType: int64(1),
fieldIsEnabled: true,
})
got := payload[fieldContent].GetStringValue()
if got != "prefixsuffix" {
t.Fatalf("unexpected sanitized content: %q", got)
}
if !utf8.ValidString(got) {
t.Fatalf("sanitized content is not valid UTF-8: % x", []byte(got))
}
if gotSourceType := payload[fieldSourceType].GetIntegerValue(); gotSourceType != 1 {
t.Fatalf("source type changed: got %d, want 1", gotSourceType)
}
if gotEnabled := payload[fieldIsEnabled].GetBoolValue(); !gotEnabled {
t.Fatal("is_enabled changed during payload sanitization")
}
}
func TestNewQdrantValueMapPreservesValidUTF8(t *testing.T) {
valid := "valid UTF-8 中文内容"
payload := newQdrantValueMap(map[string]any{
fieldContent: valid,
})
got := payload[fieldContent].GetStringValue()
if got != valid {
t.Fatalf("valid content changed: got %q, want %q", got, valid)
}
}
func TestCreatePayloadSanitizesAllStringFields(t *testing.T) {
malformed := "a" + string([]byte{0xff}) + "\x00b"
embedding := &QdrantVectorEmbedding{
Content: malformed,
SourceID: malformed,
SourceType: 2,
ChunkID: malformed,
KnowledgeID: malformed,
KnowledgeBaseID: malformed,
TagID: malformed,
IsEnabled: true,
}
payload := createPayload(embedding)
stringFields := []string{
fieldContent,
fieldSourceID,
fieldChunkID,
fieldKnowledgeID,
fieldKnowledgeBaseID,
fieldTagID,
}
for _, field := range stringFields {
got := payload[field].GetStringValue()
if got != "ab" {
t.Errorf("%s was not sanitized correctly: got %q", field, got)
}
if !utf8.ValidString(got) {
t.Errorf("%s remains invalid UTF-8: % x", field, []byte(got))
}
}
if got := payload[fieldSourceType].GetIntegerValue(); got != 2 {
t.Errorf("source type changed: got %d, want 2", got)
}
if got := payload[fieldIsEnabled].GetBoolValue(); !got {
t.Error("is_enabled changed during payload creation")
}
}
// newInterceptedQdrantClient builds a client whose unary RPCs are answered by
// the given interceptor, so repository behaviour can be pinned without a live
// Qdrant server.
func newInterceptedQdrantClient(t *testing.T, intercept grpc.UnaryClientInterceptor) *qdrant.Client {
t.Helper()
client, err := qdrant.NewClient(&qdrant.Config{
Host: "localhost",
PoolSize: 1,
SkipCompatibilityCheck: true,
GrpcOptions: []grpc.DialOption{grpc.WithUnaryInterceptor(intercept)},
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := client.Close(); err != nil {
t.Error(err)
}
})
return client
}
// Intercept the SDK's RPCs so failures and cancellation need no live server.
func newPayloadUpdateTestRepository(t *testing.T, collections []string, listErr error,
setPayload func(context.Context, *qdrant.SetPayloadPoints) error,
) *qdrantRepository {
t.Helper()
client := newInterceptedQdrantClient(t, func(
ctx context.Context, method string, req, reply any, _ *grpc.ClientConn,
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
) error {
switch request := req.(type) {
case *qdrant.ListCollectionsRequest:
if listErr != nil {
return listErr
}
response := reply.(*qdrant.ListCollectionsResponse)
for _, name := range collections {
response.Collections = append(response.Collections, &qdrant.CollectionDescription{Name: name})
}
return nil
case *qdrant.SetPayloadPoints:
return setPayload(ctx, request)
default:
return fmt.Errorf("unexpected RPC %s", method)
}
})
return &qdrantRepository{client: client, collectionBaseName: "vectors"}
}
func TestBatchPayloadUpdates(t *testing.T) {
operations := []struct {
name string
groups int
run func(context.Context, *qdrantRepository) error
}{
{"enable", 1, func(ctx context.Context, repo *qdrantRepository) error {
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"chunk": true})
}},
{"disable", 1, func(ctx context.Context, repo *qdrantRepository) error {
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"chunk": false})
}},
{"mixed status", 2, func(ctx context.Context, repo *qdrantRepository) error {
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"on": true, "off": false})
}},
{"tags", 2, func(ctx context.Context, repo *qdrantRepository) error {
return repo.BatchUpdateChunkTagID(ctx, map[string]string{"one": "tag-a", "two": "tag-b"})
}},
}
for _, operation := range operations {
t.Run(operation.name, func(t *testing.T) {
modes := []string{"success", "partial failure", "all failures", "list failure", "no collections"}
for _, mode := range modes {
t.Run(mode, func(t *testing.T) {
collections := []string{"vectors_768", "unrelated_768", "vectors_1536"}
if mode == "no collections" {
collections = []string{"unrelated_768"}
}
var listErr error
if mode == "list failure" {
listErr = errors.New("list unavailable")
}
calls := 0
var failures []error
var descriptions []string
repo := newPayloadUpdateTestRepository(t, collections, listErr,
func(_ context.Context, request *qdrant.SetPayloadPoints) error {
calls++
if request.CollectionName == "unrelated_768" {
t.Error("updated an unrelated collection")
}
fail := mode == "all failures" ||
(mode == "partial failure" && request.CollectionName == "vectors_768")
if !fail {
return nil
}
failure := fmt.Errorf("failure %d", calls)
failures = append(failures, failure)
description := fmt.Sprintf("set chunk tag_id %q",
request.Payload[fieldTagID].GetStringValue())
if enabled, ok := request.Payload[fieldIsEnabled]; ok {
description = "disable chunks"
if enabled.GetBoolValue() {
description = "enable chunks"
}
}
descriptions = append(descriptions, description+" in collection "+request.CollectionName)
return failure
})
err := operation.run(context.Background(), repo)
wantCalls := 2 * operation.groups
if mode == "list failure" || mode == "no collections" {
wantCalls = 0
}
if calls != wantCalls {
t.Fatalf("got %d updates, want %d", calls, wantCalls)
}
if listErr != nil && !errors.Is(err, listErr) {
t.Fatalf("lost list failure: %v", err)
}
if listErr == nil && len(failures) == 0 && err != nil {
t.Fatalf("unexpected error: %v", err)
}
for i, failure := range failures {
if !errors.Is(err, failure) {
t.Errorf("lost failure %v in %v", failure, err)
}
if err == nil || !strings.Contains(err.Error(), descriptions[i]) {
t.Errorf("missing operation/collection %q in %v", descriptions[i], err)
}
}
})
}
t.Run("cancellation retains earlier failures", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
failure := errors.New("first update failed")
calls := 0
repo := newPayloadUpdateTestRepository(t, []string{"vectors_768", "vectors_1536", "vectors_384"}, nil,
func(context.Context, *qdrant.SetPayloadPoints) error {
calls++
if calls == 1 {
return failure
}
cancel()
return ctx.Err()
})
err := operation.run(ctx, repo)
if calls != 2 || !errors.Is(err, failure) || !errors.Is(err, context.Canceled) {
t.Fatalf("calls=%d, err=%v; want 2 calls and both errors", calls, err)
}
})
t.Run("canceled before starting", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := operation.run(ctx, &qdrantRepository{}); !errors.Is(err, context.Canceled) {
t.Fatalf("expected cancellation before any RPC, got %v", err)
}
})
t.Run("canceled during final update", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls := 0
repo := newPayloadUpdateTestRepository(t, []string{"vectors_768"}, nil,
func(context.Context, *qdrant.SetPayloadPoints) error {
calls++
if calls == operation.groups {
cancel()
}
return nil
})
if err := operation.run(ctx, repo); !errors.Is(err, context.Canceled) {
t.Fatalf("expected cancellation instead of success, got %v", err)
}
})
t.Run("expired deadline", func(t *testing.T) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancel()
if err := operation.run(ctx, &qdrantRepository{}); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("expected deadline error before any RPC, got %v", err)
}
})
})
}
}
func TestBatchPayloadUpdatesEmptyInput(t *testing.T) {
repo := &qdrantRepository{}
if err := repo.BatchUpdateChunkEnabledStatus(context.Background(), nil); err != nil {
t.Fatal(err)
}
if err := repo.BatchUpdateChunkTagID(context.Background(), nil); err != nil {
t.Fatal(err)
}
}
// deleteTestRepository is a stand-in Qdrant that only holds `collections` and
// answers like the real server: a delete against a collection it does not have
// fails with the same "Collection ... doesn't exist!" error the issue reports.
// `probe` optionally overrides the CollectionExists answer, e.g. to inject an
// infrastructure failure; a nil probe answers from the inventory.
const qdrantMissingCollectionErr = "Collection %s doesn't exist!"
type deleteTestRepository struct {
repo *qdrantRepository
collections map[string]bool
probe func(collectionName string) (bool, error)
probed []string
deletes []string
}
func newDeleteTestRepository(t *testing.T, collections []string,
probe func(collectionName string) (bool, error),
) *deleteTestRepository {
t.Helper()
harness := &deleteTestRepository{
collections: make(map[string]bool, len(collections)),
probe: probe,
}
for _, name := range collections {
harness.collections[name] = true
}
client := newInterceptedQdrantClient(t, func(
_ context.Context, method string, req, reply any, _ *grpc.ClientConn,
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
) error {
switch request := req.(type) {
case *qdrant.CollectionExistsRequest:
name := request.GetCollectionName()
harness.probed = append(harness.probed, name)
if harness.probe == nil {
response := reply.(*qdrant.CollectionExistsResponse)
response.Result = &qdrant.CollectionExists{Exists: harness.collections[name]}
return nil
}
found, err := harness.probe(name)
if err != nil {
return err
}
reply.(*qdrant.CollectionExistsResponse).Result = &qdrant.CollectionExists{Exists: found}
return nil
case *qdrant.DeletePoints:
name := request.GetCollectionName()
harness.deletes = append(harness.deletes, name)
if !harness.collections[name] {
// Same gRPC status and wording the real server uses, so the
// NotFound no-op path is exercised rather than a paraphrase.
return status.Error(codes.NotFound, fmt.Sprintf(qdrantMissingCollectionErr, name))
}
return nil
default:
return fmt.Errorf("unexpected RPC %s", method)
}
})
harness.repo = &qdrantRepository{client: client, collectionBaseName: "vectors"}
return harness
}
// deleteOperations covers every repository method that deletes by a dimension,
// so the missing-collection rule is pinned for all three of them.
func deleteOperations() []struct {
name string
run func(context.Context, *qdrantRepository) error
} {
return []struct {
name string
run func(context.Context, *qdrantRepository) error
}{
{"chunk ids", func(ctx context.Context, repo *qdrantRepository) error {
return repo.DeleteByChunkIDList(ctx, []string{"chunk-1"}, 1024, types.KnowledgeBaseTypeDocument)
}},
{"knowledge ids", func(ctx context.Context, repo *qdrantRepository) error {
return repo.DeleteByKnowledgeIDList(ctx, []string{"knowledge-1"}, 1024, types.KnowledgeBaseTypeDocument)
}},
{"source ids", func(ctx context.Context, repo *qdrantRepository) error {
return repo.DeleteBySourceIDList(ctx, []string{"source-1"}, 1024, types.KnowledgeBaseTypeDocument)
}},
}
}
// A dimension collection is created lazily on the first write, so deleting from
// one that was never created must be a no-op rather than an error: ingest and
// re-index run "delete then write", and failing here aborts the write that would
// have created the collection (#3337).
func TestDeletesSkipMissingCollection(t *testing.T) {
for _, operation := range deleteOperations() {
t.Run(operation.name, func(t *testing.T) {
// The store holds no dimension collection yet: the delete must not
// reach Qdrant, otherwise it reports the collection as missing.
harness := newDeleteTestRepository(t, nil, nil)
if err := operation.run(context.Background(), harness.repo); err != nil {
t.Fatalf("delete against a missing collection must be a no-op, got %v", err)
}
if len(harness.probed) != 1 || harness.probed[0] != "vectors_1024" {
t.Fatalf("expected one existence probe for vectors_1024, got %v", harness.probed)
}
if len(harness.deletes) != 0 {
t.Fatalf("expected no delete RPC for a missing collection, got %v", harness.deletes)
}
})
}
}
func TestDeletesIssueWhenCollectionExists(t *testing.T) {
for _, operation := range deleteOperations() {
t.Run(operation.name, func(t *testing.T) {
harness := newDeleteTestRepository(t, []string{"vectors_1024"}, nil)
if err := operation.run(context.Background(), harness.repo); err != nil {
t.Fatal(err)
}
if len(harness.deletes) != 1 || harness.deletes[0] != "vectors_1024" {
t.Fatalf("expected one delete against vectors_1024, got %v", harness.deletes)
}
})
}
}
// Infrastructure failures must not be mistaken for an absent collection: a
// store that cannot answer must fail the delete loudly.
func TestDeletePropagatesCollectionCheckFailure(t *testing.T) {
for _, operation := range deleteOperations() {
t.Run(operation.name, func(t *testing.T) {
harness := newDeleteTestRepository(t, []string{"vectors_1024"}, func(string) (bool, error) {
return false, errors.New("qdrant unavailable")
})
err := operation.run(context.Background(), harness.repo)
if err == nil || !strings.Contains(err.Error(), "failed to check collection existence") {
t.Fatalf("expected the existence probe failure to surface, got %v", err)
}
if len(harness.deletes) != 0 {
t.Fatalf("expected no delete RPC after a failed probe, got %v", harness.deletes)
}
})
}
}
// A dimension this process already created needs no probe, which keeps the
// steady-state delete at one round-trip.
func TestDeleteSkipsProbeForInitializedDimension(t *testing.T) {
harness := newDeleteTestRepository(t, []string{"vectors_1024"}, func(string) (bool, error) {
t.Error("initialized dimensions must not be probed")
return false, nil
})
harness.repo.initializedCollections.Store(1024, true)
if err := harness.repo.DeleteByKnowledgeIDList(
context.Background(), []string{"knowledge-1"}, 1024, types.KnowledgeBaseTypeDocument,
); err != nil {
t.Fatal(err)
}
if len(harness.deletes) != 1 || harness.deletes[0] != "vectors_1024" {
t.Fatalf("expected one delete against vectors_1024, got %v", harness.deletes)
}
}
// An empty ID list short-circuits before any RPC, including the new probe.
func TestDeleteWithEmptyIDListSkipsAllRPCs(t *testing.T) {
harness := newDeleteTestRepository(t, []string{"vectors_1024"}, func(string) (bool, error) {
t.Error("empty deletes must not probe the collection")
return false, nil
})
ctx := context.Background()
if err := harness.repo.DeleteByChunkIDList(ctx, nil, 1024, types.KnowledgeBaseTypeDocument); err != nil {
t.Fatal(err)
}
if err := harness.repo.DeleteByKnowledgeIDList(ctx, nil, 1024, types.KnowledgeBaseTypeDocument); err != nil {
t.Fatal(err)
}
if err := harness.repo.DeleteBySourceIDList(ctx, nil, 1024, types.KnowledgeBaseTypeDocument); err != nil {
t.Fatal(err)
}
if len(harness.deletes) != 0 {
t.Fatalf("expected no delete RPC for an empty ID list, got %v", harness.deletes)
}
}
func TestIsMissingCollectionErr(t *testing.T) {
cases := []struct {
name string
err error
want bool
}{
{"nil", nil, false},
{"generic", errors.New("qdrant unavailable"), false},
{"issue wording", fmt.Errorf(qdrantMissingCollectionErr, "vectors_1024"), true},
{"grpc not found", status.Error(codes.NotFound, "Not found: Collection vectors_1024 doesn't exist!"), true},
{"wrapped not found", fmt.Errorf("Delete() failed: vectors_1024: %w", status.Error(codes.NotFound, "Not found")), true},
{"other grpc", status.Error(codes.Unavailable, "qdrant down"), false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := isMissingCollectionErr(tc.err); got != tc.want {
t.Fatalf("isMissingCollectionErr(%v) = %v, want %v", tc.err, got, tc.want)
}
})
}
}
// A dimension this process already created is not probed, so a Qdrant wipe
// that leaves the cache stale still reaches DeletePoints. That RPC's missing
// collection must be a no-op and must drop the cache so the following write
// can recreate the collection (#3337).
func TestDeleteTreatsStaleCacheMissingCollectionAsNoOp(t *testing.T) {
for _, operation := range deleteOperations() {
t.Run(operation.name, func(t *testing.T) {
harness := newDeleteTestRepository(t, nil, func(string) (bool, error) {
t.Error("stale cache must skip the existence probe")
return false, nil
})
harness.repo.initializedCollections.Store(1024, true)
if err := operation.run(context.Background(), harness.repo); err != nil {
t.Fatalf("stale cache + missing collection must be a no-op, got %v", err)
}
if len(harness.deletes) != 1 || harness.deletes[0] != "vectors_1024" {
t.Fatalf("expected one delete against vectors_1024, got %v", harness.deletes)
}
if _, ok := harness.repo.initializedCollections.Load(1024); ok {
t.Fatal("missing collection must drop the initialized cache so the following write can recreate it")
}
})
}
}
// errKeywordScroll makes every Scroll RPC fail the way an unreachable or
// overloaded Qdrant does.
var errKeywordScroll = errors.New("qdrant scroll unavailable")
type keywordsTestHarness struct {
repo *qdrantRepository
scrolls []string
}
// newKeywordsTestHarness wires KeywordsRetrieve to a fake Qdrant server. The
// collection list and the per-collection Scroll outcome are the only inputs the
// search loop has, so both are controlled here instead of stubbing the
// repository.
func newKeywordsTestHarness(t *testing.T, collections []string,
scroll func(collectionName string) ([]*qdrant.RetrievedPoint, error),
) *keywordsTestHarness {
t.Helper()
harness := &keywordsTestHarness{}
client := newInterceptedQdrantClient(t, func(
_ context.Context, method string, req, reply any, _ *grpc.ClientConn,
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
) error {
switch request := req.(type) {
case *qdrant.ListCollectionsRequest:
response := reply.(*qdrant.ListCollectionsResponse)
for _, name := range collections {
response.Collections = append(response.Collections, &qdrant.CollectionDescription{Name: name})
}
return nil
case *qdrant.ScrollPoints:
name := request.GetCollectionName()
harness.scrolls = append(harness.scrolls, name)
points, err := scroll(name)
if err != nil {
return err
}
reply.(*qdrant.ScrollResponse).Result = points
return nil
default:
return fmt.Errorf("unexpected RPC %s", method)
}
})
harness.repo = &qdrantRepository{client: client, collectionBaseName: "vectors"}
return harness
}
func keywordsRetrieveParams() types.RetrieveParams {
return types.RetrieveParams{
Query: "invoice total",
TopK: 10,
KnowledgeBaseIDs: []string{"kb-1"},
}
}
func keywordHitPoint(id, content string) *qdrant.RetrievedPoint {
return &qdrant.RetrievedPoint{
Id: &qdrant.PointId{PointIdOptions: &qdrant.PointId_Uuid{Uuid: id}},
Payload: map[string]*qdrant.Value{
fieldContent: qdrant.NewValueString(content),
fieldChunkID: qdrant.NewValueString(id),
fieldSourceID: qdrant.NewValueString("source-1"),
fieldSourceType: qdrant.NewValueInt(2),
},
}
}
// captureLogs redirects the package logger for one test. The conclusion
// "No keyword matches found" is only legitimate when nothing failed, so the
// tests assert on the rendered log rather than on the counters alone.
func captureLogs(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 TestKeywordsRetrieveFailsWhenEveryMatchedCollectionFails(t *testing.T) {
logs := captureLogs(t)
harness := newKeywordsTestHarness(t,
[]string{"vectors_1024", "vectors_1536", "other_2048"},
func(string) ([]*qdrant.RetrievedPoint, error) {
return nil, errKeywordScroll
},
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
if !errors.Is(err, errKeywordScroll) {
t.Fatalf("all-collections failure must surface as an error, got %v", err)
}
if !strings.Contains(err.Error(), "all 2 matched collections") {
t.Fatalf("error must state how many collections failed, got %q", err)
}
if results != nil {
t.Fatalf("no result set may accompany the error, got %d sets", len(results))
}
if want := []string{"vectors_1024", "vectors_1536"}; !slices.Equal(harness.scrolls, want) {
t.Fatalf("scroll attempts = %v, want %v: only base-name collections are searched", harness.scrolls, want)
}
if strings.Contains(logs.String(), "No keyword matches found") {
t.Fatal("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 TestKeywordsRetrieveKeepsResultsWhenOnlySomeCollectionsFail(t *testing.T) {
logs := captureLogs(t)
harness := newKeywordsTestHarness(t, []string{"vectors_1024", "vectors_1536"},
func(name string) ([]*qdrant.RetrievedPoint, error) {
if name == "vectors_1024" {
return nil, errKeywordScroll
}
return []*qdrant.RetrievedPoint{keywordHitPoint("chunk-1", "invoice total 42")}, nil
},
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
if err != nil {
t.Fatalf("a partially failed batch must not fail the caller, got %v", err)
}
if len(results) != 1 {
t.Fatalf("expected one result set, got %d", len(results))
}
if results[0].Error == nil {
t.Fatal("a partially failed batch must mark its result set with the failure")
}
if !errors.Is(results[0].Error, errKeywordScroll) {
t.Fatalf("partial error must keep the underlying cause, got %v", results[0].Error)
}
if !strings.Contains(results[0].Error.Error(), "1 of 2 matched collections") {
t.Fatalf("partial error must state what failed, got %q", results[0].Error)
}
if len(results[0].Results) != 1 {
t.Fatalf("expected the surviving collection's hit, got %d results", len(results[0].Results))
}
if got := results[0].Results[0].ChunkID; got != "chunk-1" {
t.Fatalf("unexpected chunk id %q", got)
}
if results[0].RetrieverType != types.KeywordsRetrieverType {
t.Fatalf("expected keywords retriever type, got %v", results[0].RetrieverType)
}
if strings.Contains(logs.String(), "No keyword matches found") {
t.Fatal("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 TestKeywordsRetrieveReportsNoMatchesWhenNothingFailed(t *testing.T) {
logs := captureLogs(t)
harness := newKeywordsTestHarness(t, []string{"vectors_1024"},
func(string) ([]*qdrant.RetrievedPoint, error) {
return nil, nil
},
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
if err != nil {
t.Fatalf("a successful search without matches must not error, got %v", err)
}
if len(results) != 1 || len(results[0].Results) != 0 {
t.Fatalf("expected one empty result set, got %#v", results)
}
if results[0].Error != nil {
t.Fatalf("a complete zero-hit search must not mark an error, got %v", results[0].Error)
}
if !strings.Contains(logs.String(), "No keyword matches found") {
t.Fatal("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 TestKeywordsRetrieveMarksPartialFailureWhenNothingHit(t *testing.T) {
logs := captureLogs(t)
harness := newKeywordsTestHarness(t, []string{"vectors_1024", "vectors_1536"},
func(name string) ([]*qdrant.RetrievedPoint, error) {
if name == "vectors_1024" {
return nil, errKeywordScroll
}
return nil, nil
},
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
if err != nil {
t.Fatalf("a partially failed batch must not fail the caller, got %v", err)
}
if len(results) != 1 || len(results[0].Results) != 0 {
t.Fatalf("expected one empty result set, got %#v", results)
}
if !errors.Is(results[0].Error, errKeywordScroll) {
t.Fatalf("partial failure with zero hits must still be marked, got %v", results[0].Error)
}
if strings.Contains(logs.String(), "No keyword matches found") {
t.Fatal("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 TestKeywordsRetrieveWarnsWhenNoCollectionMatchesBaseName(t *testing.T) {
logs := captureLogs(t)
harness := newKeywordsTestHarness(t, []string{"other_1024"},
func(string) ([]*qdrant.RetrievedPoint, error) {
return nil, nil
},
)
results, err := harness.repo.KeywordsRetrieve(context.Background(), keywordsRetrieveParams())
if err != nil {
t.Fatalf("an empty collection list must not error, got %v", err)
}
if len(results) != 1 || len(results[0].Results) != 0 {
t.Fatalf("expected one empty result set, got %#v", results)
}
if results[0].Error != nil {
t.Fatalf("no matching collection is not a partial failure, got %v", results[0].Error)
}
if len(harness.scrolls) != 0 {
t.Fatalf("no Scroll may be issued without a matching collection, got %v", harness.scrolls)
}
if !strings.Contains(logs.String(), "No collection matched base name") {
t.Fatal("a search that never ran must be logged as such")
}
if strings.Contains(logs.String(), "No keyword matches found") {
t.Fatal("a search that never ran must not be logged as a search that found no matches")
}
}
func TestPointWritesWaitForApplication(t *testing.T) {
indices := make([]*types.IndexInfo, 101)
embeddings := make(map[string][]float32, len(indices))
for i := range indices {
id := fmt.Sprintf("chunk-%d", i)
indices[i] = &types.IndexInfo{SourceID: id, ChunkID: id, IsEnabled: true}
embeddings[id] = []float32{0.1, 0.2, 0.3, 0.4}
}
params := map[string]any{fieldEmbedding: embeddings}
chunkMap := make(map[string]string, 65)
for i := range 65 {
chunkMap[fmt.Sprintf("chunk-%d", i)] = fmt.Sprintf("target-%d", i)
}
operations := []struct {
name string
writes int
run func(context.Context, *qdrantRepository) error
}{
{"save", 1, func(ctx context.Context, repo *qdrantRepository) error {
return repo.Save(ctx, indices[0], params)
}},
{"batch save", 2, func(ctx context.Context, repo *qdrantRepository) error {
return repo.BatchSave(ctx, indices, params)
}},
{"copy", 2, func(ctx context.Context, repo *qdrantRepository) error {
return repo.CopyIndices(ctx, "kb-src", map[string]string{"know-1": "know-2"},
chunkMap, "kb-dst", 4, types.KnowledgeBaseTypeDocument)
}},
{"enable and disable", 2, func(ctx context.Context, repo *qdrantRepository) error {
return repo.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{"on": true, "off": false})
}},
{"tags", 2, func(ctx context.Context, repo *qdrantRepository) error {
return repo.BatchUpdateChunkTagID(ctx, map[string]string{"one": "tag-a", "two": "tag-b"})
}},
{"move", 1, func(ctx context.Context, repo *qdrantRepository) error {
return repo.MoveKnowledgeIndices(ctx, "kb-src", "kb-dst", "know-1", nil, 4, "doc")
}},
}
for _, operation := range deleteOperations() {
operations = append(operations, struct {
name string
writes int
run func(context.Context, *qdrantRepository) error
}{operation.name, 1, operation.run})
}
for _, operation := range operations {
t.Run(operation.name, func(t *testing.T) {
for _, outcome := range []struct {
name string
err error
}{
{"completed", nil},
{"application failure", status.Error(codes.Internal, "failed to apply write")},
{"timeout", context.DeadlineExceeded},
} {
t.Run(outcome.name, func(t *testing.T) {
server := &copyTestServer{}
for i := range 65 {
server.source = append(server.source, copyTestSourcePoint(i))
}
applied, acknowledged := 0, 0
client := newInterceptedQdrantClient(t, func(
_ context.Context, method string, req, reply any, _ *grpc.ClientConn,
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
) error {
var wait bool
switch request := req.(type) {
case *qdrant.ListCollectionsRequest:
reply.(*qdrant.ListCollectionsResponse).Collections = []*qdrant.CollectionDescription{
{Name: "vectors_4"},
}
return nil
case *qdrant.ScrollPoints:
response := reply.(*qdrant.ScrollResponse)
response.Result, response.NextPageOffset = server.page(request)
return nil
case *qdrant.UpsertPoints:
wait = request.GetWait()
case *qdrant.DeletePoints:
wait = request.GetWait()
case *qdrant.SetPayloadPoints:
wait = request.GetWait()
default:
return fmt.Errorf("unexpected RPC %s", method)
}
// An asynchronous write can be acknowledged before it is applied,
// even if application will fail. Only waiting exposes that failure.
response := reply.(*qdrant.PointsOperationResponse)
if !wait {
acknowledged++
response.Result = &qdrant.UpdateResult{Status: qdrant.UpdateStatus_Acknowledged}
return nil
}
if outcome.err != nil {
return outcome.err
}
applied++
response.Result = &qdrant.UpdateResult{Status: qdrant.UpdateStatus_Completed}
return nil
})
repo := &qdrantRepository{client: client, collectionBaseName: "vectors"}
repo.initializedCollections.Store(4, true)
repo.initializedCollections.Store(1024, true)
err := operation.run(context.Background(), repo)
if !errors.Is(err, outcome.err) {
t.Fatalf("got error %v, want %v", err, outcome.err)
}
if acknowledged != 0 {
t.Fatalf("returned with %d writes acknowledged but not applied", acknowledged)
}
if outcome.err == nil && applied != operation.writes {
t.Fatalf("applied %d writes before return, want %d", applied, operation.writes)
}
})
}
})
}
}
// newEnsureCollectionTestRepository answers the existence probe with "missing"
// and CreateCollection with createErr, recording the payload indexes created.
func newEnsureCollectionTestRepository(t *testing.T, createErr error) (*qdrantRepository, *[]string) {
t.Helper()
var indexed []string
client := newInterceptedQdrantClient(t, func(
_ context.Context, method string, req, reply any, _ *grpc.ClientConn,
_ grpc.UnaryInvoker, _ ...grpc.CallOption,
) error {
switch request := req.(type) {
case *qdrant.CollectionExistsRequest:
reply.(*qdrant.CollectionExistsResponse).Result = &qdrant.CollectionExists{Exists: false}
return nil
case *qdrant.CreateCollection:
return createErr
case *qdrant.CreateFieldIndexCollection:
indexed = append(indexed, request.GetFieldName())
return nil
default:
return fmt.Errorf("unexpected RPC %s", method)
}
})
return &qdrantRepository{client: client, collectionBaseName: "vectors"}, &indexed
}
// Several workers write the first batches of a new dimension at once, so the
// create can lose to another worker. That must not fail the write: the
// collection exists, and its payload indexes are still ensured.
func TestEnsureCollectionAcceptsConcurrentCreate(t *testing.T) {
repo, indexed := newEnsureCollectionTestRepository(t,
status.Error(codes.AlreadyExists, "Wrong input: Collection `vectors_1024` already exists!"))
if err := repo.ensureCollection(context.Background(), 1024); err != nil {
t.Fatalf("ensureCollection after losing the create race: %v", err)
}
if _, ok := repo.initializedCollections.Load(1024); !ok {
t.Fatal("dimension must be cached once the collection is known to exist")
}
want := []string{fieldChunkID, fieldKnowledgeID, fieldKnowledgeBaseID, fieldSourceID, fieldIsEnabled, fieldContent}
if !slices.Equal(*indexed, want) {
t.Fatalf("payload indexes = %v, want %v", *indexed, want)
}
}
func TestEnsureCollectionReturnsOtherCreateErrors(t *testing.T) {
repo, indexed := newEnsureCollectionTestRepository(t, status.Error(codes.Unavailable, "qdrant down"))
err := repo.ensureCollection(context.Background(), 1024)
if status.Code(err) != codes.Unavailable {
t.Fatalf("ensureCollection error = %v, want the Unavailable create error", err)
}
if _, ok := repo.initializedCollections.Load(1024); ok {
t.Fatal("a failed create must not cache the dimension")
}
if len(*indexed) != 0 {
t.Fatalf("no payload index should be created after a failed create, got %v", *indexed)
}
}
@@ -0,0 +1,33 @@
package qdrant
import (
"sync"
"github.com/qdrant/go-client/qdrant"
)
type qdrantRepository struct {
client *qdrant.Client
collectionBaseName string
shardNumber int // 0 = use Qdrant server default
replicationFactor int // 0 = use Qdrant server default
// Cache for initialized collections (dimension -> true)
initializedCollections sync.Map
}
type QdrantVectorEmbedding struct {
Content string `json:"content"`
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 QdrantVectorEmbeddingWithScore struct {
QdrantVectorEmbedding
Score float64
}
@@ -0,0 +1,222 @@
package sqlite
import (
"bytes"
"context"
"fmt"
"os"
"strings"
"testing"
"academy/internal/logger"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID only touch the index
// copy (lite_embeddings) that retrieval reads, while the authoritative chunks
// row is written by the service layer beforehand. Swallowing an UPDATE error
// therefore makes the call look successful while retrieval keeps filtering on
// the stale is_enabled / tag_id value, so the error has to reach the caller.
func TestBatchUpdateChunkEnabledStatusReturnsUpdateError(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository,
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
[]float32{1, 0},
)
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings").Error)
err := repository.BatchUpdateChunkEnabledStatus(context.Background(), map[string]bool{"chunk-1": false})
require.Error(t, err)
assert.Contains(t, err.Error(), "chunk-1")
assert.Contains(t, err.Error(), "is_enabled")
}
func TestBatchUpdateChunkTagIDReturnsUpdateError(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository,
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
[]float32{1, 0},
)
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings").Error)
err := repository.BatchUpdateChunkTagID(context.Background(), map[string]string{"chunk-1": "tag-2"})
require.Error(t, err)
assert.Contains(t, err.Error(), "chunk-1")
assert.Contains(t, err.Error(), "tag_id")
}
// A statement that fails inside a batch must not be masked by the remaining
// statements of the same batch.
func TestBatchUpdateChunkTagIDReportsFailingStatementInBatch(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
for _, chunkID := range []string{"chunk-ok", "chunk-fail"} {
saveSQLiteTestVector(t, repository,
sqliteTestIndex(chunkID, "kb-1", "knowledge-1", "tag-1", true),
[]float32{1, 0},
)
}
require.NoError(t, repository.db.Exec(`CREATE TRIGGER fail_chunk_tag_update
BEFORE UPDATE ON lite_embeddings
WHEN OLD.chunk_id = 'chunk-fail'
BEGIN SELECT RAISE(ABORT, 'simulated index write failure'); END`).Error)
err := repository.BatchUpdateChunkTagID(context.Background(), map[string]string{
"chunk-ok": "tag-2",
"chunk-fail": "tag-2",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "chunk-fail")
assert.Contains(t, err.Error(), "simulated index write failure")
}
// Every failing statement of a batch has to be reported, not just the one that
// happened to be visited first: stopping at the first failure leaves an
// arbitrary (map-iteration-order-dependent) prefix of the index copy updated
// while blaming a single chunk. Each collected error can only exist if its own
// UPDATE was attempted, so the count proves the whole batch was run.
func TestBatchUpdateChunkTagIDReportsEveryFailingStatementInBatch(t *testing.T) {
const batchSize = 5
repository := newSQLiteRetrieverTestRepository(t)
chunkTagMap := make(map[string]string, batchSize)
for i := 1; i <= batchSize; i++ {
chunkID := fmt.Sprintf("chunk-%d", i)
chunkTagMap[chunkID] = "tag-2"
saveSQLiteTestVector(t, repository,
sqliteTestIndex(chunkID, "kb-1", "knowledge-1", "tag-1", true),
[]float32{1, 0},
)
}
require.NoError(t, repository.db.Exec(`CREATE TRIGGER fail_chunk_tag_update
BEFORE UPDATE ON lite_embeddings
BEGIN SELECT RAISE(ABORT, 'simulated index write failure'); END`).Error)
err := repository.BatchUpdateChunkTagID(context.Background(), chunkTagMap)
require.Error(t, err)
for i := 1; i <= batchSize; i++ {
assert.Contains(t, err.Error(), fmt.Sprintf("chunk-%d", i))
}
assert.Equal(t, batchSize, strings.Count(err.Error(), "simulated index write failure"))
}
// A failing statement must not cut the batch short: the other engines (Milvus,
// Qdrant) accumulate the error and finish the batch, so the rows the batch was
// asked to update are still written. The assertions are on the resulting rows
// rather than on a position in the batch because map iteration order is random.
func TestBatchUpdateChunkTagIDKeepsUpdatingAfterStatementFailure(t *testing.T) {
const batchSize = 5
repository := newSQLiteRetrieverTestRepository(t)
for i := 1; i <= batchSize; i++ {
chunkID := fmt.Sprintf("chunk-%d", i)
saveSQLiteTestVector(t, repository,
sqliteTestIndex(chunkID, "kb-1", "knowledge-1", "tag-1", true),
[]float32{1, 0},
)
}
require.NoError(t, repository.db.Exec(`CREATE TRIGGER fail_chunk_tag_update
BEFORE UPDATE ON lite_embeddings
WHEN OLD.chunk_id = 'chunk-3'
BEGIN SELECT RAISE(ABORT, 'simulated index write failure'); END`).Error)
err := repository.BatchUpdateChunkTagID(context.Background(), map[string]string{
"chunk-1": "tag-2",
"chunk-2": "tag-2",
"chunk-3": "tag-2",
"chunk-4": "tag-2",
"chunk-5": "tag-2",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "chunk-3")
assert.Contains(t, err.Error(), "simulated index write failure")
var rows []sqliteEmbedding
require.NoError(t, repository.db.Order("chunk_id").Find(&rows).Error)
require.Len(t, rows, batchSize)
for _, row := range rows {
if row.ChunkID == "chunk-3" {
assert.Equal(t, "tag-1", row.TagID, "the failing statement must not be applied")
continue
}
assert.Equal(t, "tag-2", row.TagID, "chunk %s was not updated after the failure", row.ChunkID)
}
}
// Matching no row is not an error -- the index copy may legitimately lag behind
// the authoritative chunks table -- but it used to be completely invisible, so
// both batch updates warn with the table and the chunk they were meant for.
func TestBatchUpdateChunkWarnsWhenStatementMatchesNoRow(t *testing.T) {
testCases := []struct {
name string
column string
update func(repository *sqliteRepository, ctx context.Context) error
}{
{
name: "is_enabled",
column: "is_enabled",
update: func(repository *sqliteRepository, ctx context.Context) error {
return repository.BatchUpdateChunkEnabledStatus(ctx, map[string]bool{
"chunk-1": false,
"chunk-missing": false,
})
},
},
{
name: "tag_id",
column: "tag_id",
update: func(repository *sqliteRepository, ctx context.Context) error {
return repository.BatchUpdateChunkTagID(ctx, map[string]string{
"chunk-1": "tag-2",
"chunk-missing": "tag-2",
})
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository,
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
[]float32{1, 0},
)
var logs bytes.Buffer
logger.SetOutput(&logs)
t.Cleanup(func() { logger.SetOutput(os.Stdout) })
require.NoError(t, testCase.update(repository, context.Background()))
output := logs.String()
t.Logf("captured log output:\n%s", output)
assert.Contains(t, output, "lite_embeddings."+testCase.column)
assert.Contains(t, output, "matched 0 rows for chunk chunk-missing")
assert.NotContains(t, output, "matched 0 rows for chunk chunk-1")
})
}
}
// Happy path: the updates still apply and report success.
func TestBatchUpdateChunkStatusAndTagApply(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository,
sqliteTestIndex("chunk-1", "kb-1", "knowledge-1", "tag-1", true),
[]float32{1, 0},
)
require.NoError(t, repository.BatchUpdateChunkEnabledStatus(
context.Background(), map[string]bool{"chunk-1": false}))
require.NoError(t, repository.BatchUpdateChunkTagID(
context.Background(), map[string]string{"chunk-1": "tag-2"}))
var row sqliteEmbedding
require.NoError(t, repository.db.Where("chunk_id = ?", "chunk-1").First(&row).Error)
require.NotNil(t, row.IsEnabled)
assert.False(t, *row.IsEnabled)
assert.Equal(t, "tag-2", row.TagID)
}
@@ -0,0 +1,32 @@
package sqlite
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSanitizeFTS5QueryScopesToContent(t *testing.T) {
t.Parallel()
assert.Equal(t, `content : ("2023")`, sanitizeFTS5Query("2023"))
// Quotes never reach an FTS string unescaped.
assert.Equal(t, `content : ("say" OR "hi")`, sanitizeFTS5Query(`say"hi"`))
// A lone Han character matches bigrams that start with it.
assert.Equal(t, `content : ("A" OR "股"*)`, sanitizeFTS5Query("A股"))
assert.Equal(t, "", sanitizeFTS5Query(" "))
}
// Only the content column is searched: IDs indexed alongside it must not
// match a query.
func TestKeywordsRetrieveIgnoresIDColumns(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
t.Skip("FTS5 unavailable (build without sqlite_fts5)")
}
info := sqliteTestIndex("chunk-2023", "kb", "knowledge", "", true)
info.Content = "quarterly report"
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
assert.Empty(t, keywordSearch(t, repository, "2023"))
assert.Len(t, keywordSearch(t, repository, "quarterly"), 1)
}
@@ -0,0 +1,271 @@
package sqlite
import (
"context"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A chunk row is only useful when its vec0 and FTS rows exist too: retrieval
// joins both index tables on lite_embeddings.id. A discarded index write used
// to commit the chunk row while Save still returned nil, so these tests pin the
// error and the rollback, not just the error.
func countSQLiteRows(t *testing.T, repository *sqliteRepository, sql string, args ...any) int64 {
t.Helper()
var count int64
require.NoError(t, repository.db.Raw(sql, args...).Scan(&count).Error, "count query: %s", sql)
return count
}
func TestBatchSaveRollsBackWhenVecTableIsGone(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
ctx := context.Background()
control := sqliteTestIndex("ctl", "kb", "knowledge", "", true)
saveSQLiteTestVector(t, repository, control, []float32{1, 0})
require.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
require.NoError(t, repository.db.Exec("DROP TABLE vec_embeddings_2").Error)
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
err := repository.Save(ctx, victim, map[string]any{
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
})
require.Error(t, err, "a dropped vec0 table must not be reported as a successful save")
assert.Contains(t, err.Error(), "vec_embeddings_2")
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID),
"the chunk row must roll back together with its vector row")
// The failed write drops the cached "ready" state, so the next save
// recreates the table instead of failing forever.
require.NoError(t, repository.Save(ctx, victim, map[string]any{
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
}))
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID))
assert.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
}
func TestBatchSaveRollsBackWhenFTSTableIsGone(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
t.Skip("FTS5 unavailable (build without sqlite_fts5)")
}
ctx := context.Background()
control := sqliteTestIndex("ctl", "kb", "knowledge", "", true)
saveSQLiteTestVector(t, repository, control, []float32{1, 0})
require.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM lite_embeddings_fts"))
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings_fts").Error)
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
err := repository.Save(ctx, victim, map[string]any{
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
})
require.Error(t, err, "a dropped FTS table must not be reported as a successful save")
assert.Contains(t, err.Error(), "lite_embeddings_fts")
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID),
"the chunk row must roll back together with its keyword index row")
assert.EqualValues(t, 0, countSQLiteRows(t, repository, `SELECT count(*) FROM vec_embeddings_2
WHERE rowid IN (SELECT id FROM lite_embeddings WHERE chunk_id = ?)`, victim.ChunkID))
}
func TestBatchSaveRollsBackWhenVecInsertIsRejected(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
ctx := context.Background()
// A vec0 table of another dimension occupies the name: the table is real,
// so only the insert itself can fail. A 2-dimension vector into float[3]
// is rejected by vec0.
require.NoError(t, repository.db.Exec(`CREATE VIRTUAL TABLE vec_embeddings_2
USING vec0(embedding float[3] distance_metric=cosine)`).Error)
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
err := repository.Save(ctx, victim, map[string]any{
"embedding": map[string][]float32{victim.SourceID: {0, 1}},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "vec_embeddings_2")
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID),
"a rejected vector insert must roll the chunk row back")
}
// An object that only occupies the vec0 table name used to be cached as a
// ready dimension, which kept the whole process from ever creating the table.
func TestSaveFailsWhenAnotherObjectOwnsTheVecTableName(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
ctx := context.Background()
require.NoError(t, repository.db.Exec(`CREATE VIEW vec_embeddings_2 AS SELECT 1 AS x WHERE 0`).Error)
victim := sqliteTestIndex("victim", "kb", "knowledge", "", true)
err := repository.Save(ctx, victim, map[string]any{
"embedding": map[string][]float32{victim.SourceID: {1, 0}},
})
require.Error(t, err)
assert.Contains(t, err.Error(), "vec_embeddings_2")
assert.False(t, repository.hasVecTable(2), "a failed prepare must not be cached as ready")
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", victim.ChunkID))
// Once the obstruction is gone the very next save must retry the table.
require.NoError(t, repository.db.Exec("DROP VIEW vec_embeddings_2").Error)
require.NoError(t, repository.Save(ctx, victim, map[string]any{
"embedding": map[string][]float32{victim.SourceID: {1, 0}},
}))
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM vec_embeddings_2"))
}
func TestDeleteByChunkIDListReportsIndexDeleteFailure(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
info := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
require.NoError(t, repository.db.Exec("DROP TABLE vec_embeddings_2").Error)
err := repository.DeleteByChunkIDList(context.Background(), []string{info.ChunkID}, 2,
string(types.KnowledgeTypeManual))
require.Error(t, err)
assert.Contains(t, err.Error(), "vec_embeddings_2")
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", info.ChunkID),
"the chunk row must survive an index delete that failed")
}
func TestCopyIndicesReportsVectorCopyFailure(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
source := sqliteTestIndex("chunk", "kb-src", "knowledge-src", "", true)
saveSQLiteTestVector(t, repository, source, []float32{1, 0})
require.NoError(t, repository.db.Exec("DROP TABLE vec_embeddings_2").Error)
err := repository.CopyIndices(context.Background(), "kb-src",
map[string]string{"knowledge-src": "knowledge-dst"},
map[string]string{"chunk": "chunk-dst"},
"kb-dst", 2, string(types.KnowledgeTypeManual),
)
require.Error(t, err, "a copy without its vector row must not be reported as a success")
assert.Contains(t, err.Error(), "vec_embeddings_2")
}
// A rejected row used to be logged and skipped, so a clone could report success
// while one chunk never became retrievable. The error must fail the copy and
// name the lost row, without quoting content.
func TestCopyIndicesReportsRejectedRowWithChunkIDs(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
chunk := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", true)
chunk.SourceID = "src-chunk"
chunk.Content = "secret chunk body"
question := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", false)
question.SourceID = "src-chunk-q1"
question.Content = "secret question body"
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{chunk, question}, map[string]any{
"embedding": map[string][]float32{
chunk.SourceID: {1, 0},
question.SourceID: {0, 1},
},
}))
// Only the chunk row is rejected; the question row of the same chunk still
// has to be copied, so the error can be shown to point at one row.
require.NoError(t, repository.db.Exec(`CREATE TRIGGER reject_copied_chunk BEFORE INSERT ON lite_embeddings
WHEN NEW.chunk_id = 'dst-chunk' AND NEW.source_id = 'dst-chunk'
BEGIN SELECT RAISE(ABORT, 'rejected copy'); END`).Error)
err := repository.CopyIndices(context.Background(), "kb-src",
map[string]string{"knowledge-src": "knowledge-dst"},
map[string]string{"src-chunk": "dst-chunk"},
"kb-dst", 2, string(types.KnowledgeTypeManual),
)
require.Error(t, err, "a rejected row must not be reported as a successful copy")
assert.Contains(t, err.Error(), "src-chunk", "the error must name the source chunk")
assert.Contains(t, err.Error(), "dst-chunk", "the error must name the target chunk")
assert.NotContains(t, err.Error(), "secret", "the error must locate the row without leaking its content")
assert.NotContains(t, err.Error(), "src-chunk-q1", "only the rejected row may be reported")
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE source_id = ?", "dst-chunk-q1"),
"the sibling row of the same chunk must still be copied")
assert.EqualValues(t, 0, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE source_id = ?", "dst-chunk"))
}
// A failing keyword index write is accumulated instead of ending the copy: the
// caller sees the row that lost its index row, and the copy keeps going so one
// broken row cannot hide the remaining failures.
func TestCopyIndicesReportsKeywordCopyFailureWithoutLosingTheRow(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
t.Skip("FTS5 unavailable (build without sqlite_fts5)")
}
source := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", true)
source.SourceID = "src-chunk"
saveSQLiteTestVector(t, repository, source, []float32{1, 0})
require.NoError(t, repository.db.Exec("DROP TABLE lite_embeddings_fts").Error)
err := repository.CopyIndices(context.Background(), "kb-src",
map[string]string{"knowledge-src": "knowledge-dst"},
map[string]string{"src-chunk": "dst-chunk"},
"kb-dst", 2, string(types.KnowledgeTypeManual),
)
require.Error(t, err, "a copy whose keyword index row was lost must not report success")
assert.Contains(t, err.Error(), "src-chunk")
assert.Contains(t, err.Error(), "dst-chunk")
assert.Contains(t, err.Error(), "lite_embeddings_fts")
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE source_id = ?", "dst-chunk"))
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
`SELECT count(*) FROM vec_embeddings_2 WHERE rowid IN
(SELECT id FROM lite_embeddings WHERE source_id = ?)`, "dst-chunk"),
"the vector row must still be copied after the keyword index write failed")
}
func TestSaveStillWritesEveryIndexRowOnHealthyTables(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
info := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", info.ChunkID))
assert.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
if repository.db.Migrator().HasTable("lite_embeddings_fts") {
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings_fts"))
assert.Len(t, keywordSearch(t, repository, "content of chunk"), 1)
}
}
// A driver built without the fts5 module cannot host a keyword index at all.
// That is a property of the build, so saving keeps working and the keyword
// index is simply absent; a table that goes missing while fts5 is compiled in
// is a real failure and is covered by TestBatchSaveRollsBackWhenFTSTableIsGone.
func TestSaveWorksWhenTheFTS5ModuleIsNotCompiledIn(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
if repository.db.Migrator().HasTable("lite_embeddings_fts") {
t.Skip("fts5 is compiled in; the keyword index is checked by the other tests")
}
info := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
assert.EqualValues(t, 1, countSQLiteRows(t, repository,
"SELECT count(*) FROM lite_embeddings WHERE chunk_id = ?", info.ChunkID))
assert.EqualValues(t, 1, countSQLiteRows(t, repository, "SELECT count(*) FROM vec_embeddings_2"))
}
@@ -0,0 +1,17 @@
// Package sqlite implements local retrieval with SQLite FTS and vectors.
package sqlite
import "context"
func (r *sqliteRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
_ int,
_ string,
) error {
// FTS and vector rows keep their IDs. Queries join them to this metadata row.
return r.db.WithContext(ctx).Model(&sqliteEmbedding{}).
Where("knowledge_base_id = ? AND knowledge_id = ?", sourceKB, knowledgeID).
Updates(map[string]any{"knowledge_base_id": targetKB, "tag_id": ""}).Error
}
@@ -0,0 +1,72 @@
package sqlite
import (
"context"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestMoveIndicesPreservesVectorsAndExactScopeAcrossRetry(t *testing.T) {
repo := newSQLiteRetrieverTestRepository(t)
ctx := context.Background()
for _, row := range []struct{ chunk, kb, doc string }{
{
"text",
"source",
"doc",
},
{
"image",
"source",
"doc",
},
{
"other",
"source",
"other-doc",
},
{
"foreign",
"third",
"doc",
},
} {
saveSQLiteTestVector(t, repo, sqliteTestIndex(row.chunk, row.kb, row.doc, "old-tag", true), []float32{1, 0})
}
var before []sqliteEmbedding
require.NoError(t, repo.db.Order("id").Find(&before).Error)
for range 2 {
require.NoError(
t,
repo.MoveKnowledgeIndices(ctx, "source", "target", "doc", []string{"text", "image"}, 2, "document"),
)
}
var after []sqliteEmbedding
require.NoError(t, repo.db.Order("id").Find(&after).Error)
require.Len(t, after, len(before))
for i, row := range after {
require.Equal(t, before[i].ID, row.ID)
require.Equal(t, before[i].SourceID, row.SourceID)
if row.KnowledgeID == "doc" && before[i].KnowledgeBaseID == "source" {
require.Equal(t, "target", row.KnowledgeBaseID)
require.Empty(t, row.TagID)
} else {
require.Equal(t, before[i].KnowledgeBaseID, row.KnowledgeBaseID)
require.Equal(t, "old-tag", row.TagID)
}
}
results, err := repo.vectorRetrieve(
ctx,
types.RetrieveParams{
Embedding: []float32{1, 0},
TopK: 10,
KnowledgeBaseIDs: []string{"target"},
RetrieverType: types.VectorRetrieverType,
},
)
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 2, "target vectors remain searchable after an identity-preserving move")
}
@@ -0,0 +1,994 @@
package sqlite
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"unicode"
"academy/internal/common"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
"github.com/google/uuid"
"gorm.io/gorm"
)
// sqliteEmbedding stores metadata alongside the vec0 virtual table rows
type sqliteEmbedding struct {
ID uint `gorm:"primarykey;autoIncrement"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
SourceID string `gorm:"column:source_id;not null;uniqueIndex:idx_sqlite_emb_source"`
SourceType int `gorm:"column:source_type;not null;uniqueIndex:idx_sqlite_emb_source"`
ChunkID string `gorm:"column:chunk_id;index"`
KnowledgeID string `gorm:"column:knowledge_id;index"`
KnowledgeBaseID string `gorm:"column:knowledge_base_id;index"`
TagID string `gorm:"column:tag_id;index"`
Content string `gorm:"column:content;not null"`
Dimension int `gorm:"column:dimension;not null"`
IsEnabled *bool `gorm:"column:is_enabled;default:true;index"`
}
func (sqliteEmbedding) TableName() string { return "lite_embeddings" }
type sqliteRepository struct {
db *gorm.DB
// vecMu guards vecTables: concurrent BatchSave and retrieval goroutines
// all consult it, and an unguarded map write is a fatal runtime error.
vecMu sync.RWMutex
vecTables map[int]bool // tracks which vec0 tables have been created (keyed by dimension)
// ftsUnavailable records that the driver was built without the fts5 module
// (upstream test runs do not pass -tags sqlite_fts5). Keyword indexing
// cannot exist in such a build at all, so its writes are skipped instead of
// failing every ingestion; Lite release builds always pass the tag.
ftsUnavailable bool
}
func NewSQLiteRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRepository {
logger.GetLogger(context.Background()).Info("[SQLite] Initializing SQLite retriever engine repository with sqlite-vec")
if err := db.AutoMigrate(&sqliteEmbedding{}); err != nil {
logger.GetLogger(context.Background()).Errorf("[SQLite] Failed to auto-migrate lite_embeddings: %v", err)
}
repo := &sqliteRepository{
db: db,
vecTables: make(map[int]bool),
}
if err := repo.initFTS5(); err != nil {
if errors.Is(err, errFTS5ModuleMissing) {
repo.ftsUnavailable = true
logger.GetLogger(context.Background()).Warnf(
"[SQLite] Keyword index disabled, driver has no fts5 module: %v", err)
} else {
logger.GetLogger(context.Background()).Errorf("[SQLite] Failed to initialize FTS5 index: %v", err)
}
}
enableImageChunkIndexes(db)
repo.ensureExistingVecTables()
return repo
}
// enableImageChunkIndexes repairs image OCR/caption rows that were indexed
// with is_enabled = 0 because the multimodal indexer never set IsEnabled.
// Retrieval filters on is_enabled, so those rows were never searchable.
// Only rows whose chunk is itself enabled are touched, which leaves chunks a
// user disabled alone; after the first run the statement matches nothing.
func enableImageChunkIndexes(db *gorm.DB) {
result := db.Exec(`UPDATE lite_embeddings SET is_enabled = 1
WHERE is_enabled = 0 AND chunk_id IN (
SELECT id FROM chunks
WHERE chunk_type IN (?, ?) AND is_enabled = 1
)`, string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption))
if result.Error != nil {
logger.GetLogger(context.Background()).Warnf(
"[SQLite] Failed to re-enable image chunk indexes: %v", result.Error)
return
}
if result.RowsAffected > 0 {
logger.GetLogger(context.Background()).Infof(
"[SQLite] Re-enabled %d image OCR/caption index rows", result.RowsAffected)
}
}
// errFTS5ModuleMissing reports a driver built without the fts5 module. The
// keyword index cannot exist in such a build, which is a property of the build
// rather than a write that failed at runtime.
var errFTS5ModuleMissing = errors.New("sqlite driver built without the fts5 module")
// fts5InsertSQL is shared by the initial population and every later keyword
// index write, so both always build the same row shape.
const fts5InsertSQL = `INSERT INTO lite_embeddings_fts(
rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id) VALUES(?, ?, ?, ?, ?, ?)`
// initFTS5 prepares the contentless FTS5 keyword index. A failure is returned
// so it is not mistaken for a working index; the table and its content are
// built in one transaction, because a half-populated index silently drops
// keyword recall for every row that was left out.
func (r *sqliteRepository) initFTS5() error {
var sqlStr string
err := r.db.Raw(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='lite_embeddings_fts'",
).Scan(&sqlStr).Error
if err != nil {
return fmt.Errorf("[SQLite] failed to inspect lite_embeddings_fts: %w", err)
}
// If the table exists but is not contentless (i.e. uses content='lite_embeddings'), recreate it
migrate := sqlStr != "" && strings.Contains(sqlStr, "content='lite_embeddings'")
if migrate {
logger.GetLogger(context.Background()).Infof(
"[SQLite] Migrating FTS5 table to contentless table with manual bigram tokenization")
} else if sqlStr != "" {
return nil
}
err = r.db.Transaction(func(tx *gorm.DB) error {
if migrate {
if err := tx.Exec("DROP TABLE IF EXISTS lite_embeddings_fts").Error; err != nil {
return err
}
}
createSQL := `CREATE VIRTUAL TABLE IF NOT EXISTS lite_embeddings_fts USING fts5(
content, source_id, chunk_id, knowledge_id, knowledge_base_id,
content='',
contentless_delete=1,
tokenize='unicode61'
)`
if err := tx.Exec(createSQL).Error; err != nil {
return err
}
logger.GetLogger(context.Background()).Infof(
"[SQLite] Populating contentless FTS5 table from lite_embeddings with bigrams")
// To populate, we need to read all rows and insert them via Go to apply bigram tokenization
type Row struct {
ID uint
Content string
SourceID string
ChunkID string
KnowledgeID string
KnowledgeBaseID string
}
var rows []Row
if err := tx.Raw(
"SELECT id, content, source_id, chunk_id, knowledge_id, knowledge_base_id FROM lite_embeddings",
).Scan(&rows).Error; err != nil {
return err
}
for _, row := range rows {
if err := tx.Exec(fts5InsertSQL, row.ID, tokenizeCJKBigram(row.Content), row.SourceID,
row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID).Error; err != nil {
return err
}
}
return nil
})
if err != nil {
if strings.Contains(err.Error(), "no such module: fts5") {
return fmt.Errorf("%w: %v", errFTS5ModuleMissing, err)
}
return fmt.Errorf("[SQLite] failed to initialize lite_embeddings_fts: %w", err)
}
return nil
}
func vecTableName(dim int) string {
return fmt.Sprintf("vec_embeddings_%d", dim)
}
func (r *sqliteRepository) hasVecTable(dim int) bool {
r.vecMu.RLock()
defer r.vecMu.RUnlock()
return r.vecTables[dim]
}
func (r *sqliteRepository) markVecTable(dim int) {
r.vecMu.Lock()
defer r.vecMu.Unlock()
r.vecTables[dim] = true
}
// unmarkVecTable drops the cached "ready" state of a dimension after a write
// against its table failed, so the next write re-checks the table instead of
// trusting a marker that no longer describes it.
func (r *sqliteRepository) unmarkVecTable(dim int) {
r.vecMu.Lock()
defer r.vecMu.Unlock()
delete(r.vecTables, dim)
}
// verifyVecTable rejects a same-named object that is not a vec0 table. It is
// needed because CREATE VIRTUAL TABLE IF NOT EXISTS is a silent no-op when any
// object already occupies the name, and a marker set from that no-op kept the
// dimension unindexed for the rest of the process lifetime.
func (r *sqliteRepository) verifyVecTable(tbl string) error {
var createSQL string
if err := r.db.Raw(
`SELECT COALESCE(sql, '') FROM sqlite_master WHERE type = 'table' AND name = ?`, tbl,
).Scan(&createSQL).Error; err != nil {
return fmt.Errorf("[SQLite] failed to inspect %s: %w", tbl, err)
}
if createSQL == "" {
return fmt.Errorf("[SQLite] %s is missing after CREATE VIRTUAL TABLE", tbl)
}
if !strings.Contains(strings.ToLower(createSQL), "using vec0") {
return fmt.Errorf("[SQLite] %s exists but is not a vec0 table: %s", tbl, createSQL)
}
return nil
}
// ensureVecTable makes the vec0 table of a dimension usable and returns an
// error when it cannot, so callers never write vectors into a table that does
// not exist. A dimension is only cached as ready once the table was verified.
func (r *sqliteRepository) ensureVecTable(dim int) error {
if dim <= 0 {
return nil
}
if r.hasVecTable(dim) {
return nil
}
tbl := vecTableName(dim)
createSQL := fmt.Sprintf(
`CREATE VIRTUAL TABLE IF NOT EXISTS %s USING vec0(embedding float[%d] distance_metric=cosine)`,
tbl, dim,
)
if err := r.db.Exec(createSQL).Error; err != nil {
return fmt.Errorf("[SQLite] failed to create vec0 table %s: %w", tbl, err)
}
if err := r.verifyVecTable(tbl); err != nil {
return err
}
r.markVecTable(dim)
return nil
}
func (r *sqliteRepository) ensureExistingVecTables() {
var dims []int
if err := r.db.Model(&sqliteEmbedding{}).Distinct("dimension").
Where("dimension > 0").Pluck("dimension", &dims).Error; err != nil {
logger.GetLogger(context.Background()).Warnf(
"[SQLite] Failed to list indexed dimensions: %v", err)
return
}
for _, dim := range dims {
// A failure here is not cached: the next write retries and reports it.
if err := r.ensureVecTable(dim); err != nil {
logger.GetLogger(context.Background()).Errorf(
"[SQLite] Failed to prepare vec0 table for dim %d: %v", dim, err)
}
}
}
func (r *sqliteRepository) EngineType() types.RetrieverEngineType {
return types.SQLiteRetrieverEngineType
}
func (r *sqliteRepository) Support() []types.RetrieverType {
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
}
func (r *sqliteRepository) Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error {
return r.BatchSave(ctx, []*types.IndexInfo{indexInfo}, params)
}
// BatchSave upserts by (source_id, source_type): rows already indexed for a
// source are replaced together with their FTS and vec0 entries. Callers
// re-index an edited FAQ entry under its old source ID and expect the new
// content to win; ON CONFLICT DO NOTHING kept the stale row instead, and the
// skipped rows also shifted the RETURNING ids GORM assigns back to the slice,
// attaching vectors and FTS entries to the wrong rows.
func (r *sqliteRepository) BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error {
if len(indexInfoList) == 0 {
return nil
}
type sourceKey struct {
id string
typ int
}
positions := make(map[sourceKey]int, len(indexInfoList))
rows := make([]*sqliteEmbedding, 0, len(indexInfoList))
embs := make([][]float32, 0, len(indexInfoList))
for _, info := range indexInfoList {
row := toSQLiteEmbedding(info)
emb := extractEmbedding(params, info.SourceID)
if len(emb) > 0 {
row.Dimension = len(emb)
}
// A source repeated inside one batch keeps its last entry, as an
// upsert would.
key := sourceKey{id: row.SourceID, typ: row.SourceType}
if i, ok := positions[key]; ok {
rows[i], embs[i] = row, emb
continue
}
positions[key] = len(rows)
rows = append(rows, row)
embs = append(embs, emb)
}
sourceIDs := make([]string, 0, len(rows))
for _, row := range rows {
sourceIDs = append(sourceIDs, row.SourceID)
// vec0 tables are created outside the transaction below: production
// SQLite runs on one connection, which the transaction holds.
if err := r.ensureVecTable(row.Dimension); err != nil {
return err
}
}
// Replacing a source is one transaction, so a failed insert cannot
// leave the source with its old rows deleted and no new ones.
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var candidates []sqliteEmbedding
if err := tx.Where("source_id IN ?", sourceIDs).Find(&candidates).Error; err != nil {
return err
}
existing := make([]sqliteEmbedding, 0, len(candidates))
existingIDs := make([]uint, 0, len(candidates))
for _, c := range candidates {
if _, ok := positions[sourceKey{id: c.SourceID, typ: c.SourceType}]; ok {
existing = append(existing, c)
existingIDs = append(existingIDs, c.ID)
}
}
if len(existing) > 0 {
if err := r.deleteRowsAndVecs(tx, existing); err != nil {
return err
}
if err := tx.Where("id IN ?", existingIDs).Delete(&sqliteEmbedding{}).Error; err != nil {
return err
}
}
if err := tx.Create(rows).Error; err != nil {
return err
}
// Every index row is written in the same transaction as the chunk row:
// returning the error rolls the chunk row back instead of committing a
// row that neither retrieval path can find.
for i, row := range rows {
if err := r.syncFTS5Insert(tx, row); err != nil {
return err
}
if len(embs[i]) > 0 {
if err := r.insertVec(tx, row.ID, row.Dimension, embs[i]); err != nil {
r.unmarkVecTable(row.Dimension)
return err
}
}
}
return nil
})
}
func (r *sqliteRepository) EstimateStorageSize(_ context.Context, indexInfoList []*types.IndexInfo, _ map[string]any) int64 {
var total int64
for _, info := range indexInfoList {
total += int64(len(info.Content)) + 200
}
return total
}
func (r *sqliteRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, _ int, _ string) error {
var rows []sqliteEmbedding
if err := r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Find(&rows).Error; err != nil {
return err
}
if err := r.deleteRowsAndVecs(r.db.WithContext(ctx), rows); err != nil {
return err
}
return r.db.WithContext(ctx).Where("chunk_id IN ?", chunkIDList).Delete(&sqliteEmbedding{}).Error
}
func (r *sqliteRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, _ int, _ string) error {
var rows []sqliteEmbedding
if err := r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Find(&rows).Error; err != nil {
return err
}
if err := r.deleteRowsAndVecs(r.db.WithContext(ctx), rows); err != nil {
return err
}
return r.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Delete(&sqliteEmbedding{}).Error
}
func (r *sqliteRepository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, _ int, _ string) error {
var rows []sqliteEmbedding
if err := r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Find(&rows).Error; err != nil {
return err
}
if err := r.deleteRowsAndVecs(r.db.WithContext(ctx), rows); err != nil {
return err
}
return r.db.WithContext(ctx).Where("knowledge_id IN ?", knowledgeIDList).Delete(&sqliteEmbedding{}).Error
}
func (r *sqliteRepository) CopyIndices(ctx context.Context,
_ string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
_ int, _ string,
) error {
sourceChunkIDs := make([]string, 0, len(sourceToTargetChunkIDMap))
for sourceChunkID := range sourceToTargetChunkIDMap {
sourceChunkIDs = append(sourceChunkIDs, sourceChunkID)
}
const batchSize = 500
// A copied chunk is only usable when its row, keyword index row and vector
// row all land: retrieval joins both index tables on lite_embeddings.id, so
// a dropped write leaves a chunk neither path can find while the copy still
// reports success. Every failing row is collected and the loop keeps going,
// so the caller learns all the rows that were lost, not just the first.
var copyErrs []error
for start := 0; start < len(sourceChunkIDs); start += batchSize {
end := min(start+batchSize, len(sourceChunkIDs))
// Every row of a chunk is copied: besides the chunk itself, generated
// questions are indexed as extra rows under the same chunk_id.
var sources []sqliteEmbedding
if err := r.db.WithContext(ctx).
Where("chunk_id IN ?", sourceChunkIDs[start:end]).
Order("id").
Find(&sources).Error; err != nil {
return err
}
for _, src := range sources {
targetChunkID := sourceToTargetChunkIDMap[src.ChunkID]
newRow := sqliteEmbedding{
SourceID: copiedSourceID(src.SourceID, src.ChunkID, targetChunkID),
SourceType: src.SourceType,
ChunkID: targetChunkID,
KnowledgeID: sourceToTargetKBIDMap[src.KnowledgeID],
KnowledgeBaseID: targetKnowledgeBaseID,
TagID: src.TagID,
Content: src.Content,
Dimension: src.Dimension,
IsEnabled: src.IsEnabled,
}
// The source and target chunk IDs locate the lost row without
// quoting its content into the error.
if err := r.db.WithContext(ctx).Create(&newRow).Error; err != nil {
copyErrs = append(copyErrs, fmt.Errorf(
"[SQLite] CopyIndices: failed to copy source %s (chunk %s -> %s): %w",
src.SourceID, src.ChunkID, targetChunkID, err))
continue
}
if err := r.syncFTS5Insert(r.db.WithContext(ctx), &newRow); err != nil {
copyErrs = append(copyErrs, fmt.Errorf(
"[SQLite] CopyIndices: failed to copy keyword index of source %s (chunk %s -> %s): %w",
src.SourceID, src.ChunkID, targetChunkID, err))
}
if src.Dimension > 0 {
if err := r.copyVec(ctx, src.ID, newRow.ID, src.Dimension); err != nil {
copyErrs = append(copyErrs, fmt.Errorf(
"[SQLite] CopyIndices: failed to copy vector of source %s (chunk %s -> %s): %w",
src.SourceID, src.ChunkID, targetChunkID, err))
}
}
}
}
return errors.Join(copyErrs...)
}
// copiedSourceID maps a source row's SourceID onto the target chunk the way
// the Postgres engine does, so the copy can later be deleted or re-indexed by
// source ID: a chunk row uses the chunk ID and a generated question keeps its
// "{chunkID}-{questionID}" suffix.
func copiedSourceID(sourceID, sourceChunkID, targetChunkID string) string {
if sourceID == sourceChunkID {
return targetChunkID
}
if questionID, ok := strings.CutPrefix(sourceID, sourceChunkID+"-"); ok {
return targetChunkID + "-" + questionID
}
return uuid.New().String()
}
// Both batch updates write one statement per chunk, so a failing statement only
// affects its own row. Errors are therefore accumulated and the whole batch is
// attempted (like the Milvus and Qdrant engines do) instead of stopping at the
// first failure and leaving an arbitrary prefix of the map applied, only to be
// reported as a blanket failure.
func (r *sqliteRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
var updateErrs []error
for chunkID, enabled := range chunkStatusMap {
if err := r.updateChunkIndexColumn(ctx, "is_enabled", chunkID, enabled); err != nil {
updateErrs = append(updateErrs,
fmt.Errorf("[SQLite] failed to update is_enabled for chunk %s: %w", chunkID, err))
}
}
return errors.Join(updateErrs...)
}
func (r *sqliteRepository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
var updateErrs []error
for chunkID, tagID := range chunkTagMap {
if err := r.updateChunkIndexColumn(ctx, "tag_id", chunkID, tagID); err != nil {
updateErrs = append(updateErrs,
fmt.Errorf("[SQLite] failed to update tag_id for chunk %s: %w", chunkID, err))
}
}
return errors.Join(updateErrs...)
}
// updateChunkIndexColumn applies a single per-chunk UPDATE to the retrieval
// index copy. A statement matching no row is not an error -- that row may never
// have reached the index -- but it would otherwise stay completely invisible,
// so it is warned about with the table and chunk it was meant for.
func (r *sqliteRepository) updateChunkIndexColumn(
ctx context.Context, column, chunkID string, value any,
) error {
result := r.db.WithContext(ctx).Model(&sqliteEmbedding{}).
Where("chunk_id = ?", chunkID).
Update(column, value)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
logger.GetLogger(ctx).Warnf(
"[SQLite] update of %s.%s matched 0 rows for chunk %s",
sqliteEmbedding{}.TableName(), column, chunkID,
)
}
return nil
}
// --- Retrieve ---
func (r *sqliteRepository) Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
var results []*types.RetrieveResult
if params.RetrieverType == types.KeywordsRetrieverType || params.RetrieverType == "" {
res, err := r.keywordsRetrieve(ctx, params)
if err != nil {
return nil, err
}
results = append(results, res...)
}
if params.RetrieverType == types.VectorRetrieverType || params.RetrieverType == "" {
res, err := r.vectorRetrieve(ctx, params)
if err != nil {
return nil, err
}
results = append(results, res...)
}
return results, nil
}
// --- Keywords retrieval via FTS5 ---
func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
if params.Query == "" {
return nil, nil
}
ftsQuery := sanitizeFTS5Query(params.Query)
sql := `
SELECT e.id, e.source_id, e.source_type, e.chunk_id,
e.knowledge_id, e.knowledge_base_id, e.tag_id,
e.content,
(bm25(lite_embeddings_fts) * -1000000.0) AS score
FROM lite_embeddings_fts
JOIN lite_embeddings e ON e.id = lite_embeddings_fts.rowid
WHERE lite_embeddings_fts MATCH ?
AND (e.is_enabled IS NULL OR e.is_enabled = 1)
`
args := []interface{}{ftsQuery}
for _, wp := range buildFilterWhere(params, "e") {
sql += " AND " + wp.clause
args = append(args, wp.args...)
}
sql += " ORDER BY score DESC LIMIT ?"
args = append(args, params.TopK)
type ftsResult struct {
ID uint
SourceID string
SourceType int
ChunkID string
KnowledgeID string
KnowledgeBaseID string
TagID string
Content string
Score float64
}
var rows []ftsResult
if err := r.db.WithContext(ctx).Raw(sql, args...).Scan(&rows).Error; err != nil {
return nil, fmt.Errorf("FTS5 query failed: %w", err)
}
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: query=%q, ftsQuery=%q, matched=%d rows", params.Query, ftsQuery, len(rows))
items := make([]*types.IndexWithScore, len(rows))
for i, row := range rows {
// bm25 is originally negative and very small, we multiplied it by -1000000.0 in SQL
// to make it positive and human-readable.
score := row.Score
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: #%d chunk_id=%s, score=%.4f, content_preview=%.60s",
i+1, row.ChunkID, score, row.Content)
items[i] = &types.IndexWithScore{
ID: fmt.Sprintf("%d", row.ID),
SourceID: row.SourceID,
SourceType: types.SourceType(row.SourceType),
ChunkID: row.ChunkID,
KnowledgeID: row.KnowledgeID,
KnowledgeBaseID: row.KnowledgeBaseID,
TagID: row.TagID,
Content: row.Content,
Score: score,
MatchType: types.MatchTypeKeywords,
}
}
return []*types.RetrieveResult{{
Results: items,
RetrieverEngineType: types.SQLiteRetrieverEngineType,
RetrieverType: types.KeywordsRetrieverType,
}}, nil
}
func (r *sqliteRepository) vectorRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
if len(params.Embedding) == 0 {
return nil, nil
}
dim := len(params.Embedding)
if err := r.ensureVecTable(dim); err != nil {
return nil, err
}
queryBlob, err := sqlite_vec.SerializeFloat32(params.Embedding)
if err != nil {
return nil, fmt.Errorf("serialize query vector failed: %w", err)
}
tbl := vecTableName(dim)
// ⚠️ sqlite-vec 要求必须有 k = ?
vecSQL := fmt.Sprintf(`
SELECT v.rowid, v.distance,
e.source_id, e.source_type, e.chunk_id,
e.knowledge_id, e.knowledge_base_id,
e.tag_id, e.content
FROM %s v
JOIN lite_embeddings e ON e.id = v.rowid
WHERE v.embedding MATCH ?
AND k = ?
AND v.rowid IN (
SELECT filtered.id
FROM lite_embeddings filtered
WHERE (filtered.is_enabled IS NULL OR filtered.is_enabled = 1)
`, tbl)
args := []interface{}{
queryBlob,
params.TopK, // 这里就是 k
}
// 追加过滤条件
for _, wp := range buildFilterWhere(params, "filtered") {
vecSQL += " AND " + wp.clause
args = append(args, wp.args...)
}
// ⚠️ 这里仍然建议加 ORDER BY,虽然 vec0 已经按距离返回
vecSQL += ") ORDER BY v.distance ASC"
type row struct {
Rowid uint
Distance float64
SourceID string
SourceType int
ChunkID string
KnowledgeID string
KnowledgeBaseID string
TagID string
Content string
}
var rows []row
if err := r.db.WithContext(ctx).
Raw(vecSQL, args...).
Scan(&rows).Error; err != nil {
return nil, fmt.Errorf("sqlite-vec query failed: %w", err)
}
logger.GetLogger(ctx).Infof("[SQLite] vectorRetrieve: query_dim=%d, threshold=%.4f, matched=%d rows", dim, params.Threshold, len(rows))
items := make([]*types.IndexWithScore, 0, len(rows))
for i, v := range rows {
// cosine distance = 1 - cosine_similarity
score := 1 - v.Distance
if params.Threshold > 0 && score < params.Threshold {
continue
}
logger.GetLogger(ctx).Infof("[SQLite] vectorRetrieve: #%d chunk_id=%s, distance=%.4f, score=%.4f, content_preview=%.60s",
i+1, v.ChunkID, v.Distance, score, v.Content)
items = append(items, &types.IndexWithScore{
ID: fmt.Sprintf("%d", v.Rowid),
SourceID: v.SourceID,
SourceType: types.SourceType(v.SourceType),
ChunkID: v.ChunkID,
KnowledgeID: v.KnowledgeID,
KnowledgeBaseID: v.KnowledgeBaseID,
TagID: v.TagID,
Content: v.Content,
Score: score,
MatchType: types.MatchTypeEmbedding,
})
}
return []*types.RetrieveResult{{
Results: items,
RetrieverEngineType: types.SQLiteRetrieverEngineType,
RetrieverType: types.VectorRetrieverType,
}}, nil
}
// --- Internal helpers ---
func toSQLiteEmbedding(info *types.IndexInfo) *sqliteEmbedding {
enabled := info.IsEnabled
return &sqliteEmbedding{
SourceID: info.SourceID,
SourceType: int(info.SourceType),
ChunkID: info.ChunkID,
KnowledgeID: info.KnowledgeID,
KnowledgeBaseID: info.KnowledgeBaseID,
TagID: info.TagID,
Content: common.CleanInvalidUTF8(info.Content),
Dimension: 0,
IsEnabled: &enabled,
}
}
func extractEmbedding(params map[string]any, sourceID string) []float32 {
if params == nil {
return nil
}
embMap, ok := params["embedding"].(map[string][]float32)
if !ok {
return nil
}
return embMap[sourceID]
}
// insertVec writes a row's vector through db. The vec0 table for dim must
// already exist (ensureVecTable), since db may be a transaction. Failures are
// returned so the caller's transaction rolls back instead of committing a
// chunk row whose vector row was dropped.
func (r *sqliteRepository) insertVec(db *gorm.DB, rowID uint, dim int, emb []float32) error {
if rowID == 0 {
return errors.New("[SQLite] cannot insert a vector row without a row id")
}
blob, err := sqlite_vec.SerializeFloat32(emb)
if err != nil {
return fmt.Errorf("[SQLite] failed to serialize embedding of row %d: %w", rowID, err)
}
tbl := vecTableName(dim)
if err := db.Exec(
fmt.Sprintf("INSERT INTO %s(rowid, embedding) VALUES (?, ?)", tbl), rowID, blob,
).Error; err != nil {
return fmt.Errorf("[SQLite] failed to insert vector row %d into %s: %w", rowID, tbl, err)
}
return nil
}
// deleteRowsAndVecs removes the vec0 and FTS copies of the given rows. Every
// failure is returned: deleting only the lite_embeddings rows would leave the
// retrieval indexes holding rows that no longer exist.
func (r *sqliteRepository) deleteRowsAndVecs(db *gorm.DB, rows []sqliteEmbedding) error {
dimIDs := make(map[int][]uint)
for _, row := range rows {
if row.Dimension > 0 {
dimIDs[row.Dimension] = append(dimIDs[row.Dimension], row.ID)
}
}
for dim, ids := range dimIDs {
if !r.hasVecTable(dim) {
continue
}
tbl := vecTableName(dim)
for _, id := range ids {
if err := db.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = ?", tbl), id).Error; err != nil {
return fmt.Errorf("[SQLite] failed to delete vector row %d from %s: %w", id, tbl, err)
}
}
}
if r.ftsUnavailable {
return nil
}
for _, row := range rows {
if err := db.Exec("DELETE FROM lite_embeddings_fts WHERE rowid = ?", row.ID).Error; err != nil {
return fmt.Errorf("[SQLite] failed to delete keyword index row %d: %w", row.ID, err)
}
}
return nil
}
// copyVec duplicates a vector row for a copied chunk. It reports an error when
// the destination table cannot be prepared or the source row has no vector
// row, so a clone cannot silently end up without vectors.
func (r *sqliteRepository) copyVec(ctx context.Context, srcID, dstID uint, dim int) error {
if err := r.ensureVecTable(dim); err != nil {
return err
}
tbl := vecTableName(dim)
result := r.db.WithContext(ctx).Exec(fmt.Sprintf(
"INSERT INTO %s(rowid, embedding) SELECT ?, embedding FROM %s WHERE rowid = ?",
tbl, tbl,
), dstID, srcID)
if result.Error != nil {
r.unmarkVecTable(dim)
return fmt.Errorf("[SQLite] failed to copy vector row %d -> %d in %s: %w",
srcID, dstID, tbl, result.Error)
}
if result.RowsAffected == 0 {
return fmt.Errorf("[SQLite] source row %d has no vector row in %s", srcID, tbl)
}
return nil
}
// syncFTS5Insert mirrors a lite_embeddings row into the keyword index. The
// error is returned so the caller's transaction rolls back instead of leaving
// the chunk unfindable by both retrieval paths.
func (r *sqliteRepository) syncFTS5Insert(db *gorm.DB, row *sqliteEmbedding) error {
if r.ftsUnavailable {
return nil
}
if row.ID == 0 {
return fmt.Errorf("[SQLite] cannot index chunk %s: row has no id", row.SourceID)
}
if err := db.Exec(fts5InsertSQL, row.ID, tokenizeCJKBigram(row.Content), row.SourceID, row.ChunkID,
row.KnowledgeID, row.KnowledgeBaseID).Error; err != nil {
return fmt.Errorf("[SQLite] failed to insert keyword index row for %s: %w", row.SourceID, err)
}
return nil
}
type whereClause struct {
clause string
args []interface{}
}
func buildFilterWhere(params types.RetrieveParams, tableAlias string) []whereClause {
var parts []whereClause
if len(params.KnowledgeBaseIDs) > 0 {
parts = append(parts, whereClause{
clause: tableAlias + ".knowledge_base_id IN (" + placeholders(len(params.KnowledgeBaseIDs)) + ")",
args: toInterfaceSlice(params.KnowledgeBaseIDs),
})
}
if len(params.KnowledgeIDs) > 0 {
parts = append(parts, whereClause{
clause: tableAlias + ".knowledge_id IN (" + placeholders(len(params.KnowledgeIDs)) + ")",
args: toInterfaceSlice(params.KnowledgeIDs),
})
}
if len(params.TagIDs) > 0 {
parts = append(parts, whereClause{
clause: tableAlias + ".tag_id IN (" + placeholders(len(params.TagIDs)) + ")",
args: toInterfaceSlice(params.TagIDs),
})
}
return parts
}
func placeholders(n int) string {
p := make([]string, n)
for i := range p {
p[i] = "?"
}
return strings.Join(p, ",")
}
func toInterfaceSlice(ss []string) []interface{} {
out := make([]interface{}, len(ss))
for i, s := range ss {
out[i] = s
}
return out
}
// tokenizeCJKBigram splits continuous CJK character sequences into overlapping bigrams.
// Non-CJK words are kept intact. This approach maximizes recall for CJK search.
func tokenizeCJKBigram(text string) string {
var parts []string
var currentCJK []rune
var currentNonCJK strings.Builder
flushCJK := func() {
if len(currentCJK) == 0 {
return
}
if len(currentCJK) == 1 {
parts = append(parts, string(currentCJK[0]))
} else {
for i := 0; i < len(currentCJK)-1; i++ {
parts = append(parts, string(currentCJK[i])+string(currentCJK[i+1]))
}
}
currentCJK = currentCJK[:0]
}
flushNonCJK := func() {
if currentNonCJK.Len() > 0 {
parts = append(parts, currentNonCJK.String())
currentNonCJK.Reset()
}
}
for _, r := range text {
// unicode.Han covers Chinese characters
if unicode.Is(unicode.Han, r) {
flushNonCJK()
currentCJK = append(currentCJK, r)
} else if unicode.IsSpace(r) || unicode.IsPunct(r) || unicode.IsSymbol(r) {
// Delimiters
flushCJK()
flushNonCJK()
} else {
// Alphanumeric or other languages
flushCJK()
currentNonCJK.WriteRune(r)
}
}
flushCJK()
flushNonCJK()
return strings.Join(parts, " ")
}
// sanitizeFTS5Query builds an FTS5 query from user input by applying bigram tokenization.
func sanitizeFTS5Query(q string) string {
q = strings.TrimSpace(q)
if q == "" {
return q
}
// Tokenize input query with bigrams (same as during indexing)
tokenized := tokenizeCJKBigram(q)
fields := strings.Fields(tokenized)
var parts []string
for _, f := range fields {
if f == "" {
continue
}
term := `"` + strings.ReplaceAll(f, `"`, `""`) + `"`
// The index holds CJK text as bigrams, so a lone Han character
// (the 股 of "A股") was never a token; match bigrams starting with it.
if runes := []rune(f); len(runes) == 1 && unicode.Is(unicode.Han, runes[0]) {
term += "*"
}
parts = append(parts, term)
}
if len(parts) == 0 {
return ""
}
// Use OR because we want fuzzy match across multiple bigrams/words.
// Only the content column is searched: the FTS table also indexes
// source, chunk, knowledge and KB IDs, so a query for "2023" could match
// a UUID fragment.
return "content : (" + strings.Join(parts, " OR ") + ")"
}
@@ -0,0 +1,188 @@
package sqlite
import (
"context"
"fmt"
"strings"
"sync"
"testing"
"academy/internal/types"
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
gormsqlite "gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var registerSQLiteVec sync.Once
func newSQLiteRetrieverTestRepository(t *testing.T) *sqliteRepository {
t.Helper()
registerSQLiteVec.Do(sqlite_vec.Auto)
dbName := strings.NewReplacer("/", "_", " ", "_").Replace(t.Name())
db, err := gorm.Open(gormsqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", dbName)), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, sqlDB.Close())
})
repository, ok := NewSQLiteRetrieveEngineRepository(db).(*sqliteRepository)
require.True(t, ok)
return repository
}
func saveSQLiteTestVector(t *testing.T, repository *sqliteRepository, info *types.IndexInfo, embedding []float32) {
t.Helper()
require.NoError(t, repository.Save(context.Background(), info, map[string]any{
"embedding": map[string][]float32{info.SourceID: embedding},
}))
}
func sqliteTestIndex(chunkID, knowledgeBaseID, knowledgeID, tagID string, enabled bool) *types.IndexInfo {
return &types.IndexInfo{
Content: chunkID,
SourceID: "source-" + chunkID,
SourceType: types.ChunkSourceType,
ChunkID: chunkID,
KnowledgeID: knowledgeID,
KnowledgeBaseID: knowledgeBaseID,
TagID: tagID,
IsEnabled: enabled,
}
}
func TestVectorRetrieveFiltersBeforeTopK(t *testing.T) {
testCases := []struct {
name string
blocker *types.IndexInfo
configure func(*types.RetrieveParams)
}{
{
name: "knowledge base",
blocker: sqliteTestIndex("blocker", "kb-other", "knowledge-target", "tag-target", true),
configure: func(params *types.RetrieveParams) {
params.KnowledgeBaseIDs = []string{"kb-target"}
},
},
{
name: "knowledge",
blocker: sqliteTestIndex("blocker", "kb-target", "knowledge-other", "tag-target", true),
configure: func(params *types.RetrieveParams) {
params.KnowledgeIDs = []string{"knowledge-target"}
},
},
{
name: "tag",
blocker: sqliteTestIndex("blocker", "kb-target", "knowledge-target", "tag-other", true),
configure: func(params *types.RetrieveParams) {
params.TagIDs = []string{"tag-target"}
},
},
{
name: "enabled status",
blocker: sqliteTestIndex("blocker", "kb-target", "knowledge-target", "tag-target", false),
configure: func(_ *types.RetrieveParams) {},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository, testCase.blocker, []float32{1, 0})
saveSQLiteTestVector(t, repository,
sqliteTestIndex("target", "kb-target", "knowledge-target", "tag-target", true),
[]float32{0.8, 0.6},
)
params := types.RetrieveParams{
Embedding: []float32{1, 0},
TopK: 1,
RetrieverType: types.VectorRetrieverType,
}
testCase.configure(&params)
results, err := repository.vectorRetrieve(context.Background(), params)
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 1)
assert.Equal(t, "target", results[0].Results[0].ChunkID)
})
}
}
func TestVectorRetrieveZeroThresholdDoesNotFilter(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository,
sqliteTestIndex("anti-correlated", "kb-target", "knowledge-target", "tag-target", true),
[]float32{-1, 0},
)
results, err := repository.vectorRetrieve(context.Background(), types.RetrieveParams{
Embedding: []float32{1, 0},
KnowledgeBaseIDs: []string{"kb-target"},
TopK: 1,
Threshold: 0,
RetrieverType: types.VectorRetrieverType,
})
require.NoError(t, err)
require.Len(t, results, 1)
require.Len(t, results[0].Results, 1)
assert.Equal(t, "anti-correlated", results[0].Results[0].ChunkID)
assert.Less(t, results[0].Results[0].Score, 0.0)
}
func TestVectorRetrieveAppliesSimilarityThreshold(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository,
sqliteTestIndex("below-threshold", "kb-target", "knowledge-target", "tag-target", true),
[]float32{0.5, 0.8660254},
)
results, err := repository.vectorRetrieve(context.Background(), types.RetrieveParams{
Embedding: []float32{1, 0},
KnowledgeBaseIDs: []string{"kb-target"},
TopK: 1,
Threshold: 0.75,
RetrieverType: types.VectorRetrieverType,
})
require.NoError(t, err)
require.Len(t, results, 1)
assert.Empty(t, results[0].Results)
}
func TestRetrieveReturnsVectorQueryError(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
saveSQLiteTestVector(t, repository,
sqliteTestIndex("chunk", "kb-target", "knowledge-target", "tag-target", true),
[]float32{1, 0},
)
require.NoError(t, repository.db.Exec("DROP TABLE "+vecTableName(2)).Error)
results, err := repository.Retrieve(context.Background(), types.RetrieveParams{
Embedding: []float32{1, 0},
TopK: 1,
RetrieverType: types.VectorRetrieverType,
})
require.Error(t, err)
assert.Nil(t, results)
assert.Contains(t, err.Error(), "sqlite-vec query failed")
}
func TestRetrieveReturnsKeywordQueryError(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
require.NoError(t, repository.db.Exec("DROP TABLE IF EXISTS lite_embeddings_fts").Error)
results, err := repository.Retrieve(context.Background(), types.RetrieveParams{
Query: "missing fts table",
TopK: 1,
RetrieverType: types.KeywordsRetrieverType,
})
require.Error(t, err)
assert.Nil(t, results)
assert.Contains(t, err.Error(), "FTS5 query failed")
}
@@ -0,0 +1,209 @@
package sqlite
import (
"context"
"fmt"
"sync"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func vectorSearch(t *testing.T, repository *sqliteRepository, embedding []float32) []*types.IndexWithScore {
t.Helper()
results, err := repository.vectorRetrieve(context.Background(), types.RetrieveParams{
Embedding: embedding,
TopK: 10,
RetrieverType: types.VectorRetrieverType,
})
require.NoError(t, err)
require.Len(t, results, 1)
return results[0].Results
}
func keywordSearch(t *testing.T, repository *sqliteRepository, query string) []*types.IndexWithScore {
t.Helper()
results, err := repository.keywordsRetrieve(context.Background(), types.RetrieveParams{
Query: query,
TopK: 10,
RetrieverType: types.KeywordsRetrieverType,
})
require.NoError(t, err)
require.Len(t, results, 1)
return results[0].Results
}
func TestBatchSaveReplacesExistingSource(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
info := sqliteTestIndex("faq", "kb", "knowledge", "", true)
info.Content = "oldanswer"
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
edited := *info
edited.Content = "newanswer"
saveSQLiteTestVector(t, repository, &edited, []float32{0, 1})
var count int64
require.NoError(t, repository.db.Model(&sqliteEmbedding{}).Count(&count).Error)
assert.Equal(t, int64(1), count, "re-indexing a source must replace its row")
hits := vectorSearch(t, repository, []float32{0, 1})
require.Len(t, hits, 1)
assert.Equal(t, "newanswer", hits[0].Content)
assert.InDelta(t, 1.0, hits[0].Score, 1e-3, "the vector must be the re-indexed one")
if !repository.db.Migrator().HasTable("lite_embeddings_fts") {
t.Log("FTS5 unavailable (build without sqlite_fts5); skipping keyword checks")
return
}
assert.Empty(t, keywordSearch(t, repository, "oldanswer"), "stale FTS entry must be gone")
require.Len(t, keywordSearch(t, repository, "newanswer"), 1)
}
func TestBatchSaveKeepsVectorsAlignedWhenSomeSourcesExist(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
existing := sqliteTestIndex("existing", "kb", "knowledge", "", true)
saveSQLiteTestVector(t, repository, existing, []float32{1, 0})
fresh := sqliteTestIndex("fresh", "kb", "knowledge", "", true)
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{existing, fresh}, map[string]any{
"embedding": map[string][]float32{
existing.SourceID: {1, 0},
fresh.SourceID: {0, 1},
},
}))
hits := vectorSearch(t, repository, []float32{0, 1})
require.Len(t, hits, 2)
assert.Equal(t, "fresh", hits[0].ChunkID, "the fresh row must carry its own vector")
assert.InDelta(t, 1.0, hits[0].Score, 1e-3)
}
func TestBatchSaveKeepsLastDuplicateInBatch(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
first := sqliteTestIndex("chunk", "kb", "knowledge", "", true)
first.Content = "firstversion"
second := *first
second.Content = "secondversion"
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{first, &second}, map[string]any{
"embedding": map[string][]float32{first.SourceID: {1, 0}},
}))
hits := vectorSearch(t, repository, []float32{1, 0})
require.Len(t, hits, 1)
assert.Equal(t, "secondversion", hits[0].Content)
}
func TestConcurrentBatchSaveNewDimensions(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
sqlDB, err := repository.db.DB()
require.NoError(t, err)
// Production runs SQLite on a single connection.
sqlDB.SetMaxOpenConns(1)
var wg sync.WaitGroup
errs := make(chan error, 16)
for i := range 16 {
wg.Add(1)
go func() {
defer wg.Done()
dim := 2 + i%4
info := sqliteTestIndex(fmt.Sprintf("chunk-%d", i), "kb", "knowledge", "", true)
embedding := make([]float32, dim)
embedding[0] = 1
errs <- repository.BatchSave(context.Background(), []*types.IndexInfo{info}, map[string]any{
"embedding": map[string][]float32{info.SourceID: embedding},
})
}()
}
wg.Wait()
close(errs)
for err := range errs {
require.NoError(t, err)
}
for dim := 2; dim < 6; dim++ {
assert.True(t, repository.hasVecTable(dim))
}
}
func TestCopyIndicesCopiesEveryRowOfAChunk(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
chunk := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", true)
chunk.SourceID = "src-chunk"
question := sqliteTestIndex("src-chunk", "kb-src", "knowledge-src", "", false)
question.SourceID = "src-chunk-q1"
question.Content = "generated question"
require.NoError(t, repository.BatchSave(context.Background(), []*types.IndexInfo{chunk, question}, map[string]any{
"embedding": map[string][]float32{
chunk.SourceID: {1, 0},
question.SourceID: {0, 1},
},
}))
require.NoError(t, repository.CopyIndices(context.Background(), "kb-src",
map[string]string{"knowledge-src": "knowledge-dst"},
map[string]string{"src-chunk": "dst-chunk"},
"kb-dst", 2, string(types.KnowledgeTypeManual),
))
var copied []sqliteEmbedding
require.NoError(t, repository.db.Where("knowledge_base_id = ?", "kb-dst").Order("source_id").Find(&copied).Error)
require.Len(t, copied, 2)
assert.Equal(t, "dst-chunk", copied[0].SourceID)
assert.True(t, *copied[0].IsEnabled)
assert.Equal(t, "dst-chunk-q1", copied[1].SourceID)
assert.False(t, *copied[1].IsEnabled, "enabled state must be copied")
for _, row := range copied {
assert.Equal(t, "dst-chunk", row.ChunkID)
assert.Equal(t, "knowledge-dst", row.KnowledgeID)
}
}
func TestEnableImageChunkIndexesRepairsOnlyEnabledImageChunks(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
require.NoError(t, repository.db.Exec(
`CREATE TABLE chunks (id TEXT PRIMARY KEY, chunk_type TEXT, is_enabled BOOLEAN)`).Error)
require.NoError(t, repository.db.Exec(`INSERT INTO chunks (id, chunk_type, is_enabled) VALUES
('ocr', 'image_ocr', 1), ('caption', 'image_caption', 1),
('ocr-off', 'image_ocr', 0), ('text-off', 'text', 1)`).Error)
for _, id := range []string{"ocr", "caption", "ocr-off", "text-off"} {
saveSQLiteTestVector(t, repository, sqliteTestIndex(id, "kb", "knowledge", "", false), []float32{1, 0})
}
enableImageChunkIndexes(repository.db)
enabled := map[string]bool{}
var rows []sqliteEmbedding
require.NoError(t, repository.db.Find(&rows).Error)
for _, row := range rows {
enabled[row.ChunkID] = *row.IsEnabled
}
assert.Equal(t, map[string]bool{
"ocr": true, "caption": true, "ocr-off": false, "text-off": false,
}, enabled)
}
// Replacing a source is atomic: when the insert fails, the old row stays.
func TestBatchSaveKeepsOldRowWhenInsertFails(t *testing.T) {
repository := newSQLiteRetrieverTestRepository(t)
info := sqliteTestIndex("faq", "kb", "knowledge", "", true)
info.Content = "old answer"
saveSQLiteTestVector(t, repository, info, []float32{1, 0})
require.NoError(t, repository.db.Exec(`CREATE TRIGGER reject_boom BEFORE INSERT ON lite_embeddings
WHEN NEW.content = 'boom' BEGIN SELECT RAISE(ABORT, 'rejected'); END`).Error)
edited := *info
edited.Content = "boom"
require.Error(t, repository.BatchSave(context.Background(), []*types.IndexInfo{&edited}, map[string]any{
"embedding": map[string][]float32{edited.SourceID: {0, 1}},
}))
var rows []sqliteEmbedding
require.NoError(t, repository.db.Find(&rows).Error)
require.Len(t, rows, 1)
assert.Equal(t, "old answer", rows[0].Content)
hits := vectorSearch(t, repository, []float32{1, 0})
require.Len(t, hits, 1, "the old vector must survive the failed replace")
}
@@ -0,0 +1,33 @@
// Package tencentvectordb implements retrieval against its configured vector backend.
package tencentvectordb
import (
"context"
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
)
func (r *repository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
dimension int,
_ string,
) error {
filter := tcvectordb.NewFilter(
tcvectordb.In(
fieldKnowledgeBaseID,
[]string{sourceKB},
) + " and " + tcvectordb.In(
fieldKnowledgeID,
[]string{knowledgeID},
),
)
_, err := r.client.Database(r.databaseName).
Collection(r.collectionName(dimension)).
Update(ctx, tcvectordb.UpdateDocumentParams{
QueryFilter: filter,
UpdateFields: map[string]tcvectordb.Field{fieldKnowledgeBaseID: {Val: targetKB}, fieldTagID: {Val: ""}},
})
return err
}
@@ -0,0 +1,784 @@
package tencentvectordb
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"maps"
"os"
"slices"
"sort"
"strconv"
"strings"
"unicode/utf8"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/tencent/vectordatabase-sdk-go/tcvdbtext/encoder"
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
)
const copyIndicesQueryPageSize int64 = 500
// NewTencentVectorDBRetrieveEngineRepository creates a Tencent VectorDB-backed retrieve repository.
func NewTencentVectorDBRetrieveEngineRepository(
client *tcvectordb.RpcClient,
databaseName string,
indexCfg *types.IndexConfig,
) interfaces.RetrieveEngineRepository {
if databaseName == "" {
databaseName = os.Getenv(envTencentVectorDBDatabase)
}
if databaseName == "" {
databaseName = defaultDatabaseName
}
collectionBaseName := types.ResolveCollectionName(indexCfg, envTencentVectorDBCollection, defaultCollectionName)
return &repository{
client: client,
databaseName: databaseName,
collectionBaseName: collectionBaseName,
useDimensionSuffix: shouldUseDimensionSuffix(indexCfg),
shardsNum: defaultIfZero(indexCfg.GetShardsNum(1), 1),
replicasNum: resolveReplicaNumber(indexCfg),
}
}
func resolveReplicaNumber(indexCfg *types.IndexConfig) int {
if indexCfg != nil && indexCfg.ReplicaNumber > 0 {
return indexCfg.ReplicaNumber
}
if raw := strings.TrimSpace(os.Getenv(envTencentVectorDBReplicaNum)); raw != "" {
replicas, err := strconv.Atoi(raw)
if err == nil && replicas >= 0 {
return replicas
}
}
return defaultReplicaNumber
}
func (r *repository) EngineType() types.RetrieverEngineType {
return types.TencentVectorDBRetrieverEngineType
}
func (r *repository) Support() []types.RetrieverType {
return []types.RetrieverType{types.KeywordsRetrieverType, types.VectorRetrieverType}
}
func (r *repository) Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error {
return r.BatchSave(ctx, []*types.IndexInfo{indexInfo}, params)
}
func (r *repository) BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error {
log := logger.GetLogger(ctx)
if len(indexInfoList) == 0 {
return nil
}
embeddingsByDimension := make(map[int][]*vectorEmbedding)
for _, indexInfo := range indexInfoList {
embedding := toVectorEmbedding(indexInfo, params)
if len(embedding.Embedding) == 0 {
log.Warnf("[TencentVectorDB] skip empty embedding for chunk_id=%s", indexInfo.ChunkID)
continue
}
dim := len(embedding.Embedding)
embeddingsByDimension[dim] = append(embeddingsByDimension[dim], embedding)
}
if len(embeddingsByDimension) == 0 {
return nil
}
bm25, err := r.bm25Encoder()
if err != nil {
return err
}
buildIndex := true
for dim, embeddings := range embeddingsByDimension {
docs, err := r.toDocumentsWithSparseVectors(bm25, embeddings)
if err != nil {
return err
}
if err := r.ensureCollection(ctx, dim); err != nil {
return err
}
collectionName := r.collectionName(dim)
_, err = r.client.Database(r.databaseName).Collection(collectionName).Upsert(
ctx,
docs,
&tcvectordb.UpsertDocumentParams{BuildIndex: &buildIndex},
)
if err != nil {
return fmt.Errorf("tencent vectordb batch save %s: %w", collectionName, err)
}
}
return nil
}
func (r *repository) EstimateStorageSize(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) int64 {
var total int64
for _, indexInfo := range indexInfoList {
embedding := toVectorEmbedding(indexInfo, params)
total += int64(len(embedding.Content))
total += int64(len(embedding.Embedding) * 4)
total += int64(len(embedding.Content) * 2)
total += int64(len(embedding.SourceID) + len(embedding.ChunkID) + len(embedding.KnowledgeID) + len(embedding.KnowledgeBaseID) + 256)
}
logger.GetLogger(ctx).Infof("[TencentVectorDB] estimated storage size for %d indices: %d bytes", len(indexInfoList), total)
return total
}
func (r *repository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int, knowledgeType string) error {
return r.deleteByFilter(ctx, dimension, tcvectordb.In(fieldChunkID, chunkIDList))
}
func (r *repository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int, knowledgeType string) error {
return r.deleteByFilter(ctx, dimension, tcvectordb.In(fieldSourceID, sourceIDList))
}
func (r *repository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int, knowledgeType string) error {
return r.deleteByFilter(ctx, dimension, tcvectordb.In(fieldKnowledgeID, knowledgeIDList))
}
func (r *repository) CopyIndices(
ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
knowledgeType string,
) error {
if len(sourceToTargetChunkIDMap) == 0 {
return nil
}
collectionName := r.collectionName(dimension)
ids := slices.Collect(maps.Keys(sourceToTargetChunkIDMap))
var embeddings []*vectorEmbedding
for offset := int64(0); ; offset += copyIndicesQueryPageSize {
query, err := r.client.Database(r.databaseName).Collection(collectionName).Query(
ctx,
nil,
copySourceQueryParams(sourceKnowledgeBaseID, ids, offset),
)
if err != nil {
return fmt.Errorf("tencent vectordb query source indices: %w", err)
}
embeddings = append(embeddings, remapCopiedEmbeddings(
query.Documents,
sourceToTargetKBIDMap,
sourceToTargetChunkIDMap,
targetKnowledgeBaseID,
)...)
if len(query.Documents) < int(copyIndicesQueryPageSize) {
break
}
}
if len(embeddings) == 0 {
return nil
}
bm25, err := r.bm25Encoder()
if err != nil {
return err
}
docs, err := r.toDocumentsWithSparseVectors(bm25, embeddings)
if err != nil {
return err
}
buildIndex := true
_, err = r.client.Database(r.databaseName).Collection(collectionName).Upsert(
ctx,
docs,
&tcvectordb.UpsertDocumentParams{BuildIndex: &buildIndex},
)
if err != nil {
return fmt.Errorf("tencent vectordb copy indices: %w", err)
}
return nil
}
func (r *repository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
if len(chunkStatusMap) == 0 {
return nil
}
grouped := make(map[bool][]string)
for chunkID, enabled := range chunkStatusMap {
grouped[enabled] = append(grouped[enabled], chunkID)
}
for enabled, chunkIDs := range grouped {
if err := r.updateChunkFields(ctx, chunkIDs, map[string]tcvectordb.Field{fieldIsEnabled: {Val: boolToUint64(enabled)}}); err != nil {
return err
}
}
return nil
}
func (r *repository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
if len(chunkTagMap) == 0 {
return nil
}
grouped := make(map[string][]string)
for chunkID, tagID := range chunkTagMap {
grouped[tagID] = append(grouped[tagID], chunkID)
}
for tagID, chunkIDs := range grouped {
if err := r.updateChunkFields(ctx, chunkIDs, map[string]tcvectordb.Field{fieldTagID: {Val: tagID}}); err != nil {
return err
}
}
return nil
}
func (r *repository) Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
switch params.RetrieverType {
case types.VectorRetrieverType:
return r.VectorRetrieve(ctx, params)
case types.KeywordsRetrieverType:
return r.KeywordsRetrieve(ctx, params)
default:
return nil, fmt.Errorf("invalid retriever type: %s", params.RetrieverType)
}
}
func (r *repository) VectorRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
dimension := len(params.Embedding)
if dimension == 0 {
return r.retrieveResult(nil, types.VectorRetrieverType), nil
}
collectionName := r.collectionName(dimension)
exists, err := r.client.Database(r.databaseName).ExistsCollection(ctx, collectionName)
if err != nil {
return nil, fmt.Errorf("tencent vectordb check collection %s: %w", collectionName, err)
}
if !exists {
return r.retrieveResult(nil, types.VectorRetrieverType), nil
}
limit := int64(params.TopK)
if limit <= 0 {
limit = 10
}
searchParams := &tcvectordb.SearchDocumentParams{
Filter: r.baseFilter(params),
// HNSW returns at most ef candidates; a fixed 100 capped recall
// below TopK, which reaches 500.
Params: &tcvectordb.SearchDocParams{Ef: uint32(max(limit, 100))},
RetrieveVector: false,
OutputFields: outputFields(),
Limit: limit,
}
if params.Threshold > 0 {
radius := float32(params.Threshold)
searchParams.Radius = &radius
}
search, err := r.client.Database(r.databaseName).Collection(collectionName).Search(ctx, [][]float32{params.Embedding}, searchParams)
if err != nil {
return nil, fmt.Errorf("tencent vectordb vector search %s: %w", collectionName, err)
}
if len(search.Documents) == 0 {
return r.retrieveResult(nil, types.VectorRetrieverType), nil
}
results := make([]*types.IndexWithScore, 0, len(search.Documents[0]))
for _, doc := range search.Documents[0] {
embedding := fromDocument(doc)
results = append(results, toIndexWithScore(embedding, types.MatchTypeEmbedding))
}
return r.retrieveResult(results, types.VectorRetrieverType), nil
}
func (r *repository) KeywordsRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
log := logger.GetLogger(ctx)
query := strings.TrimSpace(params.Query)
if query == "" {
return r.retrieveResult(nil, types.KeywordsRetrieverType), nil
}
bm25, err := r.bm25Encoder()
if err != nil {
return nil, err
}
queryVectors, err := bm25.EncodeQueries([]string{query})
if err != nil {
return nil, fmt.Errorf("tencent vectordb encode keyword query: %w", err)
}
if len(queryVectors) == 0 || len(queryVectors[0]) == 0 {
return r.retrieveResult(nil, types.KeywordsRetrieverType), nil
}
collections, err := r.client.Database(r.databaseName).ListCollection(ctx)
if err != nil {
return nil, fmt.Errorf("tencent vectordb list collections: %w", err)
}
limit := params.TopK
if limit <= 0 {
limit = 10
}
results := make([]*types.IndexWithScore, 0, limit)
matchedCollections := 0
failedCollections := 0
for _, collection := range collections.Collections {
if !r.matchesCollection(collection.CollectionName) {
continue
}
matchedCollections++
search, err := r.client.Database(r.databaseName).Collection(collection.CollectionName).FullTextSearch(
ctx,
tcvectordb.FullTextSearchParams{
Filter: r.baseFilter(params),
RetrieveVector: false,
OutputFields: outputFields(),
Limit: &limit,
Match: &tcvectordb.FullTextSearchMatchOption{
FieldName: fieldSparseVector,
Data: queryVectors,
},
},
)
if err != nil {
failedCollections++
log.Warnf("[TencentVectorDB] keyword search failed in %s: %v", collection.CollectionName, err)
continue
}
if len(search.Documents) == 0 {
continue
}
for _, doc := range search.Documents[0] {
embedding := fromDocument(doc)
results = append(results, toIndexWithScore(embedding, types.MatchTypeKeywords))
}
}
if matchedCollections > 0 && failedCollections == matchedCollections {
return nil, fmt.Errorf("tencent vectordb keyword search failed in all matched collections; ensure collections have the %q sparse vector index and reimport data if they were created before keyword support", fieldSparseVector)
}
sort.SliceStable(results, func(i, j int) bool {
return results[i].Score > results[j].Score
})
if len(results) > limit {
results = results[:limit]
}
return r.retrieveResult(results, types.KeywordsRetrieverType), nil
}
func (r *repository) ensureCollection(ctx context.Context, dimension int) error {
if _, ok := r.initialized.Load(dimension); ok {
return nil
}
if _, err := r.client.CreateDatabaseIfNotExists(ctx, r.databaseName); err != nil {
return fmt.Errorf("tencent vectordb ensure database %s: %w", r.databaseName, err)
}
collectionName := r.collectionName(dimension)
exists, err := r.client.Database(r.databaseName).ExistsCollection(ctx, collectionName)
if err != nil {
return fmt.Errorf("tencent vectordb check collection %s: %w", collectionName, err)
}
if exists {
r.initialized.Store(dimension, true)
return nil
}
indexes := tcvectordb.Indexes{
VectorIndex: []tcvectordb.VectorIndex{
{
FilterIndex: tcvectordb.FilterIndex{
FieldName: fieldVector,
FieldType: tcvectordb.Vector,
IndexType: tcvectordb.HNSW,
},
Dimension: uint32(dimension),
MetricType: tcvectordb.COSINE,
Params: &tcvectordb.HNSWParam{
M: 16,
EfConstruction: 200,
},
},
},
SparseVectorIndex: []tcvectordb.SparseVectorIndex{
{
FieldName: fieldSparseVector,
FieldType: tcvectordb.SparseVector,
IndexType: tcvectordb.SPARSE_INVERTED,
MetricType: tcvectordb.IP,
},
},
FilterIndex: []tcvectordb.FilterIndex{
{FieldName: fieldID, FieldType: tcvectordb.String, IndexType: tcvectordb.PRIMARY},
{FieldName: fieldContent, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
{FieldName: fieldSourceID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
{FieldName: fieldSourceType, FieldType: tcvectordb.Uint64, IndexType: tcvectordb.FILTER},
{FieldName: fieldChunkID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
{FieldName: fieldKnowledgeID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
{FieldName: fieldKnowledgeBaseID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
{FieldName: fieldTagID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
{FieldName: fieldIsEnabled, FieldType: tcvectordb.Uint64, IndexType: tcvectordb.FILTER},
},
}
_, err = r.client.Database(r.databaseName).CreateCollection(
ctx,
collectionName,
uint32(r.shardsNum),
uint32(r.replicasNum),
fmt.Sprintf("Academy embeddings collection with dimension %d", dimension),
indexes,
)
if err != nil {
if isCollectionAlreadyExistsErr(err) {
logger.GetLogger(ctx).Infof("[TencentVectorDB] collection %s already exists, skip create", collectionName)
r.initialized.Store(dimension, true)
return nil
}
return fmt.Errorf("tencent vectordb create collection %s: %w", collectionName, err)
}
r.initialized.Store(dimension, true)
return nil
}
func isCollectionAlreadyExistsErr(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "code: 15202") || strings.Contains(msg, "already exist")
}
func (r *repository) deleteByFilter(ctx context.Context, dimension int, cond string) error {
if cond == "" {
return nil
}
collectionName := r.collectionName(dimension)
_, err := r.client.Database(r.databaseName).Collection(collectionName).Delete(ctx, tcvectordb.DeleteDocumentParams{
Filter: tcvectordb.NewFilter(cond),
})
if err != nil {
return fmt.Errorf("tencent vectordb delete from %s: %w", collectionName, err)
}
return nil
}
func (r *repository) updateChunkFields(ctx context.Context, chunkIDs []string, fields map[string]tcvectordb.Field) error {
collections, err := r.client.Database(r.databaseName).ListCollection(ctx)
if err != nil {
return fmt.Errorf("tencent vectordb list collections: %w", err)
}
for _, collection := range collections.Collections {
if !r.matchesCollection(collection.CollectionName) {
continue
}
_, err := r.client.Database(r.databaseName).Collection(collection.CollectionName).Update(ctx, tcvectordb.UpdateDocumentParams{
QueryFilter: tcvectordb.NewFilter(tcvectordb.In(fieldChunkID, chunkIDs)),
UpdateFields: fields,
})
if err != nil {
return fmt.Errorf("tencent vectordb update chunks in %s: %w", collection.CollectionName, err)
}
}
return nil
}
func (r *repository) collectionName(dimension int) string {
if !r.useDimensionSuffix {
return r.collectionBaseName
}
return fmt.Sprintf("%s_%d", r.collectionBaseName, dimension)
}
func (r *repository) matchesCollection(collectionName string) bool {
if !r.useDimensionSuffix {
return collectionName == r.collectionBaseName
}
return strings.HasPrefix(collectionName, r.collectionBaseName+"_")
}
func shouldUseDimensionSuffix(indexCfg *types.IndexConfig) bool {
return indexCfg == nil || indexCfg.CollectionName == ""
}
func (r *repository) baseFilter(params types.RetrieveParams) *tcvectordb.Filter {
conditions := []string{fmt.Sprintf("%s=1", fieldIsEnabled)}
if len(params.KnowledgeBaseIDs) > 0 {
conditions = append(conditions, tcvectordb.In(fieldKnowledgeBaseID, params.KnowledgeBaseIDs))
}
if len(params.KnowledgeIDs) > 0 {
conditions = append(conditions, tcvectordb.In(fieldKnowledgeID, params.KnowledgeIDs))
}
if len(params.TagIDs) > 0 {
conditions = append(conditions, tcvectordb.In(fieldTagID, params.TagIDs))
}
if len(params.ExcludeKnowledgeIDs) > 0 {
conditions = append(conditions, tcvectordb.NotIn(fieldKnowledgeID, params.ExcludeKnowledgeIDs))
}
if len(params.ExcludeChunkIDs) > 0 {
conditions = append(conditions, tcvectordb.NotIn(fieldChunkID, params.ExcludeChunkIDs))
}
return tcvectordb.NewFilter(strings.Join(conditions, " and "))
}
func (r *repository) retrieveResult(results []*types.IndexWithScore, retrieverType types.RetrieverType) []*types.RetrieveResult {
return []*types.RetrieveResult{
{
Results: results,
RetrieverEngineType: types.TencentVectorDBRetrieverEngineType,
RetrieverType: retrieverType,
},
}
}
func (r *repository) bm25Encoder() (encoder.SparseEncoder, error) {
r.bm25Once.Do(func() {
r.bm25, r.bm25Err = encoder.NewBM25Encoder(&encoder.BM25EncoderParams{
Bm25Language: encoder.BM25_ZH_CONTENT,
})
if r.bm25Err != nil {
r.bm25Err = fmt.Errorf("tencent vectordb init BM25 encoder: %w", r.bm25Err)
}
})
return r.bm25, r.bm25Err
}
func (r *repository) toDocumentsWithSparseVectors(
bm25 encoder.SparseEncoder,
embeddings []*vectorEmbedding,
) ([]tcvectordb.Document, error) {
texts := make([]string, 0, len(embeddings))
for _, embedding := range embeddings {
texts = append(texts, embedding.Content)
}
sparseVectors, err := bm25.EncodeTexts(texts)
if err != nil {
return nil, fmt.Errorf("tencent vectordb encode BM25 sparse vectors: %w", err)
}
docs := make([]tcvectordb.Document, 0, len(embeddings))
for i, embedding := range embeddings {
if i >= len(sparseVectors) {
return nil, fmt.Errorf("tencent vectordb encoded sparse vector count mismatch: got %d, want %d", len(sparseVectors), len(embeddings))
}
embedding.SparseVector = sparseVectors[i]
docs = append(docs, toDocument(embedding))
}
return docs, nil
}
func toVectorEmbedding(indexInfo *types.IndexInfo, params map[string]any) *vectorEmbedding {
embedding := &vectorEmbedding{
ID: indexInfo.ID,
Content: cleanInvalidUTF8(indexInfo.Content),
SourceID: indexInfo.SourceID,
SourceType: int(indexInfo.SourceType),
ChunkID: indexInfo.ChunkID,
KnowledgeID: indexInfo.KnowledgeID,
KnowledgeBaseID: indexInfo.KnowledgeBaseID,
TagID: indexInfo.TagID,
IsEnabled: indexInfo.IsEnabled,
}
if embedding.ID == "" {
embedding.ID = indexInfo.SourceID
}
if embedding.ID == "" {
embedding.ID = indexInfo.ChunkID
}
if params != nil && slices.Contains(slices.Collect(maps.Keys(params)), fieldVector) {
if embeddingMap, ok := params[fieldVector].(map[string][]float32); ok {
embedding.Embedding = lookupEmbedding(embeddingMap, indexInfo)
}
}
if params != nil && slices.Contains(slices.Collect(maps.Keys(params)), "embedding") {
if embeddingMap, ok := params["embedding"].(map[string][]float32); ok {
embedding.Embedding = lookupEmbedding(embeddingMap, indexInfo)
}
}
return embedding
}
func lookupEmbedding(embeddingMap map[string][]float32, indexInfo *types.IndexInfo) []float32 {
if embedding, ok := embeddingMap[indexInfo.SourceID]; ok {
return embedding
}
return embeddingMap[indexInfo.ChunkID]
}
func copySourceQueryParams(sourceKnowledgeBaseID string, chunkIDs []string, offset int64) *tcvectordb.QueryDocumentParams {
conditions := []string{tcvectordb.In(fieldChunkID, chunkIDs)}
if sourceKnowledgeBaseID != "" {
conditions = append([]string{tcvectordb.In(fieldKnowledgeBaseID, []string{sourceKnowledgeBaseID})}, conditions...)
}
return &tcvectordb.QueryDocumentParams{
Filter: tcvectordb.NewFilter(strings.Join(conditions, " and ")),
RetrieveVector: true,
OutputFields: outputFields(),
Offset: offset,
Limit: copyIndicesQueryPageSize,
}
}
func remapCopiedEmbeddings(
docs []tcvectordb.Document,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
) []*vectorEmbedding {
embeddings := make([]*vectorEmbedding, 0, len(docs))
for _, doc := range docs {
embedding := fromDocument(doc)
targetChunkID := sourceToTargetChunkIDMap[embedding.ChunkID]
if targetChunkID == "" {
continue
}
originalSourceID := embedding.SourceID
if originalSourceID == "" {
originalSourceID = embedding.ID
}
targetSourceID := translateSourceID(originalSourceID, embedding.ChunkID, targetChunkID)
embedding.ID = targetSourceID
embedding.SourceID = targetSourceID
embedding.ChunkID = targetChunkID
embedding.KnowledgeBaseID = targetKnowledgeBaseID
if targetKBID := sourceToTargetKBIDMap[embedding.KnowledgeID]; targetKBID != "" {
embedding.KnowledgeID = targetKBID
}
embeddings = append(embeddings, embedding)
}
return embeddings
}
func translateSourceID(originalSourceID, sourceChunkID, targetChunkID string) string {
switch {
case originalSourceID == sourceChunkID:
return targetChunkID
case strings.HasPrefix(originalSourceID, sourceChunkID+"-"):
questionID := strings.TrimPrefix(originalSourceID, sourceChunkID+"-")
return fmt.Sprintf("%s-%s", targetChunkID, questionID)
default:
sum := sha256.Sum256([]byte(targetChunkID + "\x00" + sourceChunkID + "\x00" + originalSourceID))
return fmt.Sprintf("%s-%s", targetChunkID, hex.EncodeToString(sum[:])[:16])
}
}
func cleanInvalidUTF8(s string) string {
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
i++
continue
}
if r == 0 {
i += size
continue
}
b.WriteRune(r)
i += size
}
return b.String()
}
func toDocument(embedding *vectorEmbedding) tcvectordb.Document {
return tcvectordb.Document{
Id: embedding.ID,
Vector: embedding.Embedding,
SparseVector: embedding.SparseVector,
Fields: map[string]tcvectordb.Field{
fieldContent: {Val: embedding.Content},
fieldSourceID: {Val: embedding.SourceID},
fieldSourceType: {Val: uint64(embedding.SourceType)},
fieldChunkID: {Val: embedding.ChunkID},
fieldKnowledgeID: {Val: embedding.KnowledgeID},
fieldKnowledgeBaseID: {Val: embedding.KnowledgeBaseID},
fieldTagID: {Val: embedding.TagID},
fieldIsEnabled: {Val: boolToUint64(embedding.IsEnabled)},
},
}
}
func fromDocument(doc tcvectordb.Document) *vectorEmbedding {
return &vectorEmbedding{
ID: doc.Id,
Content: fieldString(doc, fieldContent),
SourceID: fieldString(doc, fieldSourceID),
SourceType: int(fieldUint64(doc, fieldSourceType)),
ChunkID: fieldString(doc, fieldChunkID),
KnowledgeID: fieldString(doc, fieldKnowledgeID),
KnowledgeBaseID: fieldString(doc, fieldKnowledgeBaseID),
TagID: fieldString(doc, fieldTagID),
Embedding: doc.Vector,
SparseVector: doc.SparseVector,
IsEnabled: fieldUint64(doc, fieldIsEnabled) == 1,
Score: float64(doc.Score),
}
}
func toIndexWithScore(embedding *vectorEmbedding, matchType types.MatchType) *types.IndexWithScore {
return &types.IndexWithScore{
ID: embedding.ID,
Content: embedding.Content,
SourceID: embedding.SourceID,
SourceType: types.SourceType(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
TagID: embedding.TagID,
Score: embedding.Score,
MatchType: matchType,
IsEnabled: embedding.IsEnabled,
}
}
func outputFields() []string {
return []string{
fieldID,
fieldContent,
fieldSourceID,
fieldSourceType,
fieldChunkID,
fieldKnowledgeID,
fieldKnowledgeBaseID,
fieldTagID,
fieldIsEnabled,
}
}
func fieldString(doc tcvectordb.Document, name string) string {
field, ok := doc.Fields[name]
if !ok {
return ""
}
return field.String()
}
func fieldUint64(doc tcvectordb.Document, name string) uint64 {
field, ok := doc.Fields[name]
if !ok {
return 0
}
return field.Uint64()
}
func boolToUint64(v bool) uint64 {
if v {
return 1
}
return 0
}
func defaultIfZero(v, def int) int {
if v <= 0 {
return def
}
return v
}
@@ -0,0 +1,125 @@
package tencentvectordb
import (
"errors"
"strings"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/tencent/vectordatabase-sdk-go/tcvdbtext/encoder"
)
func TestSupportIncludesKeywordAndVectorRetrieval(t *testing.T) {
repo := NewTencentVectorDBRetrieveEngineRepository(nil, "", nil)
supports := repo.Support()
assert.Contains(t, supports, types.KeywordsRetrieverType)
assert.Contains(t, supports, types.VectorRetrieverType)
}
func TestToDocumentIncludesSparseVector(t *testing.T) {
embedding := &vectorEmbedding{
ID: "chunk-1",
Content: "腾讯云向量数据库支持关键词检索",
SourceID: "source-1",
SourceType: int(types.ChunkSourceType),
ChunkID: "chunk-1",
KnowledgeID: "knowledge-1",
KnowledgeBaseID: "kb-1",
TagID: "tag-1",
Embedding: []float32{0.1, 0.2},
SparseVector: []encoder.SparseVecItem{
{TermId: 10, Score: 0.3},
{TermId: 20, Score: 0.7},
},
IsEnabled: true,
}
doc := toDocument(embedding)
assert.Equal(t, embedding.ID, doc.Id)
assert.Equal(t, embedding.Embedding, doc.Vector)
assert.Equal(t, embedding.SparseVector, doc.SparseVector)
assert.Equal(t, "腾讯云向量数据库支持关键词检索", doc.Fields[fieldContent].String())
assert.Equal(t, uint64(1), doc.Fields[fieldIsEnabled].Uint64())
}
func TestBaseFilterBuildsTencentVectorDBCondition(t *testing.T) {
repo := &repository{}
filter := repo.baseFilter(types.RetrieveParams{
KnowledgeBaseIDs: []string{"kb-1"},
KnowledgeIDs: []string{"knowledge-1", "knowledge-2"},
TagIDs: []string{"tag-1"},
ExcludeKnowledgeIDs: []string{"knowledge-9"},
ExcludeChunkIDs: []string{"chunk-9"},
})
cond := filter.Cond()
for _, want := range []string{
"is_enabled=1",
"knowledge_base_id in (\"kb-1\")",
"knowledge_id in (\"knowledge-1\",\"knowledge-2\")",
"tag_id in (\"tag-1\")",
"knowledge_id not in (\"knowledge-9\")",
"chunk_id not in (\"chunk-9\")",
} {
assert.True(t, strings.Contains(cond, want), "condition %q should contain %q", cond, want)
}
}
func TestTencentVectorDBDefaultsToReplicaNumberOne(t *testing.T) {
repo := NewTencentVectorDBRetrieveEngineRepository(nil, "", nil).(*repository)
assert.Equal(t, 1, repo.replicasNum)
}
func TestTencentVectorDBUsesEnvReplicaNumber(t *testing.T) {
t.Setenv(envTencentVectorDBReplicaNum, "0")
repo := NewTencentVectorDBRetrieveEngineRepository(nil, "", nil).(*repository)
assert.Equal(t, 0, repo.replicasNum)
}
func TestTencentVectorDBUsesPositiveEnvReplicaNumber(t *testing.T) {
t.Setenv(envTencentVectorDBReplicaNum, "3")
repo := NewTencentVectorDBRetrieveEngineRepository(nil, "", nil).(*repository)
assert.Equal(t, 3, repo.replicasNum)
}
func TestTencentVectorDBUsesConfiguredReplicaNumber(t *testing.T) {
t.Setenv(envTencentVectorDBReplicaNum, "0")
repo := NewTencentVectorDBRetrieveEngineRepository(nil, "", &types.IndexConfig{
ReplicaNumber: 2,
}).(*repository)
assert.Equal(t, 2, repo.replicasNum)
}
func TestCollectionNameUsesDimensionSuffixByDefault(t *testing.T) {
repo := NewTencentVectorDBRetrieveEngineRepository(nil, "", nil).(*repository)
assert.Equal(t, "academy_embeddings_1024", repo.collectionName(1024))
assert.True(t, repo.matchesCollection("academy_embeddings_1024"))
assert.False(t, repo.matchesCollection("academy_embeddings"))
}
func TestCollectionNameRespectsExplicitCollectionName(t *testing.T) {
repo := NewTencentVectorDBRetrieveEngineRepository(nil, "", &types.IndexConfig{
CollectionName: "custom_collection",
}).(*repository)
assert.Equal(t, "custom_collection", repo.collectionName(1024))
assert.True(t, repo.matchesCollection("custom_collection"))
assert.False(t, repo.matchesCollection("custom_collection_1024"))
}
func TestCollectionAlreadyExistsErrorDetection(t *testing.T) {
assert.True(t, isCollectionAlreadyExistsErr(errors.New("code: 15202, collection already exists")))
assert.True(t, isCollectionAlreadyExistsErr(errors.New("Collection Already Exist")))
assert.False(t, isCollectionAlreadyExistsErr(errors.New("permission denied")))
assert.False(t, isCollectionAlreadyExistsErr(nil))
}
@@ -0,0 +1,57 @@
package tencentvectordb
import (
"sync"
"github.com/tencent/vectordatabase-sdk-go/tcvdbtext/encoder"
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
)
const (
envTencentVectorDBDatabase = "TENCENT_VECTORDB_DATABASE"
envTencentVectorDBCollection = "TENCENT_VECTORDB_COLLECTION"
envTencentVectorDBReplicaNum = "TENCENT_VECTORDB_REPLICA_NUMBER"
defaultDatabaseName = "academy"
defaultCollectionName = "academy_embeddings"
defaultReplicaNumber = 1
fieldID = "id"
fieldVector = "vector"
fieldSparseVector = "sparse_vector"
fieldContent = "content"
fieldSourceID = "source_id"
fieldSourceType = "source_type"
fieldChunkID = "chunk_id"
fieldKnowledgeID = "knowledge_id"
fieldKnowledgeBaseID = "knowledge_base_id"
fieldTagID = "tag_id"
fieldIsEnabled = "is_enabled"
)
type repository struct {
client *tcvectordb.RpcClient
databaseName string
collectionBaseName string
useDimensionSuffix bool
shardsNum int
replicasNum int
initialized sync.Map
bm25Once sync.Once
bm25 encoder.SparseEncoder
bm25Err error
}
type vectorEmbedding struct {
ID string
Content string
SourceID string
SourceType int
ChunkID string
KnowledgeID string
KnowledgeBaseID string
TagID string
Embedding []float32
SparseVector []encoder.SparseVecItem
IsEnabled bool
Score float64
}
@@ -0,0 +1,503 @@
package weaviate
import (
"context"
"encoding/json"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/weaviate/weaviate-go-client/v5/weaviate"
)
const copyTestCollection = "Copy_64"
// cursorConflictMessage is what weaviate v1.37.3 answers when a Get combines a
// filter with the cursor API (entities/filters/cursor_validator.go).
const cursorConflictMessage = "where cannot be set with after and limit parameters"
var (
afterArgPattern = regexp.MustCompile(`after:\s*"([^"]*)"`)
limitArgPattern = regexp.MustCompile(`limit:\s*(\d+)`)
chunkArgPattern = regexp.MustCompile(`path: \["chunk_id"\] valueText: \[([^\]]*)\]`)
quotedPattern = regexp.MustCompile(`"([^"]*)"`)
)
// copySourceRow is one source vector, in the shape a GraphQL Get answers with.
func copySourceRow(id, chunkID, sourceID string) map[string]any {
return map[string]any{
fieldContent: "content of " + sourceID,
fieldSourceID: sourceID,
fieldSourceType: 1,
fieldChunkID: chunkID,
fieldKnowledgeID: "know-1",
fieldKnowledgeBaseID: "kb-src",
fieldTagID: "",
"_additional": map[string]any{"id": id, "vector": []any{0.5, 0.25}},
}
}
// copyWrittenObject is one object the copy sent to the batch endpoint.
type copyWrittenObject struct {
sourceID string
targetChunkID string
}
// copyPageServer stands in for a Weaviate data node holding the source
// vectors. It answers Get the way the real one does - with the rows whose
// chunk_id is in the ContainsAny list the query asked for, cut off at the
// query's limit - and it validates the cursor API the way the real one does,
// so a query that combines `where` with `after` fails here exactly as it fails
// in production.
type copyPageServer struct {
mu sync.Mutex
// rows holds each chunk's vectors: one for the chunk content plus one per
// generated question, all sharing the chunk_id.
rows map[string][]map[string]any
order []string
// queryLimit is the server's QUERY_MAXIMUM_RESULTS; 0 means no refusal.
queryLimit int
// ignoreChunkFilter answers every query with the same page, the way a
// source whose pages repeat themselves behaves.
ignoreChunkFilter bool
// queryError, when set, is the GraphQL error every Get is answered with.
queryError string
// omitData answers every Get with a data object that carries no Get key.
omitData bool
// omitCollection answers with a Get object that carries no key for the
// queried collection.
omitCollection bool
queries int
limits []int
requested [][]string
rejected []string
batches int
written []copyWrittenObject
unexpected []string
}
// copyTestStore builds a source whose chunks hold the given vectors. Each
// entry maps a chunk ID to its source IDs: the chunk's own content vector
// first, then one per generated question.
func copyTestStore(vectors map[string][]string) *copyPageServer {
s := &copyPageServer{rows: make(map[string][]map[string]any)}
next := 0
for _, chunkID := range slices.Sorted(maps.Keys(vectors)) {
for _, sourceID := range vectors[chunkID] {
s.rows[chunkID] = append(s.rows[chunkID], copySourceRow(copyTestUUID(next), chunkID, sourceID))
next++
}
s.order = append(s.order, chunkID)
}
return s
}
func copyTestUUID(i int) string {
return fmt.Sprintf("00000000-0000-0000-0000-%012d", i)
}
// copyTestChunkMap maps size chunks onto target chunks.
func copyTestChunkMap(size int) map[string]string {
m := make(map[string]string, size)
for i := range size {
m[fmt.Sprintf("chunk-%d", i)] = fmt.Sprintf("target-chunk-%d", i)
}
return m
}
// copyTestSingleVectorChunks builds a source with one vector per named chunk.
func copyTestSingleVectorChunks(chunkIDs ...string) *copyPageServer {
vectors := make(map[string][]string, len(chunkIDs))
for _, chunkID := range chunkIDs {
vectors[chunkID] = []string{chunkID}
}
return copyTestStore(vectors)
}
// serve starts an httptest server for s and returns a repository pointed at
// it. The copy's own query limit is left at its default; tests that need the
// truncation path lower it on the returned repository.
func (s *copyPageServer) serve(t *testing.T) *weaviateRepository {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(s.handle))
t.Cleanup(server.Close)
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
require.NoError(t, err)
return &weaviateRepository{client: client, collectionBaseName: "Copy"}
}
func (s *copyPageServer) handle(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodPost && r.URL.Path == "/v1/graphql":
var body struct {
Query string `json:"query"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
_ = json.NewEncoder(w).Encode(s.resolve(body.Query))
case r.Method == http.MethodPost && r.URL.Path == "/v1/batch/objects":
var body struct {
Objects []struct {
Properties map[string]any `json:"properties"`
} `json:"objects"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
s.mu.Lock()
s.batches++
for _, obj := range body.Objects {
s.written = append(s.written, copyWrittenObject{
sourceID: fmt.Sprint(obj.Properties[fieldSourceID]),
targetChunkID: fmt.Sprint(obj.Properties[fieldChunkID]),
})
}
s.mu.Unlock()
_, _ = w.Write([]byte(`[]`))
case r.Method == http.MethodGet && r.URL.Path == "/v1/meta":
_, _ = w.Write([]byte(`{"version":"1.37.3"}`))
default:
s.mu.Lock()
s.unexpected = append(s.unexpected, r.Method+" "+r.URL.Path)
s.mu.Unlock()
w.WriteHeader(http.StatusNotFound)
}
}
// resolve answers one GraphQL Get the way Weaviate does. A query it refused
// comes back as a successful call carrying an errors array, which is what the
// copy has to read as a failure.
func (s *copyPageServer) resolve(query string) map[string]any {
s.mu.Lock()
defer s.mu.Unlock()
s.queries++
limit := 0
if match := limitArgPattern.FindStringSubmatch(query); match != nil {
limit, _ = strconv.Atoi(match[1])
}
s.limits = append(s.limits, limit)
// The cursor API refuses a filtered query: a Get that asks for rows after a
// cursor cannot also carry where and limit.
if strings.Contains(query, "where:") {
if afterArgPattern.MatchString(query) {
s.rejected = append(s.rejected, query)
return graphQLError("cursor api: invalid 'after' parameter: " + cursorConflictMessage)
}
}
switch {
case s.queryError != "":
return graphQLError(s.queryError)
case s.omitData:
return map[string]any{"data": map[string]any{}}
case s.omitCollection:
return map[string]any{"data": map[string]any{"Get": map[string]any{}}}
}
if s.queryLimit > 0 && limit > s.queryLimit {
return graphQLError(fmt.Sprintf(
"query maximum results exceeded: the total limit calculated from the provided offset '0' "+
"and limit '%d' exceeds the configured value for QUERY_MAXIMUM_RESULTS '%d'. "+
"If you've supplied a negative offset or limit, this may be an underflow error",
limit, s.queryLimit))
}
chunkIDs := copyRequestedChunkIDs(query)
s.requested = append(s.requested, chunkIDs)
order := chunkIDs
if s.ignoreChunkFilter {
order = s.order
}
rows := make([]any, 0, len(s.rows))
for _, chunkID := range order {
for _, row := range s.rows[chunkID] {
rows = append(rows, row)
}
}
if limit > 0 && len(rows) > limit {
rows = rows[:limit]
}
return map[string]any{"data": map[string]any{"Get": map[string]any{copyTestCollection: rows}}}
}
func graphQLError(message string) map[string]any {
return map[string]any{"errors": []any{map[string]any{"message": message}}}
}
// copyRequestedChunkIDs pulls the chunk_id ContainsAny values out of a query.
func copyRequestedChunkIDs(query string) []string {
match := chunkArgPattern.FindStringSubmatch(query)
if match == nil {
return nil
}
var ids []string
for _, quoted := range quotedPattern.FindAllStringSubmatch(match[1], -1) {
ids = append(ids, quoted[1])
}
return ids
}
func (s *copyPageServer) queryCount() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.queries
}
func (s *copyPageServer) queryLimits() []int {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Clone(s.limits)
}
func (s *copyPageServer) requestedBatches() [][]string {
s.mu.Lock()
defer s.mu.Unlock()
batches := make([][]string, 0, len(s.requested))
for _, batch := range s.requested {
batches = append(batches, slices.Clone(batch))
}
return batches
}
func (s *copyPageServer) writtenObjects() []copyWrittenObject {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Clone(s.written)
}
func (s *copyPageServer) summary() string {
s.mu.Lock()
defer s.mu.Unlock()
return fmt.Sprintf("queries=%d limits=%v batches-requested=%v objects-written=%d refused-cursor-combos=%d",
s.queries, s.limits, s.requested, len(s.written), len(s.rejected))
}
// check states the invariants every copy test depends on: no Get ever combined
// where with after, and every Get named the chunk IDs it wanted.
func (s *copyPageServer) check(t *testing.T) {
t.Helper()
s.mu.Lock()
defer s.mu.Unlock()
assert.Empty(t, s.rejected, "a source query combined where with after; weaviate refuses that")
assert.Empty(t, s.unexpected, "the copy called an endpoint it should not have")
for i, batch := range s.requested {
assert.NotEmpty(t, batch, "query %d did not name the chunks it wanted", i)
}
}
// copyTestRun copies mapping from the fake source and logs what the source saw.
func copyTestRun(t *testing.T, source *copyPageServer, repo *weaviateRepository, mapping map[string]string) error {
t.Helper()
defer func() { t.Log("copy walk: " + source.summary()) }()
defer source.check(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return repo.CopyIndices(ctx, "kb-src", map[string]string{"know-1": "know-2"}, mapping, "kb-dst", 64, "doc")
}
// CopyIndices has to read the source by the chunk IDs the mapping names. A
// filtered Get that carries `after` is refused by Weaviate ("where cannot be
// set with after and limit parameters"), which the cursor walk this replaces
// provoked on its very first page, and the fake server refuses it the same way.
func TestCopyIndicesQueriesByChunkIDWithoutACursor(t *testing.T) {
const chunks = 130 // 64 + 64 + 2: more than one batch, one short batch
source := copyTestSingleVectorChunks(keysOf(copyTestChunkMap(chunks))...)
repo := source.serve(t)
require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(chunks)))
assert.Equal(t, 3, source.queryCount(), "130 mapped chunks are read as three batches")
assert.Equal(t, 130, len(source.writtenObjects()), "every mapped chunk must be copied")
assert.ElementsMatch(t, []int{64, 64, 2}, batchSizes(source.requestedBatches()),
"each read asks for one batch of the mapping")
var read []string
for _, batch := range source.requestedBatches() {
assert.True(t, slices.IsSorted(batch), "a batch is read in mapping order")
read = append(read, batch...)
}
assert.ElementsMatch(t, keysOf(copyTestChunkMap(chunks)), read,
"the reads cover the mapping exactly, each chunk once")
}
// A source that answers every request with the same page must not have that
// page replayed into the target. Reads are bounded by the mapping, so the copy
// asks for each batch once and cannot walk in circles.
func TestCopyIndicesDoesNotReplayARepeatedPage(t *testing.T) {
const pageSize = 64
source := copyTestSingleVectorChunks(keysOf(copyTestChunkMap(pageSize))...)
source.ignoreChunkFilter = true
repo := source.serve(t)
require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(pageSize)))
assert.Equal(t, 1, source.queryCount(), "the mapping is read once, not walked page by page")
assert.Equal(t, pageSize, len(source.writtenObjects()), "the page must not be written twice")
}
// A chunk holds one vector for its content plus one per generated question,
// all sharing the chunk_id. Every one of them has to reach the target: a query
// that names one chunk ID must not be mistaken for a query that returns one
// row.
func TestCopyIndicesCopiesEveryVectorOfAChunk(t *testing.T) {
source := copyTestStore(map[string][]string{
"chunk-0": {"chunk-0", "chunk-0-q1", "chunk-0-q2", "chunk-0-q3"},
})
repo := source.serve(t)
require.NoError(t, copyTestRun(t, source, repo, map[string]string{"chunk-0": "target-chunk-0"}))
written := source.writtenObjects()
assert.Equal(t, 4, len(written), "the chunk's content vector and all three question vectors")
assert.ElementsMatch(t,
[]string{"target-chunk-0", "target-chunk-0-q1", "target-chunk-0-q2", "target-chunk-0-q3"},
sourceIDsOf(written))
for _, obj := range written {
assert.Equal(t, "target-chunk-0", obj.targetChunkID)
}
}
// A batch that comes back with exactly as many rows as it asked for may have
// been cut off, so it has to be split and re-read. Here four chunk IDs produce
// five vectors: the first read is full, the two halves are not, and all five
// vectors still have to be copied.
func TestCopyIndicesSplitsABatchThatFillsTheLimit(t *testing.T) {
source := copyTestStore(map[string][]string{
"chunk-0": {"chunk-0", "chunk-0-q1"},
"chunk-1": {"chunk-1"},
"chunk-2": {"chunk-2"},
"chunk-3": {"chunk-3"},
})
repo := source.serve(t)
repo.copyQueryLimit = 4
mapping := map[string]string{
"chunk-0": "target-chunk-0",
"chunk-1": "target-chunk-1",
"chunk-2": "target-chunk-2",
"chunk-3": "target-chunk-3",
}
require.NoError(t, copyTestRun(t, source, repo, mapping))
assert.Equal(t, 5, len(source.writtenObjects()), "every vector of the batch must be copied")
assert.Equal(t, 3, source.queryCount(), "a full read is followed by two half reads")
assert.ElementsMatch(t, []int{4, 2, 2}, batchSizes(source.requestedBatches()))
}
// When one chunk on its own fills the query limit it cannot be read
// completely, and the copy has to say so rather than report success on an
// index that is missing vectors.
func TestCopyIndicesStopsOnAChunkThatFillsTheLimit(t *testing.T) {
source := copyTestStore(map[string][]string{
"chunk-0": {"chunk-0", "chunk-0-q1", "chunk-0-q2", "chunk-0-q3", "chunk-0-q4"},
})
repo := source.serve(t)
repo.copyQueryLimit = 3
err := copyTestRun(t, source, repo, map[string]string{"chunk-0": "target-chunk-0"})
require.ErrorContains(t, err, "chunk-0", "the error must name the chunk that cannot be read")
require.ErrorContains(t, err, "QUERY_MAXIMUM_RESULTS",
"the error must say the chunk's vector count reaches the server's query limit")
assert.Zero(t, len(source.writtenObjects()), "an unreadable chunk must not be reported as copied")
}
// The server's QUERY_MAXIMUM_RESULTS is not exposed over the client API, so the
// copy asks for the documented default first and, refused for it, retries at
// the limit the server names.
func TestCopyIndicesLowersTheQueryLimitWhenTheServerRefuses(t *testing.T) {
source := copyTestSingleVectorChunks("chunk-0", "chunk-1", "chunk-2")
source.queryLimit = 4
repo := source.serve(t)
require.NoError(t, copyTestRun(t, source, repo, copyTestChunkMap(3)))
assert.Equal(t, []int{10000, 4}, source.queryLimits(),
"the refused default is retried at the server's own limit")
assert.Equal(t, 3, len(source.writtenObjects()))
assert.Equal(t, 2, source.queryCount(), "only the first read pays for the refusal")
}
// A query Weaviate could not run comes back as HTTP 200 with an errors array and
// no data, so the SDK reports no Go error. Reading that as "the source has no
// more objects" turns a failed query into a successful, silently truncated copy
// - and the response type check used to panic before it could even get there.
func TestCopyIndicesReportsAQueryError(t *testing.T) {
const failure = "class Academy_embeddings_64 does not exist"
source := copyTestSingleVectorChunks("chunk-0")
source.queryError = failure
repo := source.serve(t)
defer func() {
if r := recover(); r != nil {
t.Fatalf("CopyIndices panicked on a query that could not run: %v", r)
}
}()
require.ErrorContains(t, copyTestRun(t, source, repo, copyTestChunkMap(1)), failure)
assert.Equal(t, 1, source.queryCount(), "the walk must stop on the failed query")
assert.Zero(t, len(source.writtenObjects()), "a failed query must not be reported as a finished copy")
}
// A response the walk cannot read must be reported, not turned into a panic by
// an unchecked assertion on the response shape.
func TestCopyIndicesRejectsAResponseWithoutData(t *testing.T) {
brokenResponses := map[string]func(*copyPageServer){
"no data object": func(s *copyPageServer) { s.omitData = true },
"no collection in Get": func(s *copyPageServer) { s.omitCollection = true },
}
for name, breakResponse := range brokenResponses {
t.Run(name, func(t *testing.T) {
source := copyTestSingleVectorChunks("chunk-0")
breakResponse(source)
repo := source.serve(t)
defer func() {
if r := recover(); r != nil {
t.Fatalf("CopyIndices panicked on a response without data: %v", r)
}
}()
require.ErrorContains(t, copyTestRun(t, source, repo, copyTestChunkMap(1)), "invalid response")
assert.Equal(t, 1, source.queryCount(), "the walk must stop on the unreadable response")
assert.Zero(t, len(source.writtenObjects()), "nothing may be reported as copied")
})
}
}
func keysOf[V any](m map[string]V) []string {
return slices.Sorted(maps.Keys(m))
}
func batchSizes(batches [][]string) []int {
sizes := make([]int, 0, len(batches))
for _, batch := range batches {
sizes = append(sizes, len(batch))
}
return sizes
}
func sourceIDsOf(objects []copyWrittenObject) []string {
ids := make([]string, 0, len(objects))
for _, obj := range objects {
ids = append(ids, obj.sourceID)
}
return ids
}
@@ -0,0 +1,77 @@
// Package weaviate implements retrieval and metadata updates in Weaviate.
package weaviate
import (
"context"
"fmt"
"github.com/weaviate/weaviate-go-client/v5/weaviate/filters"
"github.com/weaviate/weaviate-go-client/v5/weaviate/graphql"
)
func (w *weaviateRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
dimension int,
_ string,
) error {
collection := w.getCollectionName(dimension)
where := filters.Where().WithOperator(filters.And).WithOperands([]*filters.WhereBuilder{
filters.Where().WithPath([]string{fieldKnowledgeBaseID}).WithOperator(filters.Equal).WithValueString(sourceKB),
filters.Where().WithPath([]string{fieldKnowledgeID}).WithOperator(filters.Equal).WithValueString(knowledgeID),
})
seen := make(map[string]bool)
for {
result, err := w.client.GraphQL().Get().WithClassName(collection).WithWhere(where).WithLimit(100).
WithFields(graphql.Field{Name: "_additional", Fields: []graphql.Field{{Name: "id"}}}).
Do(ctx)
if err != nil {
return err
}
if result == nil || len(result.Errors) != 0 {
return fmt.Errorf("failed to list move indices")
}
get, ok := result.Data["Get"].(map[string]interface{})
if !ok {
return fmt.Errorf("invalid move index response")
}
rows, ok := get[collection].([]interface{})
if !ok {
return fmt.Errorf("invalid move index collection")
}
if len(rows) == 0 {
return nil
}
var ids []string
for _, row := range rows {
data, ok := row.(map[string]interface{})
if !ok {
return fmt.Errorf("invalid move index row")
}
additional, ok := data["_additional"].(map[string]interface{})
if !ok {
return fmt.Errorf("missing move index ID")
}
id, ok := additional["id"].(string)
if !ok || id == "" {
return fmt.Errorf("invalid move index ID")
}
if seen[id] {
return fmt.Errorf("move indices made no progress for %s", id)
}
seen[id] = true
ids = append(ids, id)
}
// Drain the first filtered page; after+where is unsupported by Weaviate.
// Successful updates remove these IDs from the predicate. Only an empty
// follow-up query proves completion, including after partial-page updates.
for _, id := range ids {
if err := w.client.Data().Updater().WithClassName(collection).WithID(id).WithMerge().
WithProperties(map[string]interface{}{fieldKnowledgeBaseID: targetKB, fieldTagID: ""}).
Do(ctx); err != nil {
return err
}
}
}
}
@@ -0,0 +1,130 @@
package weaviate
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/weaviate/weaviate-go-client/v5/weaviate"
)
func TestMoveKnowledgeIndicesDrainsBeyondOffsetLimitAndRetries(t *testing.T) {
const count = 10005
var mu sync.Mutex
remaining := make(map[string]bool, count)
for i := range count {
remaining[fmt.Sprintf("00000000-0000-0000-0000-%012d", i)] = true
}
failed := false
patches, queries := 0, 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/v1/graphql":
queries++
var body struct {
Query string `json:"query"`
}
if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) {
w.WriteHeader(400)
return
}
assert.Contains(t, body.Query, "knowledge_base_id")
assert.Contains(t, body.Query, "knowledge_id")
assert.Contains(t, body.Query, "source")
assert.Contains(t, body.Query, "doc")
if strings.Contains(body.Query, "offset") || strings.Contains(body.Query, "after") {
_ = json.NewEncoder(w).
Encode(map[string]any{"errors": []any{map[string]any{"message": "pagination unsupported"}}})
return
}
rows := make([]any, 0, 100)
for id := range remaining {
rows = append(rows, map[string]any{"_additional": map[string]any{"id": id}})
if len(rows) == 100 {
break
}
}
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"Get": map[string]any{"Move_3": rows}}})
case r.Method == http.MethodPatch:
id := path.Base(r.URL.Path)
assert.True(t, remaining[id], "only source-filtered IDs should be moved")
var body struct {
Properties map[string]any `json:"properties"`
Vector []float32 `json:"vector"`
}
if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) {
w.WriteHeader(400)
return
}
assert.Equal(t, map[string]any{fieldKnowledgeBaseID: "target", fieldTagID: ""}, body.Properties)
assert.Empty(t, body.Vector, "metadata merge must preserve existing vectors")
if patches == 137 && !failed {
failed = true
w.WriteHeader(http.StatusServiceUnavailable)
return
}
patches++
delete(remaining, id)
w.WriteHeader(http.StatusNoContent)
default:
// SDK probes the server version before object writes.
if r.URL.Path == "/v1/meta" {
_, _ = w.Write([]byte(`{"version":"1.30.0"}`))
return
}
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
require.NoError(t, err)
repo := &weaviateRepository{client: client, collectionBaseName: "Move"}
require.Error(t, repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, ""))
mu.Lock()
left := len(remaining)
mu.Unlock()
require.Equal(t, count-137, left)
require.NoError(t, repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, ""))
mu.Lock()
defer mu.Unlock()
require.Empty(t, remaining)
require.Equal(t, count, patches)
require.Greater(t, queries, 100)
}
func TestMoveKnowledgeIndicesRejectsNoProgress(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/v1/graphql":
_, _ = w.Write(
[]byte(`{"data":{"Get":{"Move_3":[{"_additional":{"id":"00000000-0000-0000-0000-000000000001"}}]}}}`),
)
case "/v1/meta":
_, _ = w.Write([]byte(`{"version":"1.30.0"}`))
default:
w.WriteHeader(http.StatusNoContent)
}
}))
defer server.Close()
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
require.NoError(t, err)
repo := &weaviateRepository{client: client, collectionBaseName: "Move"}
require.ErrorContains(
t,
repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, ""),
"no progress",
)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,164 @@
package weaviate
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/weaviate/weaviate-go-client/v5/weaviate"
)
// weaviateErrorBody is how Weaviate words a refused schema request.
func weaviateErrorBody(message string) string {
body, _ := json.Marshal(map[string]any{"error": []any{map[string]any{"message": message}}})
return string(body)
}
// schemaTestServer stands in for Weaviate's schema API. A class exists once a
// create has been answered with 200; probe runs before every existence check.
type schemaTestServer struct {
mu sync.Mutex
exists bool
probes int
creates int
probe func()
create func(attempt int) (int, string)
}
func (s *schemaTestServer) repository(t *testing.T) *weaviateRepository {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/schema/"):
// Answer from the state the worker found on arrival, before the
// barrier releases the race. Sampling after it instead lets the
// winner's create turn into an "already exists" answer for whoever
// the scheduler runs last, so that worker skips the create
// entirely and fewer than `workers` creates ever reach the server.
s.mu.Lock()
s.probes++
exists := s.exists
s.mu.Unlock()
if s.probe != nil {
s.probe()
}
if !exists {
w.WriteHeader(http.StatusNotFound)
return
}
_, _ = w.Write([]byte(`{"class":"Academy_embeddings_1024"}`))
case r.Method == http.MethodPost && r.URL.Path == "/v1/schema":
s.mu.Lock()
s.creates++
code, body := s.create(s.creates)
if code == http.StatusOK {
s.exists = true
}
s.mu.Unlock()
w.WriteHeader(code)
_, _ = w.Write([]byte(body))
case r.URL.Path == "/v1/meta":
_, _ = w.Write([]byte(`{"version":"1.37.3"}`))
default:
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(server.Close)
client, err := sdk.NewClient(sdk.Config{Scheme: "http", Host: strings.TrimPrefix(server.URL, "http://")})
require.NoError(t, err)
return &weaviateRepository{client: client, collectionBaseName: "Academy_embeddings"}
}
// The first batches written at a new dimension are saved by several workers at
// once, and each may find the class missing before any has created it. Only
// one create wins. Weaviate refuses the others with 422, in one of two wordings
// depending on whether they lose before or inside the Raft apply; neither may
// fail their writes. The barrier makes every worker see the class as missing,
// so the race happens every run.
func TestEnsureCollectionToleratesConcurrentCreation(t *testing.T) {
const workers = 8
var arrived atomic.Int32
allProbed := make(chan struct{})
server := &schemaTestServer{
probe: func() {
n := arrived.Add(1)
if n == workers {
close(allProbed)
}
if n > workers {
return // a loser looking again after its 422
}
select {
case <-allProbed:
case <-time.After(5 * time.Second):
t.Error("not every worker probed the class")
}
},
create: func(attempt int) (int, string) {
switch {
case attempt == 1:
return http.StatusOK, `{"class":"Academy_embeddings_1024"}`
case attempt%2 == 0:
return http.StatusUnprocessableEntity,
weaviateErrorBody("updating schema: TYPE_ADD_CLASS: class already exists")
default:
return http.StatusUnprocessableEntity,
weaviateErrorBody("class name Academy_embeddings_1024 already exists")
}
},
}
repo := server.repository(t)
var wg sync.WaitGroup
errs := make(chan error, workers)
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
errs <- repo.ensureCollection(context.Background(), 1024)
}()
}
wg.Wait()
close(errs)
for err := range errs {
assert.NoError(t, err, "a worker lost the creation race")
}
assert.Equal(t, workers, server.creates, "every worker should have attempted the create")
_, ok := repo.initializedCollections.Load(1024)
assert.True(t, ok, "dimension 1024 should be marked initialized")
}
// A 422 for any other reason leaves the class missing, so the write must fail
// rather than be recorded as initialized.
func TestEnsureCollectionFailsWhenTheCreateIsRejected(t *testing.T) {
server := &schemaTestServer{create: func(int) (int, string) {
return http.StatusUnprocessableEntity, weaviateErrorBody("invalid property: data type not supported")
}}
repo := server.repository(t)
require.ErrorContains(t, repo.ensureCollection(context.Background(), 1024), "failed to create collection")
assert.Equal(t, 2, server.probes, "the class should be looked up again after the 422")
_, ok := repo.initializedCollections.Load(1024)
assert.False(t, ok)
}
// Only a 422 means the create was refused; anything else is reported as it is.
func TestEnsureCollectionDoesNotRecheckOtherFailures(t *testing.T) {
server := &schemaTestServer{create: func(int) (int, string) {
return http.StatusInternalServerError, weaviateErrorBody("disk full")
}}
repo := server.repository(t)
require.Error(t, repo.ensureCollection(context.Background(), 1024))
assert.Equal(t, 1, server.probes)
}
@@ -0,0 +1,23 @@
package weaviate
import (
"testing"
"academy/internal/types"
)
// Weaviate certainty is (1 + cos) / 2; vector hits leave the driver as
// cosine similarity.
func TestParseGraphQLResponseReportsCosine(t *testing.T) {
t.Parallel()
items := []interface{}{
map[string]interface{}{
"_additional": map[string]interface{}{"id": "p1", "certainty": 0.9},
"chunk_id": "c1",
},
}
got := parseGraphQLResponse(items, "Coll", types.MatchTypeEmbedding)
if len(got) != 1 || got[0].Score < 0.8-1e-9 || got[0].Score > 0.8+1e-9 {
t.Fatalf("scores = %+v, want cosine 0.8", got)
}
}
@@ -0,0 +1,37 @@
package weaviate
import (
"sync"
"github.com/weaviate/weaviate-go-client/v5/weaviate"
)
type weaviateRepository struct {
client *weaviate.Client
collectionBaseName string
replicationFactor int // 0 = use Weaviate server default
desiredShardCount int // 0 = use Weaviate server default
// copyQueryLimit caps the rows one CopyIndices source query may return.
// 0 = defaultCopyQueryLimit. Tests lower it to drive the truncation and
// batch-splitting paths with small fixtures.
copyQueryLimit int
// Cache for initialized collections (dimension -> true)
initializedCollections sync.Map
}
type WeaviateVectorEmbedding struct {
Content string `json:"content"`
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 WeaviateVectorEmbeddingWithScore struct {
WeaviateVectorEmbedding
Score float64
}