An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Recover queued embed block content indexing https://github.com/siyuan-note/siyuan/issues/20214
Daniel5c7c89efa44f
diff --git a/kernel/model/index.go b/kernel/model/index.goindex 1d8f2b1816..8a7cc9f7be 100644--- a/kernel/model/index.go+++ b/kernel/model/index.go@@ -31,7 +31,6 @@ import ("github.com/88250/go-humanize""github.com/88250/gulu""github.com/88250/lute/ast"- "github.com/88250/lute/editor""github.com/88250/lute/html""github.com/88250/lute/parse""github.com/panjf2000/ants/v2"@@ -393,44 +392,11 @@ func autoIndexEmbedBlock() {embedBlocks = append(embedBlocks, sql.QueryEmptyContentEmbedBlocksInBox(boxID)...)}for i, embedBlock := range embedBlocks {- markdown := strings.TrimSpace(embedBlock.Markdown)- markdown = strings.TrimPrefix(markdown, "{{")- stmt := strings.TrimSuffix(markdown, "}}")-- // 嵌入块的 Markdown 内容需要反转义- stmt = html.UnescapeString(stmt)- stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")-- // 需要移除首尾的空白字符以判断是否具有 //!js 标记- stmt = strings.TrimSpace(stmt)- if "" == stmt {- continue- }- if strings.HasPrefix(stmt, "//!js") {- // https://github.com/siyuan-note/siyuan/issues/9648- // js 嵌入块不支持自动索引,由前端主动调用 /api/search/updateEmbedBlock 接口更新内容 https://github.com/siyuan-note/siyuan/issues/9736+ content, supported := sql.CalculateEmbedBlockContent(embedBlock)+ if !supported {continue}-- // 嵌入块脚本来自文档内容,属于不可信输入:执行前必须校验为单条只读查询,- // 不能用「是否包含 select 子串」代替,注释或子查询即可绕过- if err := sql.CheckReadonlyBlockQueryStatement(stmt, embedBlock.Box); nil != err {- logging.LogWarnf("skip non-readonly embed block [%s] script: %s", embedBlock.ID, err)- continue- }-- var queryResultBlocks []*sql.Block- if IsEncryptedBox(embedBlock.Box) {- queryResultBlocks = sql.SelectBlocksRawStmtNoParseInBox(stmt, 102400, embedBlock.Box)- } else {- queryResultBlocks = sql.SelectBlocksRawStmtNoParse(stmt, 102400)- }- for _, block := range queryResultBlocks {- embedBlock.Content += block.Content- }- if "" == embedBlock.Content {- embedBlock.Content = "no query result"- }+ embedBlock.Content = contentsql.UpdateBlockContentQueue(embedBlock)if 63 <= i { // 一次任务中最多处理 64 个嵌入块,防止卡顿diff --git a/kernel/sql/embed_content.go b/kernel/sql/embed_content.gonew file mode 100644index 0000000000..3c7c65c1bb--- /dev/null+++ b/kernel/sql/embed_content.go@@ -0,0 +1,39 @@+package sql++import (+ "strings"++ "github.com/88250/lute/editor"+ "github.com/88250/lute/html"+ "github.com/siyuan-note/logging"+)++// CalculateEmbedBlockContent 计算只读 SQL 嵌入的搜索内容;空脚本和 JavaScript 嵌入由前端更新。+func CalculateEmbedBlockContent(block *Block) (content string, supported bool) {+ stmt := strings.TrimSpace(block.Markdown)+ stmt = strings.TrimPrefix(stmt, "{{")+ stmt = strings.TrimSuffix(stmt, "}}")+ stmt = html.UnescapeString(stmt)+ stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")+ stmt = strings.TrimSpace(stmt)+ if stmt == "" || strings.HasPrefix(stmt, "//!js") {+ return "", false+ }+ if err := CheckReadonlyBlockQueryStatement(stmt, block.Box); err != nil {+ logging.LogWarnf("skip non-readonly embed block [%s] script: %s", block.ID, err)+ return "", false+ }+ var blocks []*Block+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(block.Box) {+ blocks = SelectBlocksRawStmtNoParseInBox(stmt, 102400, block.Box)+ } else {+ blocks = SelectBlocksRawStmtNoParse(stmt, 102400)+ }+ for _, result := range blocks {+ content += result.Content+ }+ if content == "" {+ content = "no query result"+ }+ return content, true+}diff --git a/kernel/sql/index_queue.go b/kernel/sql/index_queue.goindex c91b7dd64a..57d0252733 100644--- a/kernel/sql/index_queue.go+++ b/kernel/sql/index_queue.go@@ -28,10 +28,12 @@ import ("github.com/88250/gulu""github.com/88250/lute"+ "github.com/88250/lute/ast""github.com/gofrs/flock""github.com/siyuan-note/eventbus""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -138,6 +140,8 @@ func dbOpToIndexEntry(op *dbQueueOperation) *indexEntry {return &indexEntry{Action: "delete_assets", Hashes: op.removeAssetHashes}case "index_node":return &indexEntry{Action: "index_node", ID: op.id, Box: op.box}+ case "update_block_content":+ return &indexEntry{Action: op.action, ID: op.block.ID, Box: op.block.Box}default:return nil}@@ -302,6 +306,24 @@ func indexEntryToOp(e indexEntry, luteEngine *lute.Lute, prefix string) (*dbQueureturn &dbQueueOperation{removeAssetHashes: e.Hashes, inQueueTime: time.Now(), action: "delete_assets"}, nilcase "index_node":return &dbQueueOperation{id: e.ID, box: e.Box, inQueueTime: time.Now(), action: "index_node"}, nil+ case "update_block_content":+ bt := treenode.GetBlockTreeInBox(e.ID, e.Box)+ if bt == nil || bt.BoxID != e.Box {+ return nil, os.ErrNotExist+ }+ tree, err := filesys.LoadTree(e.Box, bt.Path, luteEngine)+ if err != nil {+ logIndexEntryLoadError(prefix, e.Action, e, err)+ return nil, err+ }+ node := treenode.GetNodeInTree(tree, e.ID)+ if node == nil || node.Type != ast.NodeBlockQueryEmbed {+ return nil, os.ErrNotExist+ }+ block, _ := buildBlockFromNode(node, tree)+ // 只持久化块定位信息;恢复时重新计算派生内容,不能把查询脚本当作搜索内容。+ block.Content, _ = CalculateEmbedBlockContent(block)+ return &dbQueueOperation{block: block, inQueueTime: time.Now(), action: e.Action}, nil}return nil, fmt.Errorf("unknown index queue action [%s]", e.Action)}diff --git a/kernel/sql/index_queue_test.go b/kernel/sql/index_queue_test.goindex 3ef33f027d..1d0ab7e20d 100644--- a/kernel/sql/index_queue_test.go+++ b/kernel/sql/index_queue_test.go@@ -156,6 +156,32 @@ func TestRecoverIndexQueueLoadsTreesOnlyWhenExecuted(t *testing.T) {}}+func TestEmbedContentQueueRecoveryDescriptors(t *testing.T) {+ prepareIndexQueueTest(t)+ block := &Block{ID: "20261008000001-embed01", Box: "20261008000000-embed01", Content: "private derived content"}+ UpdateBlockContentQueue(block)+ entries := loadIndexQueue()+ if len(entries) != 1 || entries[0].Action != "update_block_content" || entries[0].ID != block.ID || entries[0].Box != block.Box {+ t.Fatalf("missing embed recovery descriptor: %#v", entries)+ }+ data, err := os.ReadFile(filepath.Join(util.QueueDir, "index.queue"))+ if err != nil || bytes.Contains(data, []byte(block.Content)) {+ t.Fatalf("derived content leaked to global recovery queue: %s, %v", data, err)+ }+ operationQueue = nil+ recoverIndexQueue()+ UpdateBlockContentQueue(block)+ latest := *block+ latest.Content = "new result"+ UpdateBlockContentQueue(&latest)+ other := *block+ other.Box = "20261008000000-embed02"+ UpdateBlockContentQueue(&other)+ if len(operationQueue) != 3 || operationQueue[0].recoveryEntry == nil || operationQueue[1].block.Content != latest.Content || operationQueue[2].block.Box != other.Box {+ t.Fatal("live embed update overwrote recovery or crossed notebook boundaries")+ }+}+func TestClearIndexQueuePreservesRawTail(t *testing.T) {prepareIndexQueueTest(t)appendOperation(&dbQueueOperation{action: "delete_box", box: "committed"})diff --git a/kernel/sql/index_recovery_fts5_test.go b/kernel/sql/index_recovery_fts5_test.goindex 930e88932f..9376a25310 100644--- a/kernel/sql/index_recovery_fts5_test.go+++ b/kernel/sql/index_recovery_fts5_test.go@@ -8,6 +8,7 @@ import ("os""os/exec""path/filepath"+ "strings""testing""time"@@ -55,7 +56,9 @@ func TestIndexRecoveryLifecycle(t *testing.T) {newTree := func() *parse.Tree {id := ast.NewNodeID()tree := treenode.NewTree(box, "/"+id+".sy", "/Recovery", "Recovery")- tree.Root.AppendChild(treenode.NewParagraph("recovery content"))+ paragraph := treenode.NewParagraph("")+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("recovery content")})+ tree.Root.AppendChild(paragraph)if _, err := filesys.WriteTree(tree); err != nil {t.Fatal(err)}@@ -166,6 +169,66 @@ func TestIndexRecoveryLifecycle(t *testing.T) {assertRows(second)})+ t.Run("embed content is recalculated and searchable after restart", func(t *testing.T) {+ ClearQueue()+ tree := newTree()+ source := tree.Root.LastChild+ embed := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeBlockQueryEmbed}+ embed.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript, Tokens: []byte("select * from blocks where id='" + source.ID + "'")})+ tree.Root.AppendChild(embed)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.IndexBlockTree(tree)+ IndexTreeQueue(tree)+ FlushQueue()+ block, _ := buildBlockFromNode(embed, tree)+ var sourceContent string+ if err := db.QueryRow("SELECT content FROM blocks WHERE id = ?", source.ID).Scan(&sourceContent); err != nil || sourceContent != "recovery content" {+ t.Fatalf("missing recovery query source: id=%s content=%q err=%v", source.ID, sourceContent, err)+ }+ if content, supported := CalculateEmbedBlockContent(block); !supported || content != sourceContent {+ t.Fatalf("query calculation failed before recovery: markdown=%q content=%q supported=%v", block.Markdown, content, supported)+ }+ block.Content = "old stale result"+ UpdateBlockContentQueue(block)+ FlushQueue()+ block.Content = "uncommitted result"+ UpdateBlockContentQueue(block)+ restartQueue()+ FlushQueue()+ var content string+ if err := db.QueryRow("SELECT content FROM blocks WHERE id = ?", embed.ID).Scan(&content); err != nil || content != "recovery content" {+ t.Fatalf("embed recovery indexed script or stale content: %q, %v", content, err)+ }+ var matches int+ if err := db.QueryRow("SELECT COUNT(*) FROM blocks_fts WHERE blocks_fts MATCH 'recovery' AND id = ?", embed.ID).Scan(&matches); err != nil || matches != 1 {+ t.Fatalf("recovered embed is not searchable: %d, %v", matches, err)+ }+ if len(loadIndexQueue()) != 0 {+ t.Fatal("completed embed recovery was not checkpointed")+ }++ for _, script := range []string{"//!js return [];", "select * from blocks where id='missing'"} {+ embed.FirstChild.Tokens = []byte(script)+ cache.RemoveTreeDataInBox(tree.ID, box)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ block.Content = "stale result"+ UpdateBlockContentQueue(block)+ restartQueue()+ FlushQueue()+ want := "no query result"+ if strings.HasPrefix(script, "//!js") {+ want = ""+ }+ if err := db.QueryRow("SELECT content FROM blocks WHERE id = ?", embed.ID).Scan(&content); err != nil || content != want {+ t.Fatalf("unsupported or empty embed recovery: %q, %v", content, err)+ }+ }+ })+t.Run("locked notebook recovery does not block ordinary documents", func(t *testing.T) {ClearQueue()isEncrypted := IsEncryptedBoxFndiff --git a/kernel/sql/queue.go b/kernel/sql/queue.goindex c4058128d1..b62145d296 100644--- a/kernel/sql/queue.go+++ b/kernel/sql/queue.go@@ -519,7 +519,7 @@ func UpdateBlockContentQueue(block *Block) {newOp := &dbQueueOperation{block: block, inQueueTime: time.Now(), action: "update_block_content"}for i, op := range operationQueue {- if "update_block_content" == op.action && op.block.ID == block.ID {+ if "update_block_content" == op.action && op.recoveryEntry == nil && op.block.ID == block.ID && op.block.Box == block.Box {operationQueue[i] = newOpreturn}