Skip to content

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

:bug: Align reference rebuild detection with normal indexing https://github.com/siyuan-note/siyuan/issues/20942

Daniel0cc56d3f2c95
diff --git a/kernel/model/index.go b/kernel/model/index.go
index 97ca6656f3..e9cff2bc77 100644
--- a/kernel/model/index.go
+++ b/kernel/model/index.go
@@ -17,7 +17,6 @@
package model
import (
- "bytes"
"context"
"fmt"
"io/fs"
@@ -372,7 +371,7 @@ func IndexRefs() {
for _, treeAbsPath := range paths {
p := filepath.ToSlash(strings.TrimPrefix(treeAbsPath, filepath.Join(util.DataDir, box.ID)))
- // 加密笔记本的 .sy 是密文,必须走 filesys.LoadTree 透明解密;无法用 bytes.Contains 预检
+ // Encrypted documents must be authenticated by filesys.LoadTree.
var tree *parse.Tree
if encryptedBox {
loadTree, loadErr := filesys.LoadTree(box.ID, p, luteEngine)
@@ -388,10 +387,6 @@ func IndexRefs() {
continue
}
- if !bytes.Contains(data, []byte("TextMarkBlockRefID")) && !bytes.Contains(data, []byte("TextMarkFileAnnotationRefID")) {
- continue
- }
-
parseTree, parseErr := filesys.LoadTreeByData(data, box.ID, p, luteEngine)
if nil != parseErr {
logging.LogWarnf("parse json to tree [%s] failed: %s", treeAbsPath, parseErr)
@@ -400,17 +395,10 @@ func IndexRefs() {
tree = parseTree
}
- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
- if !entering {
- return ast.WalkContinue
- }
-
- if treenode.IsBlockRef(n) || treenode.IsFileAnnotationRef(n) {
- defBlockIDs = append(defBlockIDs, tree.Root.ID)
- defBlockBoxes[tree.Root.ID] = box.ID
- }
- return ast.WalkContinue
- })
+ if sql.TreeHasRefs(tree) {
+ defBlockIDs = append(defBlockIDs, tree.Root.ID)
+ defBlockBoxes[tree.Root.ID] = box.ID
+ }
}
}
}
diff --git a/kernel/model/index_refs_fts5_test.go b/kernel/model/index_refs_fts5_test.go
new file mode 100644
index 0000000000..3279881a9b
--- /dev/null
+++ b/kernel/model/index_refs_fts5_test.go
@@ -0,0 +1,121 @@
+//go:build fts5
+
+package model
+
+import (
+ "context"
+ gosql "database/sql"
+ "os"
+ "os/exec"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestIndexRefsMatchesNormalIndex(t *testing.T) {
+ if os.Getenv("SIYUAN_TEST_INDEX_REFS") != "1" {
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestIndexRefsMatchesNormalIndex$", "-test.v")
+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_INDEX_REFS=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("reference reindex subprocess: %v\n%s", err, output)
+ }
+ return
+ }
+ prepareHPathRefreshTest(t)
+ box := &Box{ID: ast.NewNodeID()}
+ boxConf := conf.NewBoxConf()
+ boxConf.Closed = false
+ if err := box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ definition := newHPathTestDoc(t, box.ID, "/", "Definition", 1)
+ for _, kind := range []string{"block", "embed", "title", "database", "annotation"} {
+ tree := newHPathTestDoc(t, box.ID, "/", kind, 1)
+ var node *ast.Node
+ switch kind {
+ case "block":
+ node = treenode.NewParagraph("")
+ node.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: definition.ID,
+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: "Definition"})
+ case "embed":
+ node = &ast.Node{Type: ast.NodeBlockQueryEmbed, ID: ast.NewNodeID()}
+ node.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript, Tokens: []byte("select * from blocks where id='" + definition.ID + "'")})
+ case "title":
+ node = &ast.Node{Type: ast.NodeCallout, ID: ast.NewNodeID(), CalloutType: "NOTE", CalloutTitleExplicit: true,
+ CalloutTitle: "((" + definition.ID + ` "Definition"))`}
+ node.AppendChild(treenode.NewParagraph(""))
+ case "database":
+ view := av.NewAttributeView(ast.NewNodeID())
+ view.KeyValues = append(view.KeyValues, &av.KeyValues{
+ Key: &av.Key{ID: ast.NewNodeID(), Type: av.KeyTypeText},
+ Values: []*av.Value{{Type: av.KeyTypeText, Text: &av.ValueText{Rich: &av.ValueTextRich{
+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,
+ Content: "((" + definition.ID + ` "Definition"))`,
+ }}}},
+ })
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ node = &ast.Node{Type: ast.NodeAttributeView, ID: ast.NewNodeID(), AttributeViewID: view.ID}
+ case "annotation":
+ node = treenode.NewParagraph("")
+ node.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "file-annotation-ref",
+ TextMarkFileAnnotationRefID: "assets/document.pdf/20261026000000-annot01", TextMarkTextContent: "Annotation"})
+ }
+ node.SetIALAttr("id", node.ID)
+ tree.Root.AppendChild(node)
+ if err := writeTreeUpsertQueue(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ }
+ sql.FlushQueue()
+ database, err := gosql.Open("sqlite3_extended", util.DBPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer database.Close()
+ read := func() []string {
+ t.Helper()
+ rows, err := database.Query("SELECT root_id || ':' || block_id || ':' || def_block_id || ':' || type FROM refs UNION ALL SELECT root_id || ':' || block_id || ':' || file_path || ':' || annotation_id FROM file_annotation_refs ORDER BY 1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var result []string
+ for rows.Next() {
+ var value string
+ if err = rows.Scan(&value); err != nil {
+ t.Fatal(err)
+ }
+ result = append(result, value)
+ }
+ if err = rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ return result
+ }
+ want := read()
+ if len(want) != 5 {
+ t.Fatalf("normal index did not include all reference fixtures: %v", want)
+ }
+ for _, table := range []string{"refs", "file_annotation_refs"} {
+ if _, err = database.Exec("DELETE FROM " + table); err != nil {
+ t.Fatal(err)
+ }
+ }
+ IndexRefs()
+ sql.FlushQueue()
+ if got := read(); !reflect.DeepEqual(got, want) {
+ t.Fatalf("reference rebuild differs from normal indexing:\n got %v\nwant %v", got, want)
+ }
+}
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 8ba97a2c6e..054b910a08 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -561,6 +561,13 @@ func SetIndexAssetPath(b bool) {
indexAssetPath.Store(b)
}
+// TreeHasRefs uses the same extraction as normal indexing, including rich
+// inline titles, attribute views and embedded references.
+func TreeHasRefs(tree *parse.Tree) bool {
+ refs, annotations := refsFromTree(tree)
+ return len(refs) > 0 || len(annotations) > 0
+}
+
func refsFromTree(tree *parse.Tree) (refs []*Ref, fileAnnotationRefs []*FileAnnotationRef) {
treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if entering {