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: Prevent incomplete mentions after candidate filtering
Danielb012b373b48a
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex a6248063e7..13a2b6fe07 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -1059,10 +1059,16 @@ func quoteFTSPhrase(phrase string) string {return "\"" + strings.ReplaceAll(phrase, "\"", "\"\"") + "\""}-func buildBackmentionQuery(matchExpression, rootID string, limit int) (query string, args []any) {+func buildBackmentionQuery(matchExpression, rootID, beforeID string, limit int) (query string, args []any) {query = "SELECT * FROM blocks_fts WHERE blocks_fts MATCH ? AND root_id != ?" +- " AND type IN ('d', 'h', 'p', 't') ORDER BY id DESC LIMIT ?"- args = []any{matchExpression, rootID, limit}+ " AND type IN ('d', 'h', 'p', 't')"+ args = []any{matchExpression, rootID}+ if "" != beforeID {+ query += " AND id < ?"+ args = append(args, beforeID)+ }+ query += " ORDER BY id DESC LIMIT ?"+ args = append(args, limit)return}@@ -1091,77 +1097,75 @@ func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBacif "" != keyword {buf.WriteString(" AND (" + quoteFTSPhrase(keyword) + ")")}- query, args := buildBackmentionQuery(buf.String(), rootID, Conf.Search.Limit)-- sqlBlocks := sql.SelectBlocksRawStmtArgsInBox(query, args, Conf.Search.Limit, boxID)terms := mentionKeywordsif "" != keyword {terms = append(terms, keyword)}- blocks := fromSQLBlocks(&sqlBlocks, strings.Join(terms, search.TermSep), beforeLen)-luteEngine := util.NewLute()- var tmp []*Block- for _, b := range blocks {- tree := parse.Parse("", gulu.Str.ToBytes(b.Markdown), luteEngine.ParseOptions)- if nil == tree {- continue+ limit := Conf.Search.Limit+ beforeID := ""+ // 按块 ID 分批补取候选,正文校验和反链排除后的有效提及才占用结果额度。+ for len(ret) < limit {+ query, args := buildBackmentionQuery(buf.String(), rootID, beforeID, limit)+ sqlBlocks := sql.SelectBlocksRawStmtArgsInBox(query, args, limit, boxID)+ if len(sqlBlocks) == 0 {+ break}-- textBuf := &bytes.Buffer{}- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering || n.IsBlock() {- return ast.WalkContinue+ beforeID = sqlBlocks[len(sqlBlocks)-1].ID+ blocks := fromSQLBlocks(&sqlBlocks, strings.Join(terms, search.TermSep), beforeLen)+ for _, b := range blocks {+ if excludeBacklinkIDs.Contains(b.ID) {+ continue}- if ast.NodeText == n.Type /* NodeText 包含了标签命中的情况 */ || ast.NodeLinkText == n.Type {- textBuf.Write(n.Tokens)+ tree := parse.Parse("", gulu.Str.ToBytes(b.Markdown), luteEngine.ParseOptions)+ if nil == tree {+ continue}- return ast.WalkContinue- })- text := textBuf.String()- text = strings.TrimSpace(text)- if "" == text {- continue- }+ textBuf := &bytes.Buffer{}+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if !entering || n.IsBlock() {+ return ast.WalkContinue+ }+ if ast.NodeText == n.Type /* NodeText 包含了标签命中的情况 */ || ast.NodeLinkText == n.Type {+ textBuf.Write(n.Tokens)+ }+ return ast.WalkContinue+ })- newText, matched := markReplaceSpanWithSplit(text, mentionKeywords, search.GetMarkSpanStart(search.MarkDataType), search.GetMarkSpanEnd())- if matched {- tmp = append(tmp, b)+ text := textBuf.String()+ text = strings.TrimSpace(text)+ if "" == text {+ continue+ }- k := getMarkedTextContents(newText, search.GetMarkSpanStart(search.MarkDataType), search.GetMarkSpanEnd())- retMentionKeywords = append(retMentionKeywords, k...)- } else {- // columnFilter 中的命名、别名和备注命中的情况- // 反链提及搜索范围增加命名、别名和备注 https://github.com/siyuan-note/siyuan/issues/7639- if gulu.Str.Contains(trimMarkTags(b.Name), mentionKeywords) ||- gulu.Str.Contains(trimMarkTags(b.Alias), mentionKeywords) ||- gulu.Str.Contains(trimMarkTags(b.Memo), mentionKeywords) {- tmp = append(tmp, b)+ newText, matched := markReplaceSpanWithSplit(text, mentionKeywords, search.GetMarkSpanStart(search.MarkDataType), search.GetMarkSpanEnd())+ if matched {+ ret = append(ret, b)++ k := getMarkedTextContents(newText, search.GetMarkSpanStart(search.MarkDataType), search.GetMarkSpanEnd())+ retMentionKeywords = append(retMentionKeywords, k...)+ } else {+ // columnFilter 中的命名、别名和备注命中的情况+ // 反链提及搜索范围增加命名、别名和备注 https://github.com/siyuan-note/siyuan/issues/7639+ if gulu.Str.Contains(trimMarkTags(b.Name), mentionKeywords) ||+ gulu.Str.Contains(trimMarkTags(b.Alias), mentionKeywords) ||+ gulu.Str.Contains(trimMarkTags(b.Memo), mentionKeywords) {+ ret = append(ret, b)+ }}+ if len(ret) == limit {+ break+ }+ }+ if len(sqlBlocks) < limit {+ break}}- blocks = tmpretMentionKeywords = gulu.Str.RemoveDuplicatedElem(retMentionKeywords)- mentionKeywords = retMentionKeywords-- mentionBlockMap := map[string]*Block{}- for _, block := range blocks {- mentionBlockMap[block.ID] = block-- refText := getContainStr(block.Content, mentionKeywords)- block.RefText = refText+ for _, block := range ret {+ block.RefText = getContainStr(block.Content, retMentionKeywords)}-- for _, mentionBlock := range mentionBlockMap {- if !excludeBacklinkIDs.Contains(mentionBlock.ID) {- ret = append(ret, mentionBlock)- }- }-- sort.SliceStable(ret, func(i, j int) bool {- return ret[i].ID > ret[j].ID- })return}diff --git a/kernel/model/backlink_mention_fts5_test.go b/kernel/model/backlink_mention_fts5_test.gonew file mode 100644index 0000000000..788345879e--- /dev/null+++ b/kernel/model/backlink_mention_fts5_test.go@@ -0,0 +1,170 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/emirpasic/gods/sets/hashset"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestBacklinkMentionFilteredPagination(t *testing.T) {+ for _, encrypted := range []bool{false, true} {+ name := "plain"+ if encrypted {+ name = "encrypted"+ }+ t.Run(name, func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Search = conf.NewSearch()+ var trees []*parse.Tree+ for _, id := range []string{fixture.sourceID, fixture.targetID} {+ tree, err := LoadTreeByBlockID(id)+ if err != nil {+ t.Fatal(err)+ }+ for tree.Root.FirstChild != nil {+ tree.Root.FirstChild.Unlink()+ }+ trees = append(trees, tree)+ }+ boxID := ""+ if encrypted {+ boxID = fixture.box.ID+ dek := bytes.Repeat([]byte{0x65}, 32)+ markRuntimeEncryptedBox(boxID)+ setDEKForTest(boxID, dek)+ boxConf := conf.NewBoxConf()+ boxConf.Encrypted = true+ boxConf.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec}+ if err := encryptBoxMetadata(boxID, boxConf, dek); err != nil {+ t.Fatal(err)+ }+ data, err := json.Marshal(boxConf)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), data, 0600); err != nil {+ t.Fatal(err)+ }+ mountedEncryptedBoxes.Store(boxID, true)+ t.Cleanup(func() {+ sql.CloseEncryptedDB(boxID)+ treenode.CloseEncryptedBlockTreeDB(boxID)+ mountedEncryptedBoxes.Delete(boxID)+ forgetRuntimeEncryptedBox(boxID)+ encryptedBoxLifecycles.Delete(boxID)+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ })+ if err = treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {+ t.Fatal(err)+ }+ if err = sql.OpenEncryptedDB(boxID, dek); err != nil {+ t.Fatal(err)+ }+ }+ trees[0].Root.SetIALAttr("title", "needle")+ trees[0].HPath = "/needle"+ self := treenode.NewParagraph("20260926160009-self001")+ self.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("needle")})+ trees[0].Root.AppendChild(self)+ ids := []string{+ "20260926160001-mention", "20260926160002-mention",+ "20260926160003-mention", "20260926160004-mention",+ "20260926160005-ref0001", "20260926160006-ref0002",+ "20260926160007-ref0004", "20260926160008-ref0003",+ }+ for i, id := range ids {+ p := treenode.NewParagraph(id)+ switch i {+ case 1:+ p.SetIALAttr("name", "needle")+ p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("metadata match")})+ case 4, 5, 7:+ if i != 5 {+ p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("needle ")})+ }+ p.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref",+ TextMarkBlockRefID: fixture.sourceID, TextMarkBlockRefSubtype: "s", TextMarkTextContent: "broad"})+ case 6:+ p.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref",+ TextMarkBlockRefID: fixture.targetID, TextMarkBlockRefSubtype: "s", TextMarkTextContent: "broad"})+ default:+ p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("needle")})+ }+ trees[1].Root.AppendChild(p)+ }+ for _, tree := range trees {+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.UpdateRefsTreeQueue(tree)+ }+ sql.FlushQueue()+ query, args := buildBackmentionQuery(columnFilter()+`:("needle" OR "broad")`, fixture.sourceID, "", 64)+ if candidates := sql.SelectBlocksRawStmtArgsInBox(query, args, 64, boxID); len(candidates) != len(ids) {+ var candidateIDs []string+ for _, candidate := range candidates {+ candidateIDs = append(candidateIDs, candidate.ID)+ }+ t.Fatalf("fixture should contain %d candidates, got %v", len(ids), candidateIDs)+ }+ excluded := hashset.New(ids[4], ids[5], ids[7])+ for _, limit := range []int{1, 2, 3, 4, 5, 64} {+ Conf.Search.Limit = limit+ want := []string{ids[3], ids[2], ids[1], ids[0]}+ if limit < len(want) {+ want = want[:limit]+ }+ for _, keyword := range []string{"", "needle", "absent"} {+ keywords, blocks := searchBackmentionInBox([]string{"needle", "broad"}, keyword, excluded, fixture.sourceID, 12, boxID)+ if keyword == "absent" {+ if len(blocks) != 0 || len(keywords) != 0 {+ t.Fatal("unmatched keyword returned mentions")+ }+ continue+ }+ var got []string+ for _, block := range blocks {+ got = append(got, block.ID)+ }+ if !reflect.DeepEqual(got, want) || !reflect.DeepEqual(keywords, []string{"needle"}) {+ t.Fatalf("limit %d, keyword %q: got %v/%v, want %v/[needle]", limit, keyword, got, keywords, want)+ }+ _, _, mentions, _, count := GetBacklink2InBox(fixture.sourceID, "", keyword, 0, 0, false, boxID)+ if len(mentions) != 1 || count != len(want) {+ t.Fatalf("list limit %d, keyword %q: got %d groups/%d mentions, want 1/%d", limit, keyword, len(mentions), count, len(want))+ }+ }+ }+ Conf.Search.Limit = 2+ _, blocks := searchBackmentionInBox([]string{"needle", "broad"}, "", hashset.New(ids[0], ids[1], ids[2], ids[3], ids[4], ids[5], ids[7]), fixture.sourceID, 12, boxID)+ if len(blocks) != 0 {+ t.Fatal("fully filtered candidates returned mentions")+ }+ if encrypted {+ _, blocks = searchBackmention([]string{"needle", "broad"}, "", excluded, fixture.sourceID, 12)+ if len(blocks) != 0 {+ t.Fatal("encrypted mentions leaked into global search")+ }+ }+ })+ }+}diff --git a/kernel/model/backlink_test.go b/kernel/model/backlink_test.goindex 2824cad534..1a7be5d866 100644--- a/kernel/model/backlink_test.go+++ b/kernel/model/backlink_test.go@@ -45,7 +45,7 @@ func TestQuoteFTSPhrase(t *testing.T) {func TestBuildBackmentionQueryBindsValues(t *testing.T) {matchExpression := `content:("stored'title") AND ("client'keyword")`rootID := "root'id"- query, args := buildBackmentionQuery(matchExpression, rootID, 64)+ query, args := buildBackmentionQuery(matchExpression, rootID, "", 64)if strings.Contains(query, matchExpression) || strings.Contains(query, rootID) {t.Fatalf("query contains an unbound value: %s", query)@@ -57,4 +57,13 @@ func TestBuildBackmentionQueryBindsValues(t *testing.T) {if !reflect.DeepEqual(args, expectedArgs) {t.Fatalf("expected arguments %#v, got %#v", expectedArgs, args)}+ beforeID := "cursor'id"+ query, args = buildBackmentionQuery(matchExpression, rootID, beforeID, 64)+ if strings.Contains(query, beforeID) || !strings.Contains(query, "AND id < ?") {+ t.Fatalf("cursor must be bound as an exclusive upper boundary: %s", query)+ }+ expectedArgs = []any{matchExpression, rootID, beforeID, 64}+ if !reflect.DeepEqual(args, expectedArgs) {+ t.Fatalf("expected arguments %#v, got %#v", expectedArgs, args)+ }}