Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Semantic search using AI embeddings https://github.com/siyuan-note/siyuan/issues/17788 https://github.com/siyuan-note/siyuan/issues/18002

Daniel2f133c5b5b76
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 042ba96612..0cb838a83e 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -451,6 +451,12 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,
return
}
+// DownloadNetAssets2LocalAssets 将语法树中的网络资源下载到本地并改写链接,
+// 不持久化文档树,由调用方负责后续保存与渲染。
+func DownloadNetAssets2LocalAssets(tree *parse.Tree, onlyImg bool, originalURL string, assetsDirPath string) {
+ netAssets2LocalAssets0(tree, onlyImg, originalURL, assetsDirPath, false)
+}
+
func SearchAssetsByName(keyword string, exts []string) (ret []*cache.Asset) {
ret = []*cache.Asset{}
var keywords []string
diff --git a/kernel/model/embedding.go b/kernel/model/embedding.go
index 7e5c299ad0..9aaa95dc14 100644
--- a/kernel/model/embedding.go
+++ b/kernel/model/embedding.go
@@ -44,6 +44,12 @@ const (
embeddingMinTextLen = 7
embeddingMaxContentLen = 12000
embeddingVectorDim = 4 // float32 = 4 bytes
+
+ // 嵌入失败重试的退避参数:API 不可用时避免连接风暴
+ // delay = min(embeddingBackoffBase << (failCount-1), embeddingBackoffMax)
+ embeddingBackoffBase = 30 // 首次失败后 30s 重试
+ embeddingBackoffMax = 30 * 60 // 上限 30min
+ embeddingMaxFailCount = 8 // 单块连续失败到此次数视为永久失败,不再调度
)
var (
@@ -55,6 +61,10 @@ var (
embeddingIgnoreLock sync.Mutex
embeddingStop atomic.Bool
+
+ // embeddingErrNotified 标记本轮是否已向用户提示过嵌入失败,避免多个并发 worker 失败时重复弹窗。
+ // 每次 processPendingEmbeddings 开始时随 embeddingStop 一起重置。
+ embeddingErrNotified atomic.Bool
)
func checkEmbeddingTable() bool {
@@ -111,6 +121,7 @@ func processPendingEmbeddings() {
}
embeddingStop.Store(false)
+ embeddingErrNotified.Store(false)
workCh := make(chan embeddingJob, embeddingMaxConcurrency*2)
@@ -135,7 +146,10 @@ func processPendingEmbeddings() {
return
}
- results, err := sql.QueryNoLimit(stmtPendingBlocks)
+ // SQL 粗筛下界用最小退避间隔,保证不漏掉到期的重试块;逐块的精确退避在下面 Go 侧再判
+ now := time.Now().Unix()
+ cutoff := now - int64(embeddingBackoffBase) // embeddingBackoffBase 单位为秒
+ results, err := sql.QueryNoLimitArgs(stmtPendingBlocks, embeddingMaxFailCount, cutoff)
if err != nil {
logging.LogErrorf("query pending embedding blocks failed: %s", err)
return
@@ -147,6 +161,9 @@ func processPendingEmbeddings() {
var texts []string
var blocks []map[string]any
+ anySubmitted := false // 本轮是否向 workCh 提交过 job
+ backoffSkipped := 0 // 因未到退避时间被跳过的块数(这类块状态不变,下轮还会被捞出)
+ minRemaining := int64(embeddingBackoffMax) // 这些块中最近的剩余等待秒数(embeddingBackoffMax 单位为秒)
for _, row := range results {
id, _ := row["id"].(string)
rootID, _ := row["root_id"].(string)
@@ -154,10 +171,28 @@ func processPendingEmbeddings() {
path, _ := row["path"].(string)
updated, _ := row["updated"].(string)
content, _ := row["content"].(string)
+
+ // 失败过的块按各自 fail_count 精确判断是否到退避时间,未到期则本轮跳过
+ failCount, _ := row["fail_count"].(int64)
+ lastTried, _ := row["last_tried"].(int64)
+ if failCount > 0 {
+ if failCount >= embeddingMaxFailCount {
+ continue // 永久失败,不再调度
+ }
+ required := int64(embeddingBackoffFor(int(failCount)) / time.Second)
+ if elapsed := now - lastTried; elapsed < required {
+ backoffSkipped++
+ if remaining := required - elapsed; remaining < minRemaining {
+ minRemaining = remaining
+ }
+ continue // 未到该块的退避时间
+ }
+ }
+
matcher := getEmbeddingIgnoreMatcher()
if (nil != matcher && matcher.MatchesPath("/"+box+path)) ||
len(content) < embeddingMinTextLen || len(content) > embeddingMaxContentLen {
- sql.Exec("INSERT OR IGNORE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ sql.Exec("INSERT OR IGNORE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated, fail_count, last_tried) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0)",
id, rootID, box, path, []byte{}, embeddingModel(), 0, updated)
continue
}
@@ -167,12 +202,32 @@ func processPendingEmbeddings() {
if len(texts) >= embeddingBatchSize {
workCh <- embeddingJob{texts: texts, blocks: blocks}
+ anySubmitted = true
texts = nil
blocks = nil
}
}
if len(texts) > 0 {
workCh <- embeddingJob{texts: texts, blocks: blocks}
+ anySubmitted = true
+ }
+
+ // 本轮没有提交任何 job,且全部是被退避跳过的块:这些块状态没变,下轮 SQL 还会捞出同样的块,
+ // 直接进下一轮会 CPU 忙等 + 高频 DB 查询。sleep 到最近的到期时间再继续,期间检查熔断以便及时退出。
+ if !anySubmitted && backoffSkipped > 0 {
+ wait := time.Duration(minRemaining) * time.Second
+ if wait < time.Second {
+ wait = time.Second
+ }
+ // 分段 sleep,每秒检查一次 embeddingStop,熔断时尽快退出
+ for wait > 0 && !embeddingStop.Load() {
+ step := wait
+ if step > time.Second {
+ step = time.Second
+ }
+ time.Sleep(step)
+ wait -= step
+ }
}
}
}()
@@ -180,10 +235,33 @@ func processPendingEmbeddings() {
workersWg.Wait()
}
-const stmtPendingBlocks = "SELECT b.id, b.root_id, b.box, b.path, b.content, b.updated FROM blocks b " +
+// stmtPendingBlocks 捞取待嵌入块,分两类:
+// 1. 从未尝试过(e.id IS NULL);
+// 2. 失败过、未达永久失败阈值、且距上次尝试已超过退避间隔(e.last_tried < ?)。
+// 参数顺序:?1=maxFailCount,?2=now-backoff(仅作 fail_count>0 块的粗筛下界,精确退避由 Go 侧按每块 fail_count 计算)。
+const stmtPendingBlocks = "SELECT b.id, b.root_id, b.box, b.path, b.content, b.updated, " +
+ "COALESCE(e.fail_count, 0) AS fail_count, COALESCE(e.last_tried, 0) AS last_tried " +
+ "FROM blocks b " +
"LEFT JOIN block_embeddings e ON b.id = e.id " +
"WHERE e.id IS NULL " +
- "ORDER BY b.updated DESC LIMIT 100"
+ "OR (e.fail_count > 0 AND e.fail_count < ? AND e.last_tried < ?) " +
+ "ORDER BY fail_count ASC, b.updated DESC LIMIT 100"
+
+// embeddingBackoffFor 返回给定失败次数对应的退避间隔(首次失败 fail_count=1 对应 base)。
+func embeddingBackoffFor(failCount int) time.Duration {
+ if failCount < 1 {
+ return time.Duration(embeddingBackoffBase) * time.Second
+ }
+ shift := failCount - 1
+ if shift > 20 {
+ shift = 20 // 防溢出
+ }
+ d := embeddingBackoffBase << uint(shift)
+ if d > embeddingBackoffMax || d < 0 {
+ return time.Duration(embeddingBackoffMax) * time.Second
+ }
+ return time.Duration(d) * time.Second
+}
func encodeVector(vec []float32) []byte {
buf := make([]byte, len(vec)*embeddingVectorDim)
@@ -203,8 +281,27 @@ func decodeVector(b []byte) []float32 {
func doEmbedAndStore(texts []string, blocks []map[string]any) {
vectors, err := util.BatchGetEmbeddings(texts, embeddingKey(), embeddingBaseURL(), embeddingModel(), embeddingTimeout())
if err != nil {
- if util.IsNetworkError(err) {
- embeddingStop.Store(true)
+ // 任何 API 错误(含模型不存在/鉴权失败/限流/网络异常)都熔断本轮,避免连接风暴
+ embeddingStop.Store(true)
+ logging.LogErrorf("create embeddings failed, stop this round: %s", err)
+ // 多个 worker 可能并发失败,用 CAS 保证本轮只向用户提示一次
+ if embeddingErrNotified.CompareAndSwap(false, true) {
+ util.PushErrMsg("Embedding request failed, indexing paused. Please check AI embedding config.", 5000)
+ }
+
+ // 失败块记录 fail_count/last_tried,使其进入按各自退避节奏的重试队列,而非被反复无界重试
+ now := time.Now().Unix()
+ for _, row := range blocks {
+ id, _ := row["id"].(string)
+ rootID, _ := row["root_id"].(string)
+ box, _ := row["box"].(string)
+ path, _ := row["path"].(string)
+ updated, _ := row["updated"].(string)
+ // 先确保占位行存在(INSERT OR IGNORE 不覆盖已有行),再累加失败计数
+ sql.Exec("INSERT OR IGNORE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated, fail_count, last_tried) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0)",
+ id, rootID, box, path, []byte{}, embeddingModel(), 0, updated)
+ sql.Exec("UPDATE block_embeddings SET fail_count = fail_count + 1, last_tried = ?, embedding = ?, model = ?, content_len = 0 WHERE id = ?",
+ now, []byte{}, embeddingModel(), id)
}
return
}
@@ -219,7 +316,8 @@ func doEmbedAndStore(texts []string, blocks []map[string]any) {
buf := encodeVector(vectors[i])
- err = sql.Exec("INSERT OR REPLACE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ // 成功则整行重写,fail_count/last_tried 复位为 0
+ err = sql.Exec("INSERT OR REPLACE INTO block_embeddings (id, root_id, box, path, embedding, model, content_len, updated, fail_count, last_tried) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0)",
id, rootID, box, path, buf, embeddingModel(), len(plainText), updated)
if err != nil {
logging.LogErrorf("store embedding failed for block [%s]: %s", id, err)
diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go
index e913880d2d..b714c94047 100644
--- a/kernel/sql/block_query.go
+++ b/kernel/sql/block_query.go
@@ -359,6 +359,12 @@ func QueryNoLimit(stmt string) (ret []map[string]any, err error) {
return queryRawStmt(stmt, math.MaxInt)
}
+// QueryNoLimitArgs 与 QueryNoLimit 一致,但支持参数化查询(stmt 中用 ? 占位,args 顺序填入)。
+// 用于 embedding 索引器按 fail_count/last_tried 调度时的带参 SELECT。
+func QueryNoLimitArgs(stmt string, args ...any) (ret []map[string]any, err error) {
+ return queryRawStmtArgs(stmt, args, math.MaxInt)
+}
+
func Query(stmt string, limit int) (ret []map[string]any, err error) {
originalStmt := stmt
// Kernel API `/api/query/sql` support `||` operator https://github.com/siyuan-note/siyuan/issues/9662
@@ -540,6 +546,47 @@ func queryRawStmt(stmt string, limit int) (ret []map[string]any, err error) {
return
}
+// queryRawStmtArgs 与 queryRawStmt 一致,但走带参数的 query,避免 SQL 拼接注入与时间格式问题。
+func queryRawStmtArgs(stmt string, args []any, limit int) (ret []map[string]any, err error) {
+ rows, err := query(stmt, args...)
+ if err != nil {
+ return
+ }
+ defer rows.Close()
+
+ cols, err := rows.Columns()
+ if err != nil || nil == cols {
+ return
+ }
+
+ noLimit := !containsLimitClause(stmt)
+ var count int
+ for rows.Next() {
+ columns := make([]any, len(cols))
+ columnPointers := make([]any, len(cols))
+ for i := range columns {
+ columnPointers[i] = &columns[i]
+ }
+
+ if err = rows.Scan(columnPointers...); err != nil {
+ return
+ }
+
+ m := make(map[string]any)
+ for i, colName := range cols {
+ val := columnPointers[i].(*any)
+ m[colName] = *val
+ }
+
+ ret = append(ret, m)
+ count++
+ if noLimit && limit < count {
+ break
+ }
+ }
+ return
+}
+
func SelectBlocksRawStmtNoParse(stmt string, limit int) (ret []*Block) {
return selectBlocksRawStmt(stmt, limit)
}
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index c46ae0a6e3..bcb5d81967 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -95,6 +95,8 @@ func initDatabase(forceRebuild bool) {
if !forceRebuild {
// 检查数据库结构版本,如果版本不一致的话说明改过表结构,需要重建
if util.DatabaseVer == getDatabaseVer() {
+ // 老库版本一致但缺少新加的列时,做幂等迁移(不升 DatabaseVer,避免全库重建丢失已嵌入向量)
+ migrateBlockEmbeddingsSchema()
recoverIndexQueue()
return
}
@@ -234,7 +236,7 @@ func initDBTables() {
if err != nil {
logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "drop table [block_embeddings] failed: %s", err)
}
- _, err = db.Exec("CREATE TABLE block_embeddings (id TEXT PRIMARY KEY, root_id TEXT, box TEXT, path TEXT, embedding BLOB, model TEXT, content_len INTEGER, updated TEXT)")
+ _, err = db.Exec("CREATE TABLE block_embeddings (id TEXT PRIMARY KEY, root_id TEXT, box TEXT, path TEXT, embedding BLOB, model TEXT, content_len INTEGER, updated TEXT, fail_count INTEGER NOT NULL DEFAULT 0, last_tried INTEGER NOT NULL DEFAULT 0)")
if err != nil {
logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create table [block_embeddings] failed: %s", err)
}
@@ -1427,6 +1429,56 @@ func Exec(stmt string, args ...any) error {
return err
}
+// migrateBlockEmbeddingsSchema 为 block_embeddings 幂等补充失败重试相关的列。
+// 不升 DatabaseVer(避免全库重建丢失已嵌入向量);列已存在时跳过,老行自动取默认值 0。
+func migrateBlockEmbeddingsSchema() {
+ if nil == db {
+ return
+ }
+
+ // PRAGMA table_info 返回每列的定义,name 字段即列名
+ rows, err := db.Query("PRAGMA table_info(block_embeddings)")
+ if err != nil {
+ logging.LogErrorf("check block_embeddings columns failed: %s", err)
+ return
+ }
+ defer rows.Close()
+
+ existing := map[string]bool{}
+ for rows.Next() {
+ var cid int
+ var name, ctype string
+ var notnull, pk int
+ var dfltValue any
+ if err = rows.Scan(&cid, &name, &ctype, &notnull, &dfltValue, &pk); err != nil {
+ logging.LogErrorf("scan block_embeddings column info failed: %s", err)
+ return
+ }
+ existing[name] = true
+ }
+
+ // 表不存在(首次启动还没建)时 existing 为空,跳过;待 initDBTables 建表
+ if 0 == len(existing) {
+ return
+ }
+
+ addColumns := []string{
+ "ALTER TABLE block_embeddings ADD COLUMN fail_count INTEGER NOT NULL DEFAULT 0",
+ "ALTER TABLE block_embeddings ADD COLUMN last_tried INTEGER NOT NULL DEFAULT 0",
+ }
+ // SQLite 的 ALTER TABLE ADD COLUMN 无法在单条语句里加多列,逐条执行;列已存在会报错,忽略
+ if !existing["fail_count"] {
+ if _, err = db.Exec(addColumns[0]); err != nil {
+ logging.LogErrorf("add column [fail_count] failed: %s", err)
+ }
+ }
+ if !existing["last_tried"] {
+ if _, err = db.Exec(addColumns[1]); err != nil {
+ logging.LogErrorf("add column [last_tried] failed: %s", err)
+ }
+ }
+}
+
func beginTx() (tx *sql.Tx, err error) {
if tx, err = db.Begin(); err != nil {
logging.LogErrorf("begin tx failed: %s\n %s", err, logging.ShortStack())
diff --git a/kernel/util/openai.go b/kernel/util/openai.go
index c8e0ca374a..706361ea77 100644
--- a/kernel/util/openai.go
+++ b/kernel/util/openai.go
@@ -20,6 +20,7 @@ import (
"context"
"net/http"
"strings"
+ "sync"
"time"
"github.com/sashabaranov/go-openai"
@@ -179,6 +180,27 @@ func IsNetworkError(err error) bool {
strings.Contains(msg, "network")
}
+// embeddingHTTPClient 单例 HTTP 客户端,复用连接池并限制每主机最大连接数,
+// 避免 embedding 索引器在 API 不可用时新建大量连接形成连接风暴。
+// 单次请求超时由调用方用 context.WithTimeout 控制,client 本身不设全局 Timeout。
+var (
+ embeddingHTTPClientOnce sync.Once
+ embeddingHTTPClient *http.Client
+)
+
+func getEmbeddingHTTPClient() *http.Client {
+ embeddingHTTPClientOnce.Do(func() {
+ transport := &http.Transport{
+ MaxConnsPerHost: 4, // 同一 embedding endpoint 的并发连接上限
+ MaxIdleConns: 8,
+ MaxIdleConnsPerHost: 4,
+ IdleConnTimeout: 90 * time.Second,
+ }
+ embeddingHTTPClient = &http.Client{Transport: transport}
+ })
+ return embeddingHTTPClient
+}
+
func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, timeout int) (ret [][]float32, err error) {
if 1 > len(texts) {
return
@@ -186,10 +208,7 @@ func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, timeout i
config := openai.DefaultConfig(apiKey)
config.BaseURL = baseURL
- config.HTTPClient = &http.Client{
- Timeout: time.Duration(timeout) * time.Second,
- Transport: &http.Transport{},
- }
+ config.HTTPClient = getEmbeddingHTTPClient()
client := openai.NewClientWithConfig(config)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)