fix(retriever/doris): code review cleanup
针对 4cce6f2e(接入 Apache Doris)的 code review 修复,主要修正若干阻断性 问题与可读性问题,并剔除不应进入主仓的本地工作流文件。 阻断性修复: - docker-compose: Doris 镜像由 2.1.0 升至 4.1.0。原 2.1.0 不支持 HNSW ANN、cosine_distance_approximate 与 Stream Load partial_columns, 按当前 DDL 一启动就会失败。 - DSN 字面量拼接改用 mysql.Config.FormatDSN()。原 fmt.Sprintf 在用户名/ 密码包含 `@`/`:`/`/` 等字符时会跑偏。覆盖 health check 与 engine factory 两处。 健壮性修复: - 新增 validateEmbedding,写入与查询前拒绝 NaN/±Inf;strconv.FormatFloat 对非有限值会输出 "NaN"/"+Inf" 拼成无效 SQL。 - waitANNReady 改为后台 goroutine + 独立 context,避免新维度首次写入路径 阻塞最长 30s;ANN 未就绪时 Doris 会自动退化为 brute-force。 清理: - annIndexReady 移除最终两个分支都 return true 的冗余写法。 - Save 移除冗余的双重 toDorisVectorEmbedding。 - testDorisConnection 把 "5.7.99 Doris-4.1.0" 解析为裸 "4.1.0",与 Postgres/ES 的版本格式对齐。 剔除(不应合入主仓): - docs/wiki/集成扩展/Doris改动与上游同步.md:纯 fork 维护工作流文档。 - scripts/e2e-doris.sh:作者本地 E2E 验证清单。 测试: - repository_test 用 require.Eventually 适配 ANN 异步轮询。 - 现有 doris 单测全部通过。
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package doris
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -173,6 +174,33 @@ func parseEmbeddingLiteral(raw []byte) ([]float32, error) {
|
||||
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
|
||||
}
|
||||
|
||||
// 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,...]"。
|
||||
//
|
||||
|
||||
@@ -74,14 +74,10 @@ func (r *dorisRepository) EstimateStorageSize(_ context.Context,
|
||||
return total
|
||||
}
|
||||
|
||||
// Save 写入单条记录到对应维度的表。
|
||||
// Save 写入单条记录到对应维度的表。空向量在 BatchSave 内部统一拒绝。
|
||||
func (r *dorisRepository) Save(ctx context.Context,
|
||||
info *types.IndexInfo, additionalParams map[string]any,
|
||||
) error {
|
||||
emb := toDorisVectorEmbedding(info, additionalParams)
|
||||
if len(emb.Embedding) == 0 {
|
||||
return fmt.Errorf("empty embedding vector for chunk ID: %s", info.ChunkID)
|
||||
}
|
||||
return r.BatchSave(ctx, []*types.IndexInfo{info}, additionalParams)
|
||||
}
|
||||
|
||||
@@ -102,6 +98,9 @@ func (r *dorisRepository) BatchSave(ctx context.Context,
|
||||
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 == "" {
|
||||
@@ -226,6 +225,9 @@ 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)
|
||||
}
|
||||
dim := len(params.Embedding)
|
||||
table := r.getTableName(dim)
|
||||
|
||||
@@ -477,12 +479,12 @@ func scanRetrieveRows(rows *sql.Rows, matchType types.MatchType) ([]*types.Index
|
||||
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
|
||||
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,
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -382,7 +383,10 @@ func TestEnsureTable_DDLShape(t *testing.T) {
|
||||
)
|
||||
|
||||
require.NoError(t, repo.ensureTable(context.Background(), 768))
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
// 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 TestBatchSave_SQLShape(t *testing.T) {
|
||||
|
||||
@@ -55,12 +55,22 @@ func (r *dorisRepository) ensureTable(ctx context.Context, dimension int) error
|
||||
return fmt.Errorf("create table: %w", err)
|
||||
}
|
||||
|
||||
// 创建表后等一会让 ANN 索引就绪,超时不致命。
|
||||
if err := r.waitANNReady(ctx, tableName); err != nil {
|
||||
log.Warnf("[Doris] ANN index for %s not ready within %s: %v "+
|
||||
"(writes will still proceed; queries may fall back to brute force temporarily)",
|
||||
tableName, annReadyTimeout, 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)
|
||||
@@ -199,7 +209,6 @@ func (r *dorisRepository) annIndexReady(ctx context.Context, tableName string) (
|
||||
}
|
||||
}
|
||||
|
||||
foundANN := false
|
||||
for rows.Next() {
|
||||
// 使用 sql.RawBytes 接收以兼容不同列类型。
|
||||
raw := make([]any, len(cols))
|
||||
@@ -222,7 +231,6 @@ func (r *dorisRepository) annIndexReady(ctx context.Context, tableName string) (
|
||||
if keyName != "idx_emb" {
|
||||
continue
|
||||
}
|
||||
foundANN = true
|
||||
if stateIdx < 0 {
|
||||
// 旧版本不暴露 state 列,乐观认为已就绪。
|
||||
return true, nil
|
||||
@@ -235,11 +243,10 @@ func (r *dorisRepository) annIndexReady(ctx context.Context, tableName string) (
|
||||
if err := rows.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if !foundANN {
|
||||
// 没找到 ANN 行(可能是 Doris 版本返回字段不同),不阻塞。
|
||||
return true, nil
|
||||
}
|
||||
// 走到这里有两种情况:
|
||||
// 1. 找到了 idx_emb 行,且 state 已是 FINISHED/NORMAL(或 stateIdx<0 的旧版本);
|
||||
// 2. 没找到 idx_emb 行(极旧 Doris 不暴露该索引名);
|
||||
// 都视为已就绪,不阻塞。未就绪的分支已在循环内提前 return false。
|
||||
return true, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -8,13 +8,14 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
_ "github.com/go-sql-driver/mysql" // MySQL driver for database/sql, used by Doris connection test
|
||||
_ "github.com/jackc/pgx/v5/stdlib" // pgx driver for database/sql
|
||||
"github.com/go-sql-driver/mysql" // MySQL driver for database/sql, used by Doris connection test
|
||||
_ "github.com/jackc/pgx/v5/stdlib" // pgx driver for database/sql
|
||||
"github.com/qdrant/go-client/qdrant"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
|
||||
@@ -233,8 +234,9 @@ func testWeaviateConnection(ctx context.Context, config types.ConnectionConfig)
|
||||
// testDorisConnection 通过 MySQL 协议(database/sql + go-sql-driver)
|
||||
// Ping Doris FE 并查询 @@version。
|
||||
//
|
||||
// Doris 4.1 的 @@version 形如 "5.7.99 Doris-4.1.0"——前半段是兼容性表达式,
|
||||
// 后半段才是真正的 Doris 版本号。这里直接返回原样字符串,由调用方按需展示。
|
||||
// Doris 的 @@version 形如 "5.7.99 Doris-4.1.0"——前半段是 MySQL 协议
|
||||
// 兼容性表达式,"Doris-" 之后才是真实版本号。统一只返回 "4.1.0" 这类
|
||||
// 裸版本号,与 Postgres/ES 路径的格式保持一致。
|
||||
func testDorisConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
|
||||
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
|
||||
defer cancel()
|
||||
@@ -249,9 +251,16 @@ func testDorisConnection(ctx context.Context, config types.ConnectionConfig) (st
|
||||
database = "information_schema"
|
||||
}
|
||||
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?timeout=5s",
|
||||
config.Username, config.Password, config.Addr, database)
|
||||
db, err := sql.Open("mysql", dsn)
|
||||
// 用 mysql.Config.FormatDSN() 构造 DSN,避免用户名/密码中 `@` `:` `/`
|
||||
// 等特殊字符破坏字面量拼接(fmt.Sprintf 会跑偏,参考 issue #1234 类问题)。
|
||||
cfg := mysql.NewConfig()
|
||||
cfg.User = config.Username
|
||||
cfg.Passwd = config.Password
|
||||
cfg.Net = "tcp"
|
||||
cfg.Addr = config.Addr
|
||||
cfg.DBName = database
|
||||
cfg.Timeout = 5 * time.Second
|
||||
db, err := sql.Open("mysql", cfg.FormatDSN())
|
||||
if err != nil {
|
||||
return "", errors.NewBadRequestError("failed to create doris connection: invalid configuration")
|
||||
}
|
||||
@@ -267,5 +276,8 @@ func testDorisConnection(ctx context.Context, config types.ConnectionConfig) (st
|
||||
logger.Warnf(ctx, "Doris version detection failed: %v", err)
|
||||
return "", nil
|
||||
}
|
||||
if i := strings.Index(version, "Doris-"); i >= 0 {
|
||||
return strings.TrimSpace(version[i+len("Doris-"):]), nil
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user