Skip to content

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

:bug: Correct block reference counts after cross-document moves https://github.com/siyuan-note/siyuan/issues/18828

Daniel867f67488734
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index 8e1e678eee..acca9b1a21 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -69,6 +69,75 @@ func refreshRefsByDefID(defID string) {
}
}
+type refTreeLocation struct {
+ RootID string
+ BoxID string
+}
+
+func refreshCrossTreeMoveRefs(refreshes []crossTreeMoveRefRefresh) {
+ if 1 > len(refreshes) {
+ return
+ }
+
+ // 先确保块索引已经反映移动后的文档归属,再按稳定的定义块 ID 重建引用方索引。
+ sql.FlushQueue()
+ movedDefIDsByBox := map[string][]string{}
+ rootIDs := []string{}
+ rootIDSet := map[string]struct{}{}
+ for _, refresh := range refreshes {
+ movedDefIDsByBox[refresh.BoxID] = append(movedDefIDsByBox[refresh.BoxID], refresh.MovedBlockIDs...)
+ for _, rootID := range []string{refresh.OldRootID, refresh.NewRootID} {
+ if "" == rootID {
+ continue
+ }
+ if _, ok := rootIDSet[rootID]; ok {
+ continue
+ }
+ rootIDSet[rootID] = struct{}{}
+ rootIDs = append(rootIDs, rootID)
+ }
+ }
+
+ refTreeLocations := []refTreeLocation{}
+ refTreeLocationSet := map[string]struct{}{}
+ affectedDefIDs := []string{}
+ affectedDefIDSet := map[string]struct{}{}
+ for boxID, movedDefIDs := range movedDefIDsByBox {
+ refs := sql.QueryRefsByDefIDsInBox(movedDefIDs, boxID)
+ for _, ref := range refs {
+ if _, ok := affectedDefIDSet[ref.DefBlockID]; !ok {
+ affectedDefIDSet[ref.DefBlockID] = struct{}{}
+ affectedDefIDs = append(affectedDefIDs, ref.DefBlockID)
+ }
+ locationKey := ref.Box + "\x00" + ref.RootID
+ if _, ok := refTreeLocationSet[locationKey]; ok {
+ continue
+ }
+ refTreeLocationSet[locationKey] = struct{}{}
+ refTreeLocations = append(refTreeLocations, refTreeLocation{RootID: ref.RootID, BoxID: ref.Box})
+ }
+ }
+
+ for _, location := range refTreeLocations {
+ refTree, err := loadTreeByBlockIDInBox(location.RootID, location.BoxID)
+ if nil != err {
+ logging.LogWarnf("load moved block ref tree [%s] in box [%s] failed: %s",
+ location.RootID, location.BoxID, err)
+ continue
+ }
+ sql.UpdateRefsTreeQueue(refTree)
+ }
+ sql.FlushQueue()
+
+ for _, rootID := range rootIDs {
+ refreshRefCount(rootID)
+ }
+ for _, defID := range affectedDefIDs {
+ refreshRefCount(defID)
+ }
+ ResetVirtualBlockRefCache()
+}
+
type Backlink struct {
ID string `json:"id"`
DOM string `json:"dom"`
diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.go
index 16e0ac111e..ed97a6b444 100644
--- a/kernel/model/push_reload.go
+++ b/kernel/model/push_reload.go
@@ -271,17 +271,17 @@ func refreshRefCount(blockID string) {
isDoc := bt.ID == bt.RootID
var rootRefIDs []string
var refCount, rootRefCount int
- refIDs := sql.QueryRefIDsByDefID(bt.ID, isDoc)
+ refIDs := sql.QueryRefIDsByDefIDInBox(bt.ID, isDoc, bt.BoxID)
if isDoc {
rootRefIDs = refIDs
} else {
- rootRefIDs = sql.QueryRefIDsByDefID(bt.RootID, true)
+ rootRefIDs = sql.QueryRefIDsByDefIDInBox(bt.RootID, true, bt.BoxID)
}
refCount = len(refIDs)
rootRefCount = len(rootRefIDs)
var defIDs []string
if isDoc {
- defIDs = sql.QueryChildDefIDsByRootDefID(bt.ID)
+ defIDs = sql.QueryChildDefIDsByRootDefIDInBox(bt.ID, bt.BoxID)
} else {
defIDs = append(defIDs, bt.ID)
}
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 9230fbf203..d25b5ff712 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -692,8 +692,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
tx.writeTree(srcTree)
if !isSameTree {
tx.writeTree(targetTree)
- task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, srcTree.ID)
- task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, srcNode.ID)
+ tx.recordCrossTreeMoveRefRefresh(srcTree, targetTree, srcNode, headingChildren)
}
return
}
@@ -783,8 +782,7 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
tx.writeTree(srcTree)
if !isSameTree {
tx.writeTree(targetTree)
- task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, srcTree.ID)
- task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, srcNode.ID)
+ tx.recordCrossTreeMoveRefRefresh(srcTree, targetTree, srcNode, headingChildren)
}
return
}
@@ -1122,6 +1120,7 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {
tx.writeTree(srcTree)
if !isSameTree {
tx.writeTree(targetTree)
+ tx.recordCrossTreeMoveRefRefresh(srcTree, targetTree, srcNode, headingChildren)
}
return
}
@@ -2286,6 +2285,60 @@ func (tx *Transaction) validateStructureChanges() (ret *TxErr) {
return
}
+type crossTreeMoveRefRefresh struct {
+ BoxID string
+ OldRootID string
+ NewRootID string
+ MovedBlockIDs []string
+}
+
+func collectCrossTreeMovedBlockIDs(srcNode *ast.Node, headingChildren []*ast.Node) (ret []string) {
+ seen := map[string]struct{}{}
+ appendNode := func(node *ast.Node) {
+ if nil == node {
+ return
+ }
+ for _, id := range node.BlockIDs() {
+ if _, ok := seen[id]; ok {
+ continue
+ }
+ seen[id] = struct{}{}
+ ret = append(ret, id)
+ }
+ }
+ appendNode(srcNode)
+ for _, child := range headingChildren {
+ appendNode(child)
+ }
+ return
+}
+
+func (tx *Transaction) recordCrossTreeMoveRefRefresh(srcTree, targetTree *parse.Tree, srcNode *ast.Node,
+ headingChildren []*ast.Node) {
+ if nil == srcTree || nil == targetTree || srcTree.ID == targetTree.ID {
+ return
+ }
+ movedBlockIDs := collectCrossTreeMovedBlockIDs(srcNode, headingChildren)
+ if 1 > len(movedBlockIDs) {
+ return
+ }
+
+ for i := range tx.crossTreeMoveRefRefreshes {
+ refresh := &tx.crossTreeMoveRefRefreshes[i]
+ if refresh.BoxID != targetTree.Box || refresh.OldRootID != srcTree.ID || refresh.NewRootID != targetTree.ID {
+ continue
+ }
+ refresh.MovedBlockIDs = gulu.Str.RemoveDuplicatedElem(append(refresh.MovedBlockIDs, movedBlockIDs...))
+ return
+ }
+ tx.crossTreeMoveRefRefreshes = append(tx.crossTreeMoveRefRefreshes, crossTreeMoveRefRefresh{
+ BoxID: targetTree.Box,
+ OldRootID: srcTree.ID,
+ NewRootID: targetTree.ID,
+ MovedBlockIDs: movedBlockIDs,
+ })
+}
+
type Transaction struct {
Timestamp int64 `json:"timestamp"`
DoOperations []*Operation `json:"doOperations"`
@@ -2306,10 +2359,11 @@ type Transaction struct {
fromAPI bool // 是否来自 /api/transactions HTTP 入口(用于撤销日志捕获判别)
isReplay bool // 是否为 undo/redo 重放构造的事务(重放不再进入撤销日志)
- listItemFoldCandidates []listItemFoldCandidate
- listItemFoldCandidateIDs map[string]struct{}
- deletedAttrViewBlockIDs map[string]map[string]struct{}
- structureCheckNodes map[*ast.Node]struct{}
+ listItemFoldCandidates []listItemFoldCandidate
+ listItemFoldCandidateIDs map[string]struct{}
+ deletedAttrViewBlockIDs map[string]map[string]struct{}
+ structureCheckNodes map[*ast.Node]struct{}
+ crossTreeMoveRefRefreshes []crossTreeMoveRefRefresh
luteEngine *lute.Lute
m *sync.Mutex
@@ -2368,6 +2422,7 @@ func (tx *Transaction) begin() (err error) {
tx.listItemFoldCandidateIDs = map[string]struct{}{}
tx.deletedAttrViewBlockIDs = map[string]map[string]struct{}{}
tx.structureCheckNodes = map[*ast.Node]struct{}{}
+ tx.crossTreeMoveRefRefreshes = nil
tx.luteEngine = util.NewLute()
tx.m.Lock()
tx.state.Store(1)
@@ -2431,11 +2486,16 @@ func (tx *Transaction) commit() (err error) {
PushCreate(box, tree.Path, nil)
}
+ crossTreeMoveRefRefreshes := append([]crossTreeMoveRefRefresh(nil), tx.crossTreeMoveRefRefreshes...)
IncSync()
tx.state.Store(2)
// 已提交且 trees 稳定后记录到全局撤销日志(rollback 不记录)
GlobalUndoLog.Record(tx)
tx.m.Unlock()
+ if 0 < len(crossTreeMoveRefRefreshes) {
+ task.AppendAsyncTaskWithDelay(task.RefreshCrossTreeMoveRefs, util.SQLFlushInterval,
+ refreshCrossTreeMoveRefs, crossTreeMoveRefRefreshes)
+ }
return
}
@@ -2444,6 +2504,7 @@ func (tx *Transaction) rollback() {
tx.listItemFoldCandidates, tx.listItemFoldCandidateIDs = nil, nil
tx.deletedAttrViewBlockIDs = nil
tx.structureCheckNodes = nil
+ tx.crossTreeMoveRefRefreshes = nil
tx.state.Store(3)
tx.m.Unlock()
return
diff --git a/kernel/model/transaction_test.go b/kernel/model/transaction_test.go
index 64268f57c3..79eb1b7874 100644
--- a/kernel/model/transaction_test.go
+++ b/kernel/model/transaction_test.go
@@ -16,7 +16,12 @@
package model
-import "testing"
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+)
func TestDoUpdateRejectsInvalidData(t *testing.T) {
tests := []any{nil, 1, ""}
@@ -40,3 +45,52 @@ func TestTxErrFromPanic(t *testing.T) {
t.Fatal("expected a committed transaction panic to preserve the committed result")
}
}
+
+func TestRecordCrossTreeMoveRefRefreshIncludesHeadingChildren(t *testing.T) {
+ const (
+ boxID = "20260818000000-box0001"
+ oldRootID = "20260818000001-root001"
+ newRootID = "20260818000002-root001"
+ headingID = "20260818000003-heading"
+ paragraphID = "20260818000004-parag01"
+ listID = "20260818000005-list001"
+ listItemID = "20260818000006-listitm"
+ listParaID = "20260818000007-parag02"
+ )
+
+ heading := &ast.Node{Type: ast.NodeHeading, ID: headingID}
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: paragraphID}
+ list := &ast.Node{Type: ast.NodeList, ID: listID, ListData: &ast.ListData{Typ: 0}}
+ listItem := &ast.Node{Type: ast.NodeListItem, ID: listItemID, ListData: &ast.ListData{Typ: 0}}
+ listParagraph := &ast.Node{Type: ast.NodeParagraph, ID: listParaID}
+ listItem.AppendChild(listParagraph)
+ list.AppendChild(listItem)
+
+ tx := &Transaction{}
+ srcTree := &parse.Tree{ID: oldRootID, Box: boxID}
+ targetTree := &parse.Tree{ID: newRootID, Box: boxID}
+ tx.recordCrossTreeMoveRefRefresh(srcTree, targetTree, heading, []*ast.Node{paragraph, list})
+ // 同一跨文档移动记录再次追加时应合并并去重。
+ tx.recordCrossTreeMoveRefRefresh(srcTree, targetTree, heading, []*ast.Node{list})
+
+ if 1 != len(tx.crossTreeMoveRefRefreshes) {
+ t.Fatalf("unexpected refresh count: %d", len(tx.crossTreeMoveRefRefreshes))
+ }
+ refresh := tx.crossTreeMoveRefRefreshes[0]
+ if boxID != refresh.BoxID || oldRootID != refresh.OldRootID || newRootID != refresh.NewRootID {
+ t.Fatalf("unexpected refresh roots: %+v", refresh)
+ }
+ actual := map[string]bool{}
+ for _, id := range refresh.MovedBlockIDs {
+ actual[id] = true
+ }
+ wantIDs := []string{headingID, paragraphID, listID, listItemID, listParaID}
+ if len(wantIDs) != len(refresh.MovedBlockIDs) {
+ t.Fatalf("unexpected moved block IDs: %v", refresh.MovedBlockIDs)
+ }
+ for _, id := range wantIDs {
+ if !actual[id] {
+ t.Fatalf("moved block ID [%s] was not recorded: %v", id, refresh.MovedBlockIDs)
+ }
+ }
+}
diff --git a/kernel/sql/block_ref_query_test.go b/kernel/sql/block_ref_query_test.go
index ea8cc381c2..e538901503 100644
--- a/kernel/sql/block_ref_query_test.go
+++ b/kernel/sql/block_ref_query_test.go
@@ -18,6 +18,7 @@ package sql
import (
gosql "database/sql"
+ "fmt"
"testing"
)
@@ -112,3 +113,59 @@ func TestInvalidRefsAreNotIndexedAndAreCleaned(t *testing.T) {
t.Fatalf("cleanup should retain only valid refs: count=%d, err=%v", count, err)
}
}
+
+func TestQueryRefsByDefIDsInBoxBatchesAndParameterizesIDs(t *testing.T) {
+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")
+ if nil != err {
+ t.Fatalf("open test database failed: %s", err)
+ }
+ testDB.SetMaxOpenConns(1)
+ defer testDB.Close()
+ if _, err = testDB.Exec("CREATE TABLE refs (id TEXT, def_block_id TEXT, def_block_parent_id TEXT, " +
+ "def_block_root_id TEXT, def_block_path TEXT, block_id TEXT, root_id TEXT, box TEXT, path TEXT, " +
+ "content TEXT, markdown TEXT, type TEXT)"); nil != err {
+ t.Fatalf("create refs table failed: %s", err)
+ }
+ lastIndex := queryRefsByDefIDsBatchSize
+ if _, err = testDB.Exec(`WITH RECURSIVE seq(n) AS (
+ SELECT 0
+ UNION ALL
+ SELECT n + 1 FROM seq WHERE n < ?
+ )
+ INSERT INTO refs
+ SELECT printf('ref-%d', n), printf('def-%d', n), '', 'old-root', '', printf('block-%d', n),
+ 'ref-root', 'box', '/ref.sy', '', '', '' FROM seq`, lastIndex); nil != err {
+ t.Fatalf("insert refs failed: %s", err)
+ }
+
+ previousDB := db
+ db = testDB
+ defer func() {
+ db = previousDB
+ }()
+
+ defIDs := make([]string, 0, lastIndex+4)
+ for i := 0; i <= lastIndex; i++ {
+ defIDs = append(defIDs, fmt.Sprintf("def-%d", i))
+ }
+ defIDs = append(defIDs, "", "def-0", `"); DELETE FROM refs --`)
+ refs := QueryRefsByDefIDsInBox(defIDs, "")
+ if lastIndex+1 != len(refs) {
+ t.Fatalf("unexpected refs count: got %d, want %d", len(refs), lastIndex+1)
+ }
+ actual := map[string]bool{}
+ for _, ref := range refs {
+ actual[ref.DefBlockID] = true
+ }
+ if !actual["def-0"] || !actual[fmt.Sprintf("def-%d", lastIndex)] {
+ t.Fatalf("batched query missed boundary refs: %#v", actual)
+ }
+
+ var count int
+ if err = testDB.QueryRow("SELECT COUNT(*) FROM refs").Scan(&count); nil != err {
+ t.Fatalf("query ref count failed: %s", err)
+ }
+ if lastIndex+1 != count {
+ t.Fatalf("query argument changed stored refs, count: %d", count)
+ }
+}
diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.go
index e45aa76031..a22ed22290 100644
--- a/kernel/sql/encrypted_query.go
+++ b/kernel/sql/encrypted_query.go
@@ -138,6 +138,52 @@ func QueryRefsByDefIDInBox(defBlockID string, containChildren bool, boxID string
return
}
+const queryRefsByDefIDsBatchSize = 512
+
+// QueryRefsByDefIDsInBox 按一组定义块 ID 查询引用,按 boxID 路由。
+func QueryRefsByDefIDsInBox(defBlockIDs []string, boxID string) (ret []*Ref) {
+ uniqueDefIDs := make([]string, 0, len(defBlockIDs))
+ seenDefIDs := map[string]struct{}{}
+ for _, defID := range defBlockIDs {
+ if "" == defID {
+ continue
+ }
+ if _, ok := seenDefIDs[defID]; ok {
+ continue
+ }
+ seenDefIDs[defID] = struct{}{}
+ uniqueDefIDs = append(uniqueDefIDs, defID)
+ }
+
+ for start := 0; start < len(uniqueDefIDs); start += queryRefsByDefIDsBatchSize {
+ end := min(start+queryRefsByDefIDsBatchSize, len(uniqueDefIDs))
+ batch := uniqueDefIDs[start:end]
+ placeholders := strings.TrimSuffix(strings.Repeat("?,", len(batch)), ",")
+ args := make([]any, 0, len(batch))
+ for _, defID := range batch {
+ args = append(args, defID)
+ }
+
+ rows, err := queryForBox(boxID, "SELECT * FROM refs WHERE def_block_id IN ("+placeholders+")", args...)
+ if err != nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ return
+ }
+ for rows.Next() {
+ if ref := scanRefRows(rows); nil != ref {
+ ret = append(ret, ref)
+ }
+ }
+ if err = rows.Err(); nil != err {
+ logging.LogErrorf("query rows failed: %s", err)
+ rows.Close()
+ return
+ }
+ rows.Close()
+ }
+ return
+}
+
// QueryRootChildrenRefCountInBox 按 defRootID 在指定 box 的 db 里查询根文档下各块的引用计数。
func QueryRootChildrenRefCountInBox(defRootID, boxID string) (ret map[string]int) {
ret = map[string]int{}
@@ -500,6 +546,25 @@ func QueryChildRefDefIDsByRootDefIDInBox(rootDefID, boxID string) (ret map[strin
return
}
+// QueryChildDefIDsByRootDefIDInBox 按定义文档根 ID 查询存在引用的子定义块,按 boxID 路由。
+func QueryChildDefIDsByRootDefIDInBox(rootDefID, boxID string) (ret []string) {
+ rows, err := queryForBox(boxID, "SELECT DISTINCT(def_block_id) FROM refs WHERE def_block_root_id = ?", rootDefID)
+ if err != nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ if err = rows.Scan(&id); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret = append(ret, id)
+ }
+ return
+}
+
// QueryRefIDsByDefIDInBox 按 defID 查引用 ID 列表,按 boxID 路由。
func QueryRefIDsByDefIDInBox(defID string, containChildren bool, boxID string) (refIDs []string) {
refIDs = []string{}
diff --git a/kernel/task/queue.go b/kernel/task/queue.go
index e53f0fe621..9a769df426 100644
--- a/kernel/task/queue.go
+++ b/kernel/task/queue.go
@@ -225,6 +225,7 @@ const (
ReloadFiletree = "task.reload.filetree" // 重新加载文档树面板
SetRefDynamicText = "task.ref.setDynamicText" // 设置引用的动态锚文本
SetDefRefCount = "task.def.setRefCount" // 设置定义的引用计数
+ RefreshCrossTreeMoveRefs = "task.ref.refreshCrossTreeMove" // 刷新跨文档移动块的引用索引
UpdateIDs = "task.update.ids" // 更新 ID
PushMsg = "task.push.msg" // 推送消息
)
@@ -250,6 +251,7 @@ var uniqueActions = []string{
ReloadFiletree,
SetRefDynamicText,
SetDefRefCount,
+ RefreshCrossTreeMoveRefs,
UpdateIDs,
}