An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Improve performance when renaming documents with large subtrees https://github.com/siyuan-note/siyuan/issues/19562
Daniel2ae56c71db8e
diff --git a/docs/DOCUMENT-HPATH.md b/docs/DOCUMENT-HPATH.mdnew file mode 100644index 0000000000..7ea1bbc532--- /dev/null+++ b/docs/DOCUMENT-HPATH.md@@ -0,0 +1,33 @@+# 文档重命名与路径索引++重命名文档时,源文档立即保存,块树数据库中的文档行同步更新。按可读路径定位或创建文档仍使用最新文档路径。内容库及块树库中内容块的 `hpath` 副本在后台逐步更新,SQL 查询在此期间可能读到新旧路径混合的结果。++## 更新方式++- 纯重命名不加载后代正文,不删除重建后代块树,不修改后代 `.sy` 文件+- 相同文档的重复重命名合并处理;父任务可以覆盖后代的批量更新,但每个改名源文档保留独立恢复记录+- 文档行通过按笔记本、数据路径建立的局部索引定位,避免为了统计子树规模扫描全部内容块+- 后台每次最多运行约 20 毫秒,每批最多更新两库各 512 行,根据实测批次耗时在 32 至 512 行之间调整;单条语句不能强行打断,所以预算不是严格的延迟上限+- 批次之间释放数据库事务和锁,普通编辑及索引队列优先,同步期间暂停后台更新;默认每 100 毫秒调度一次+- 执行批次前重新读取文档位置与路径,并在块树写锁内校验快照;普通索引操作使用当前文档路径,避免旧队列写回过期的 `hpath`+- 移动仍走原有流程,后台路径更新不会修改笔记本归属或真实数据路径++## 恢复与加密兼容++`conf/hpath-refresh.json` 是版本为 `1` 的本地任务记录,不参与笔记数据同步。记录只包含笔记本 ID、文档 ID 和由 ID 组成的数据路径,不存储标题、正文、密钥或块游标。源文档写入前先持久化记录,完成两个数据库的全部批次后才清除。进程中断后从头检查,已更新的行不再重复写入。++启动时先从源文档恢复用于定位的文档元数据,再后台补齐内容块路径。恢复读取会认证加密文件、检查文档格式和身份;缺失、损坏或认证失败时保留源文件及任务,不补建父文档。加密笔记本每个后台调度周期持有操作租约,锁定后暂停,重新解锁并建立索引后继续。此次改动不改变 `.sy` 密文格式、AAD、密钥材料、历史、备份或同步格式。++普通索引队列新增 `rename_doc` 操作,仅及时更新文档标题和文档行。既有 `rename` 记录继续按原有逐文档方式恢复。后台任务独立于普通队列的整批快照清理,避免仅完成第一批就丢失恢复记录。++## 回归验证++在 `kernel/` 执行:++```text+go test -tags "fts5 sqlcipher" ./model ./sql ./treenode ./filesys -run "Test(DocumentHPathRefresh|EncryptedDocumentHPathRefresh|IndexQueueRenameRecovery|ReadDocHPathDoesNotRepairSource|HPathRefreshYieldsToBlockTreeWriter)" -count=1+```++这些测试包含有界更新、后代文件和块树行身份保持不变、按新路径创建文档、重复及父子改名、旧编辑快照、部分更新后的恢复、源文件已保存但元数据未更新时的恢复、数据库写入失败、移动、删除、同步标题、加密锁定及重新解锁、密文保持不变和认证失败保留原数据。它们也包含在 CI 的完整内核测试命令 `go test -tags "fts5 sqlcipher" ./... -count=1` 中。++耗时超过一秒的后台任务会记录文档数、批次数、总耗时和实际数据库批次耗时。评估性能时应同时观察前台响应时间、CPU 和磁盘读写量,不应将包含调度等待的总耗时视为数据库写入时间。diff --git a/kernel/filesys/hpath.go b/kernel/filesys/hpath.gonew file mode 100644index 0000000000..b758304c99--- /dev/null+++ b/kernel/filesys/hpath.go@@ -0,0 +1,32 @@+package filesys++import (+ "path/filepath"+ "strings"++ "github.com/siyuan-note/siyuan/kernel/util"+)++// ReadDocHPath 只读文档属性并认证加密源文件,不解析块树、不修复或补建任何文件。+func ReadDocHPath(boxID, p string) (hpath string, properties map[string]string, err error) {+ if p, err = ValidateBoxRelativePath(boxID, p); err != nil {+ return+ }+ parts := strings.Split(strings.TrimPrefix(filepath.ToSlash(p), "/"), "/")+ for i := range parts {+ docPath := strings.Join(parts[:i+1], "/")+ if i < len(parts)-1 {+ docPath += ".sy"+ }+ properties, err = readDocIAL(filepath.Join(util.DataDir, boxID, docPath), true)+ if err != nil {+ return "", nil, err+ }+ title := properties["title"]+ if title == "" && i < len(parts)-1 {+ title = "Untitled"+ }+ hpath += "/" + title+ }+ return+}diff --git a/kernel/filesys/hpath_test.go b/kernel/filesys/hpath_test.gonew file mode 100644index 0000000000..3c547d4f6a--- /dev/null+++ b/kernel/filesys/hpath_test.go@@ -0,0 +1,55 @@+package filesys++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestReadDocHPathDoesNotRepairSource(t *testing.T) {+ previous := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = previous })+ box := "20260915000000-hpath01"+ parent := "20260915000001-hpath01"+ child := "20260915000002-hpath01"+ dir := filepath.Join(util.DataDir, box, parent)+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ writeDoc := func(id, p, title string) {+ t.Helper()+ data, err := json.Marshal(map[string]any{"ID": id, "Type": "NodeDocument", "Properties": map[string]string{"id": id, "title": title}})+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(p, data, 0600); err != nil {+ t.Fatal(err)+ }+ }+ childPath := "/" + parent + "/" + child + ".sy"+ writeDoc(child, filepath.Join(dir, child+".sy"), "Child")+ parentFile := filepath.Join(util.DataDir, box, parent+".sy")+ if _, _, err := ReadDocHPath(box, childPath); !os.IsNotExist(err) {+ t.Fatalf("expected missing parent error, got %v", err)+ }+ if _, err := os.Stat(parentFile); !os.IsNotExist(err) {+ t.Fatal("read-only recovery created a parent file")+ }+ writeDoc(parent, parentFile, "Parent")+ if hpath, props, err := ReadDocHPath(box, childPath); err != nil || hpath != "/Parent/Child" || props["id"] != child {+ t.Fatalf("unexpected path metadata: %q, %#v, %v", hpath, props, err)+ }+ writeDoc(child, parentFile, "Wrong identity")+ before, _ := os.ReadFile(parentFile)+ if _, _, err := ReadDocHPath(box, childPath); err == nil {+ t.Fatal("mismatched source identity was accepted")+ }+ after, _ := os.ReadFile(parentFile)+ if string(before) != string(after) {+ t.Fatal("failed recovery modified the source")+ }+}diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex ed53f1fc0f..3c955b4ba7 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -325,6 +325,10 @@ func checkTreeFile(absPath string) error {// readParentDocIAL 区分父文档缺失与读取、认证、解析失败,只有缺失才允许补树。func readParentDocIAL(absPath string) (map[string]string, error) {+ return readDocIAL(absPath, false)+}++func readDocIAL(absPath string, strict bool) (map[string]string, error) {boxID := docIALBoxID(absPath)dek, _, release, err := acquireCryptoLease(boxID)if err != nil {@@ -343,12 +347,22 @@ func readParentDocIAL(absPath string) (map[string]string, error) {if err != nil {return nil, err}+ if strict {+ if err = treenode.CheckSpecJSON(data); err != nil {+ return nil, err+ }+ }var doc struct {+ ID string+ Type stringProperties map[string]string}if err = json.Unmarshal(data, &doc); err != nil {return nil, fmt.Errorf("parse parent document [%s]: %w", absPath, err)}+ if strict && (doc.ID != util.GetTreeID(absPath) || doc.Type != "NodeDocument") {+ return nil, fmt.Errorf("invalid document identity [%s]", absPath)+ }if len(doc.Properties) == 0 {return nil, fmt.Errorf("missing parent document properties [%s]", absPath)}diff --git a/kernel/job/cron.go b/kernel/job/cron.goindex 0173828f3a..5ffbf18357 100644--- a/kernel/job/cron.go+++ b/kernel/job/cron.go@@ -36,6 +36,7 @@ func StartCron() {go every(2*time.Hour, model.RefreshCheckJob2H)go every(6*time.Hour, model.RefreshCheckJob6H)go every(3*time.Second, model.FlushUpdateRefTextRenameDocJob)+ go every(100*time.Millisecond, model.RefreshHPathsJob)go every(util.SQLFlushInterval, sql.FlushTxJob)go every(util.SQLFlushInterval, sql.FlushHistoryTxJob)go every(util.SQLFlushInterval, sql.FlushAssetContentTxJob)diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex edfe14b61e..335bb3f160 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -1057,6 +1057,9 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int, isql.FlushQueue()util.IsExiting.Store(true)+ // 等待正在执行的路径批次退出,未完成任务保留在配置目录供下次启动恢复。+ hpathRefresh.Lock()+ hpathRefresh.Unlock()newVerInstallPkgPath := getNewVerInstallPkgPath()if !skipNewVerInstallPkg() && "" != newVerInstallPkgPath {if 2 == execInstallPkg || (force && 0 == execInstallPkg) { // 将新版本安装包交给桌面宿主执行@@ -1337,6 +1340,7 @@ func InitBoxes() {}}+ recoverDocHPaths()logging.LogInfof("tree/block count [%d/%d]", treenode.CountTrees(), blockCount)}diff --git a/kernel/model/file.go b/kernel/model/file.goindex 868dee2e83..b1065d536d 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1223,12 +1223,10 @@ func indexWriteTreeUpsertQueue(tree *parse.Tree) (err error) {}func renameWriteJSONQueue(tree *parse.Tree) (err error) {- size, err := filesys.WriteTree(tree)+ size, err := writeRenameDoc(tree)if err != nil {return}- sql.RenameTreeQueue(tree)- treenode.UpsertBlockTree(tree)refreshDocInfoWithSize(tree, size)return}@@ -1889,6 +1887,9 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin}}+ // 文件位置和块树索引切换期间暂停后台路径任务,避免将移动中的文档误判为已删除。+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()needMoveSubDocs := fromBox.Exist(fromFolder)if needMoveSubDocs {// 移动子文档文件夹@@ -2239,21 +2240,6 @@ func renameDoc0(boxID, p, title string) (err error) {return}- subFiles := box.ListFiles(tree.Path)- for _, subFile := range subFiles {- if !strings.HasSuffix(subFile.path, ".sy") {- continue- }-- subTree, loadErr := filesys.LoadTree(box.ID, subFile.path, luteEngine) // LoadTree 会重新构造 HPath- if loadErr != nil {- continue- }-- treenode.SetBlockTreePath(subTree)- sql.RenameTreeQueue(subTree)- }-refText := getNodeRefText(tree.Root)evt := util.NewCmdResult("rename", 0, util.PushModeBroadcast)evt.Data = map[string]any{diff --git a/kernel/model/hpath_refresh.go b/kernel/model/hpath_refresh.gonew file mode 100644index 0000000000..203ac5703f--- /dev/null+++ b/kernel/model/hpath_refresh.go@@ -0,0 +1,429 @@+package model++import (+ "crypto/sha256"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/88250/lute/parse"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/logging"+ "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"+)++// 恢复记录只含稳定标识及数据路径,不能写入加密笔记本的标题或正文。+// 游标不持久化:重启后从源文档恢复路径,已完成的行不会重复写入。+type hpathRefreshEntry struct {+ Box string `json:"box"`+ ID string `json:"id"`+ Path string `json:"path"`+}++type hpathRefreshTask struct {+ hpathRefreshEntry+ due time.Time+ first time.Time+ recover bool+ docs []string+ index int+ blockAfter int64+ treeAfter int64+ fingerprint [32]byte+ scope [32]byte+ limit int+ covers map[string]*hpathRefreshTask+ started time.Time+ active time.Duration+ batches int+}++var hpathRefresh = struct {+ sync.Mutex+ file string+ tasks map[string]*hpathRefreshTask+ last string+}{}++func loadHPathRefreshLocked() error {+ p := filepath.Join(util.ConfDir, "hpath-refresh.json")+ if hpathRefresh.file == p && hpathRefresh.tasks != nil {+ return nil+ }+ tasks := map[string]*hpathRefreshTask{}+ data, err := os.ReadFile(p)+ if err != nil && !os.IsNotExist(err) {+ return err+ }+ if err == nil {+ var store struct {+ Version int `json:"version"`+ Tasks []hpathRefreshEntry `json:"tasks"`+ }+ if err = json.Unmarshal(data, &store); err != nil {+ return err+ }+ if store.Version != 1 {+ return fmt.Errorf("unsupported hpath refresh version %d", store.Version)+ }+ for _, entry := range store.Tasks {+ if entry.ID == "" || entry.Box == "" {+ return errors.New("invalid hpath refresh entry")+ }+ if _, err = filesys.ValidateBoxRelativePath(entry.Box, entry.Path); err != nil {+ return err+ }+ tasks[entry.Box+"/"+entry.ID] = &hpathRefreshTask{hpathRefreshEntry: entry, recover: true, limit: 256}+ }+ }+ hpathRefresh.file, hpathRefresh.tasks, hpathRefresh.last = p, tasks, ""+ return nil+}++func saveHPathRefreshLocked() error {+ entries := make([]hpathRefreshEntry, 0, len(hpathRefresh.tasks))+ for _, task := range hpathRefresh.tasks {+ entries = append(entries, task.hpathRefreshEntry)+ }+ sort.Slice(entries, func(i, j int) bool {+ return entries[i].Box+entries[i].ID < entries[j].Box+entries[j].ID+ })+ data, err := json.Marshal(struct {+ Version int `json:"version"`+ Tasks []hpathRefreshEntry `json:"tasks"`+ }{1, entries})+ if err != nil {+ return err+ }+ // WriteFile 使用临时文件、Sync 和替换,写入成功后才允许修改源文档。+ return filelock.WriteFile(hpathRefresh.file, data)+}++func queueHPathRefreshLocked(tree *parse.Tree) (key string, err error) {+ if err = loadHPathRefreshLocked(); err != nil {+ return+ }+ key = tree.Box + "/" + tree.ID+ first := time.Now()+ if old := hpathRefresh.tasks[key]; old != nil {+ first = old.first+ }+ // 后代再次改名时重置覆盖它的父任务;每个源文档仍保留恢复记录,避免合并后漏掉中断的写入。+ for otherKey, other := range hpathRefresh.tasks {+ if other.Box != tree.Box || otherKey == key {+ continue+ }+ bt := treenode.GetBlockTreeInBox(other.ID, other.Box)+ if bt == nil || bt.BoxID != tree.Box {+ continue+ }+ if strings.HasPrefix(tree.Path, strings.TrimSuffix(bt.Path, ".sy")+"/") {+ other.docs, other.index = nil, 0+ other.covers = nil+ other.blockAfter, other.treeAfter = 0, 0+ other.due = time.Now().Add(500 * time.Millisecond)+ }+ }+ previous := hpathRefresh.tasks[key]+ hpathRefresh.tasks[key] = &hpathRefreshTask{+ hpathRefreshEntry: hpathRefreshEntry{tree.Box, tree.ID, tree.Path},+ first: first, due: time.Now().Add(500 * time.Millisecond), recover: true, limit: 256,+ }+ if err = saveHPathRefreshLocked(); err != nil {+ if previous == nil {+ delete(hpathRefresh.tasks, key)+ } else {+ hpathRefresh.tasks[key] = previous+ }+ }+ return+}++func writeRenameDoc(tree *parse.Tree) (size uint64, err error) {+ if err = AcquireEncryptedBoxOperation(tree.Box); err != nil {+ return+ }+ defer ReleaseEncryptedBoxOperation(tree.Box)+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()+ if util.IsExiting.Load() {+ return 0, errors.New("kernel is exiting")+ }+ tree.HPath = treenode.CurrentParentHPath(tree)+ key, err := queueHPathRefreshLocked(tree)+ if err != nil {+ return 0, err+ }+ if size, err = filesys.WriteTree(tree); err != nil {+ return+ }+ if treenode.GetBlockTreeInBox(tree.ID, tree.Box) == nil {+ treenode.UpsertBlockTree(tree)+ }+ if err = treenode.RefreshDocHPaths(tree); err != nil {+ return+ }+ sql.RenameDocQueue(tree)+ hpathRefresh.tasks[key].recover = false+ return+}++// RefreshHPathsJob 每次最多处理一个批次,普通编辑和索引刷新优先。+func RefreshHPathsJob() {+ if !util.IsBooted() || util.IsExiting.Load() || txQueueSize() > 0 || isFlushing.Load() || !syncLock.TryLock() {+ return+ }+ defer syncLock.Unlock()+ if !databaseIndexDataLock.TryLock() {+ return+ }+ defer databaseIndexDataLock.Unlock()+ if !hpathRefresh.TryLock() {+ return+ }+ defer hpathRefresh.Unlock()+ if err := loadHPathRefreshLocked(); err != nil {+ logging.LogErrorf("load hpath refresh tasks failed: %s", err)+ return+ }+ var keys []string+ if len(hpathRefresh.tasks) == 0 {+ return+ }+ opened := map[string]bool{}+ for _, box := range Conf.GetOpenedBoxes() {+ opened[box.ID] = true+ }+ for key, task := range hpathRefresh.tasks {+ covered := false+ for _, parent := range hpathRefresh.tasks {+ if parent.covers[key] == task {+ covered = true+ break+ }+ }+ if covered {+ continue+ }+ if time.Now().Before(task.due) && time.Since(task.first) < 2*time.Second {+ continue+ }+ if !opened[task.Box] {+ continue+ }+ keys = append(keys, key)+ }+ if len(keys) == 0 {+ return+ }+ sort.Strings(keys)+ key := keys[0]+ for _, candidate := range keys {+ if candidate > hpathRefresh.last {+ key = candidate+ break+ }+ }+ // 先恢复所有源文档的元数据,再让父任务合并后代的批量路径更新。+ for _, candidate := range keys {+ if hpathRefresh.tasks[candidate].recover {+ key = candidate+ break+ }+ }+ hpathRefresh.last = key+ task := hpathRefresh.tasks[key]+ if err := AcquireEncryptedBoxOperation(task.Box); err != nil {+ return+ }+ defer ReleaseEncryptedBoxOperation(task.Box)+ start := time.Now()+ done, err := false, error(nil)+ for {+ index, blockAfter, treeAfter, recovering, docCount := task.index, task.blockAfter, task.treeAfter, task.recover, len(task.docs)+ done, err = refreshHPathsTask(task)+ if done || err != nil || time.Since(start) >= 20*time.Millisecond || txQueueSize() > 0 {+ break+ }+ if index == task.index && blockAfter == task.blockAfter && treeAfter == task.treeAfter && recovering == task.recover && docCount == len(task.docs) {+ break+ }+ }+ if err != nil {+ // 失败保留源文件和恢复记录;重试重新读取当前位置及标题。+ task.docs, task.index, task.recover = nil, 0, true+ task.covers = nil+ task.blockAfter, task.treeAfter = 0, 0+ task.first, task.due = time.Now().Add(5*time.Second), time.Now().Add(5*time.Second)+ logging.LogWarnf("refresh document hpaths [%s] failed: %s", key, err)+ return+ }+ if done {+ removed := map[string]*hpathRefreshTask{key: task}+ root := treenode.GetBlockTreeInBox(task.ID, task.Box)+ for coveredKey, covered := range task.covers {+ if hpathRefresh.tasks[coveredKey] != covered || root == nil {+ continue+ }+ doc := treenode.GetBlockTreeInBox(covered.ID, root.BoxID)+ if doc != nil && doc.BoxID == root.BoxID && strings.HasPrefix(doc.Path, strings.TrimSuffix(root.Path, ".sy")+"/") {+ removed[coveredKey] = covered+ delete(hpathRefresh.tasks, coveredKey)+ }+ }+ delete(hpathRefresh.tasks, key)+ if err = saveHPathRefreshLocked(); err != nil {+ for removedKey, removedTask := range removed {+ hpathRefresh.tasks[removedKey] = removedTask+ }+ logging.LogErrorf("save hpath refresh tasks failed: %s", err)+ return+ }+ sql.ClearCache()+ util.BroadcastByType("main", "databaseIndexCommit", 0, "", map[string]any{"rootIDs": []string{task.ID}, "backlinkChanged": true, "backlinkFull": true})+ if !task.started.IsZero() && time.Since(task.started) > time.Second {+ logging.LogInfof("refreshed document hpaths [%s], docs [%d], batches [%d], elapsed [%dms], active [%dms]", key, len(task.docs), task.batches, time.Since(task.started).Milliseconds(), task.active.Milliseconds())+ }+ }+}++func refreshHPathsTask(task *hpathRefreshTask) (done bool, err error) {+ if task.started.IsZero() {+ task.started = time.Now()+ }+ root := treenode.GetBlockTreeInBox(task.ID, task.Box)+ if !IsEncryptedBox(task.Box) && (root == nil || root.BoxID != task.Box) {+ root = treenode.GetBlockTree(task.ID)+ if root != nil && IsEncryptedBox(root.BoxID) {+ return false, errors.New("hpath refresh crossed an encrypted notebook boundary")+ }+ }+ if root == nil {+ // 索引尚未恢复时不能丢弃磁盘上仍存在的文档任务。+ if _, statErr := os.Stat(filepath.Join(util.DataDir, task.Box, task.Path)); statErr == nil {+ return false, errors.New("hpath refresh document is not indexed")+ } else if !os.IsNotExist(statErr) {+ return false, statErr+ }+ return true, nil+ }+ scope := sha256.Sum256([]byte(root.BoxID + "\x00" + root.Path + "\x00" + root.HPath))+ if task.scope != scope {+ task.docs, task.index, task.covers = nil, 0, nil+ task.blockAfter, task.treeAfter = 0, 0+ task.scope = scope+ }+ if task.docs == nil {+ if task.recover {+ hpath, properties, loadErr := filesys.ReadDocHPath(root.BoxID, root.Path)+ if loadErr != nil {+ return false, loadErr+ }+ tree := treenode.NewTree(root.BoxID, root.Path, hpath, properties["title"])+ tree.Root.KramdownIAL = nil+ for key, value := range properties {+ tree.Root.SetIALAttr(key, value)+ }+ if err = treenode.RefreshDocHPaths(tree); err != nil {+ return false, err+ }+ sql.RenameDocQueue(tree)+ task.recover = false+ return false, nil+ }+ for _, other := range hpathRefresh.tasks {+ if other.recover && other.Box == root.BoxID {+ bt := treenode.GetBlockTreeInBox(other.ID, other.Box)+ if bt != nil && (strings.HasPrefix(bt.Path, strings.TrimSuffix(root.Path, ".sy")+"/") || strings.HasPrefix(root.Path, strings.TrimSuffix(bt.Path, ".sy")+"/")) {+ return false, nil+ }+ }+ }+ docs, listErr := treenode.DocHPaths(root.BoxID, root.Path)+ if listErr != nil {+ return false, listErr+ }+ task.docs = make([]string, 0, len(docs))+ for _, doc := range docs {+ task.docs = append(task.docs, doc.ID)+ }+ task.covers = map[string]*hpathRefreshTask{}+ for key, other := range hpathRefresh.tasks {+ if other == task || other.Box != root.BoxID {+ continue+ }+ bt := treenode.GetBlockTreeInBox(other.ID, other.Box)+ if bt != nil && bt.BoxID == root.BoxID && strings.HasPrefix(bt.Path, strings.TrimSuffix(root.Path, ".sy")+"/") {+ task.covers[key] = other+ }+ }+ }+ if task.index >= len(task.docs) {+ current := treenode.GetBlockTreeInBox(root.ID, root.BoxID)+ if current == nil || current.BoxID != root.BoxID || current.Path != root.Path || current.HPath != root.HPath {+ return false, errors.New("document changed before hpath refresh completed")+ }+ return true, nil+ }+ doc := treenode.GetBlockTreeInBox(task.docs[task.index], root.BoxID)+ if doc == nil || doc.BoxID != root.BoxID || (doc.Path != root.Path && !strings.HasPrefix(doc.Path, strings.TrimSuffix(root.Path, ".sy")+"/")) {+ task.index+++ task.blockAfter, task.treeAfter = 0, 0+ return false, nil+ }+ fingerprint := sha256.Sum256([]byte(doc.BoxID + "\x00" + doc.Path + "\x00" + doc.HPath))+ if task.fingerprint != fingerprint {+ task.blockAfter, task.treeAfter = 0, 0+ task.fingerprint = fingerprint+ }+ start := time.Now()+ blockAfter, treeAfter, docDone, busy, err := sql.RefreshHPathsBatch(doc, task.blockAfter, task.treeAfter, task.limit)+ if err != nil || busy {+ return false, err+ }+ task.batches+++ task.active += time.Since(start)+ task.blockAfter, task.treeAfter = blockAfter, treeAfter+ if time.Since(start) > 25*time.Millisecond && task.limit > 32 {+ task.limit /= 2+ } else if time.Since(start) < 10*time.Millisecond && task.limit < 512 {+ task.limit *= 2+ }+ if docDone {+ task.index+++ task.blockAfter, task.treeAfter = 0, 0+ }+ return false, nil+}++// recoverDocHPaths 在启动时先恢复文档定位元数据,内容块副本继续由后台补齐。+func recoverDocHPaths() {+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()+ if err := loadHPathRefreshLocked(); err != nil {+ logging.LogErrorf("load document path recovery failed: %s", err)+ return+ }+ for _, task := range hpathRefresh.tasks {+ if !task.recover || Conf.Box(task.Box) == nil {+ continue+ }+ if err := AcquireEncryptedBoxOperation(task.Box); err != nil {+ continue+ }+ _, err := refreshHPathsTask(task)+ ReleaseEncryptedBoxOperation(task.Box)+ if err != nil {+ logging.LogErrorf("recover document paths [%s/%s] failed: %s", task.Box, task.ID, err)+ }+ }+}diff --git a/kernel/model/hpath_refresh_sqlcipher_test.go b/kernel/model/hpath_refresh_sqlcipher_test.gonew file mode 100644index 0000000000..6cf1c393d8--- /dev/null+++ b/kernel/model/hpath_refresh_sqlcipher_test.go@@ -0,0 +1,150 @@+//go:build fts5 && (sqlcipher || libsqlcipher)++package model++import (+ "bytes"+ "context"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/cache"+ "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 TestEncryptedDocumentHPathRefresh(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_ENCRYPTED_HPATH_REFRESH") != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestEncryptedDocumentHPathRefresh$", "-test.v")+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_ENCRYPTED_HPATH_REFRESH=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("encrypted hpath refresh subprocess: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ password := "hpath-refresh-test-password"+ if err := EnableEncryptedNotebook(password); err != nil {+ t.Fatal(err)+ }+ boxID, err := CreateEncryptedBox("Encrypted", password)+ if err != nil {+ t.Fatal(err)+ }+ if _, err = Mount(boxID); err != nil {+ t.Fatal(err)+ }+ parent := newHPathTestDoc(t, boxID, "/", "PrivateParent", 1)+ child := newHPathTestDoc(t, boxID, parent.Path, "PrivateChild", 400)+ // 先完成测试构造树的常规格式规范化,再保存用于检查重命名兼容性的密文基线。+ for _, docPath := range []string{parent.Path, child.Path} {+ cache.RemoveTreeData(util.GetTreeID(docPath))+ if _, err = filesys.LoadTree(boxID, docPath, util.NewLute()); err != nil {+ t.Fatal(err)+ }+ }+ sql.FlushQueue()+ childFile := filepath.Join(util.DataDir, boxID, child.Path)+ before, err := os.ReadFile(childFile)+ if err != nil || !util.IsCiphertext(before) {+ t.Fatalf("fixture is not encrypted: %v", err)+ }+ if err = RenameDoc(boxID, parent.Path, "PrivateRenamed"); err != nil {+ t.Fatal(err)+ }+ assertChildCiphertext := func(stage string) {+ t.Helper()+ data, readErr := os.ReadFile(childFile)+ if readErr != nil || !bytes.Equal(before, data) {+ t.Fatalf("descendant ciphertext changed at %s: %v", stage, readErr)+ }+ }+ assertChildCiphertext("rename")+ journal, err := os.ReadFile(filepath.Join(util.ConfDir, "hpath-refresh.json"))+ if err != nil || bytes.Contains(journal, []byte("Private")) {+ t.Fatalf("task journal leaked titles: %s, %v", journal, err)+ }+ boxEncryption, err := GetBoxEncryption(boxID)+ if err != nil {+ t.Fatal(err)+ }+ LockBox(boxID)+ assertChildCiphertext("lock")+ RefreshHPathsJob()+ if len(hpathRefresh.tasks) != 1 {+ t.Fatal("locked notebook lost its pending task")+ }+ if sql.GetEncryptedDB(boxID) != nil || treenode.GetBlockTreeInBox(child.ID, boxID) != nil {+ t.Fatal("background reopened a locked notebook")+ }+ if err = UnlockBox(boxID, password, boxEncryption); err != nil {+ t.Fatal(err)+ }+ if _, err = Mount(boxID); err != nil {+ t.Fatal(err)+ }+ assertChildCiphertext("mount")+ // 锁定会删除派生索引;解锁后使用认证过的原文件重建,再恢复未完成的任务。+ for _, original := range []struct{ id, path string }{{parent.ID, parent.Path}, {child.ID, child.Path}} {+ tree, loadErr := filesys.LoadTree(boxID, original.path, util.NewLute())+ if loadErr != nil {+ t.Fatal(loadErr)+ }+ assertChildCiphertext("load for reindex")+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ }+ drainHPathRefreshTest(t)+ assertHPathTestDoc(t, sql.GetEncryptedDB(boxID), child, "/PrivateRenamed/PrivateChild")+ after, err := os.ReadFile(childFile)+ if err != nil || !bytes.Equal(before, after) {+ t.Fatalf("rename or recovery rewrote descendant ciphertext: %v", err)+ }+ if sql.GetBlock(child.ID) != nil {+ t.Fatal("encrypted block escaped into the global index")+ }++ // 恢复时必须认证源密文;认证失败既不能回退明文,也不能清除恢复记录。+ if err = RenameDoc(boxID, parent.Path, "PrivateRetry"); err != nil {+ t.Fatal(err)+ }+ sql.FlushQueue()+ parentFile := filepath.Join(util.DataDir, boxID, parent.Path)+ original, err := os.ReadFile(parentFile)+ if err != nil {+ t.Fatal(err)+ }+ corrupt := append([]byte(nil), original...)+ corrupt[len(corrupt)-1] ^= 1+ if err = os.WriteFile(parentFile, corrupt, 0600); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeData(parent.ID)+ hpathRefresh.Lock()+ hpathRefresh.tasks, hpathRefresh.file = nil, ""+ if err = loadHPathRefreshLocked(); err != nil {+ t.Fatal(err)+ }+ task := hpathRefresh.tasks[boxID+"/"+parent.ID]+ _, recoveryErr := refreshHPathsTask(task)+ hpathRefresh.Unlock()+ if recoveryErr == nil {+ t.Fatal("corrupted source was accepted during recovery")+ }+ preserved, err := os.ReadFile(parentFile)+ if err != nil || !bytes.Equal(corrupt, preserved) || len(hpathRefresh.tasks) == 0 {+ t.Fatal("failed authentication changed source or dropped recovery")+ }+ if err = os.WriteFile(parentFile, original, 0600); err != nil {+ t.Fatal(err)+ }+ drainHPathRefreshTest(t)+ assertHPathTestDoc(t, sql.GetEncryptedDB(boxID), child, "/PrivateRetry/PrivateChild")+}diff --git a/kernel/model/hpath_refresh_test.go b/kernel/model/hpath_refresh_test.gonew file mode 100644index 0000000000..f0fce69fe4--- /dev/null+++ b/kernel/model/hpath_refresh_test.go@@ -0,0 +1,308 @@+//go:build fts5++package model++import (+ "bytes"+ "context"+ gosql "database/sql"+ "os"+ "os/exec"+ "path"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "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 TestDocumentHPathRefresh(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_HPATH_REFRESH") != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDocumentHPathRefresh$", "-test.v")+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_HPATH_REFRESH=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("hpath refresh subprocess: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ box := &Box{ID: "20260915000000-hpath01"}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "HPath", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ database, err := gosql.Open("sqlite3_extended", util.DBPath)+ if err != nil {+ t.Fatal(err)+ }+ defer database.Close()++ parent := newHPathTestDoc(t, box.ID, "/", "Parent", 1)+ child := newHPathTestDoc(t, box.ID, parent.Path, "Child", 1400)+ grandchild := newHPathTestDoc(t, box.ID, child.Path, "Grandchild", 4)+ sibling := newHPathTestDoc(t, box.ID, "/", "Parent", 2)+ sql.FlushQueue()+ childFile := filepath.Join(util.DataDir, child.Box, child.Path)+ before, err := os.ReadFile(childFile)+ if err != nil {+ t.Fatal(err)+ }+ btDatabase, err := gosql.Open("sqlite3_extended", util.BlockTreeDBPath)+ if err != nil {+ t.Fatal(err)+ }+ defer btDatabase.Close()+ var beforeRowID int64+ if err = btDatabase.QueryRow("SELECT rowid FROM blocktrees WHERE id = ?", child.Root.FirstChild.ID).Scan(&beforeRowID); err != nil {+ t.Fatal(err)+ }++ t.Run("bounded writes and immediate document lookup", func(t *testing.T) {+ if err := RenameDoc(box.ID, parent.Path, "Renamed"); err != nil {+ t.Fatal(err)+ }+ if got := treenode.GetBlockTreeRootByHPath(box.ID, "/Renamed/Child"); got == nil || got.ID != child.ID {+ t.Fatalf("new child path is not immediately addressable: %#v", got)+ }+ if got := treenode.GetBlockTreeInBox(child.Root.FirstChild.ID, box.ID); got.HPath != "/Parent/Child" {+ t.Fatalf("content block path was eagerly rewritten: %q", got.HPath)+ }+ after, err := os.ReadFile(childFile)+ if err != nil || !bytes.Equal(before, after) {+ t.Fatalf("renaming parent changed descendant file: %v", err)+ }+ var afterRowID int64+ if err = btDatabase.QueryRow("SELECT rowid FROM blocktrees WHERE id = ?", child.Root.FirstChild.ID).Scan(&afterRowID); err != nil || beforeRowID != afterRowID {+ t.Fatalf("descendant blocktree was rebuilt: %d, %d, %v", beforeRowID, afterRowID, err)+ }+ doc := treenode.GetBlockTreeInBox(child.ID, box.ID)+ if _, _, _, busy, err := sql.RefreshHPathsBatch(doc, 0, 0, 64); err != nil || !busy {+ t.Fatalf("background did not yield to pending indexes: busy=%v err=%v", busy, err)+ }+ sql.FlushQueue()+ if _, _, done, busy, err := sql.RefreshHPathsBatch(doc, 0, 0, 64); err != nil || busy || done {+ t.Fatalf("bounded batch failed: done=%v busy=%v err=%v", done, busy, err)+ }+ var changed int+ if err = database.QueryRow("SELECT COUNT(*) FROM blocks WHERE root_id = ? AND hpath = ?", child.ID, "/Renamed/Child").Scan(&changed); err != nil || changed == 0 || changed > 64 {+ t.Fatalf("batch exceeded row budget: %d, %v", changed, err)+ }+ newID, err := createDocsByHPathSync(box.ID, "/Renamed/Child/Added", "", child.ID, ast.NewNodeID(), false)+ if err != nil {+ t.Fatal(err)+ }+ newDoc := treenode.GetBlockTreeInBox(newID, box.ID)+ if newDoc == nil || path.Dir(newDoc.Path) != strings.TrimSuffix(child.Path, ".sy") {+ t.Fatalf("path creation duplicated the parent: %#v", newDoc)+ }+ })++ t.Run("rename coalescing and stale queued edit", func(t *testing.T) {+ stale, err := filesys.LoadTree(box.ID, child.Path, util.NewLute())+ if err != nil {+ t.Fatal(err)+ }+ if err = RenameDoc(box.ID, parent.Path, "Final"); err != nil {+ t.Fatal(err)+ }+ if err = RenameDoc(box.ID, child.Path, "Leaf"); err != nil {+ t.Fatal(err)+ }+ stale.HPath = "/Parent/Child"+ sql.UpsertTreeQueue(stale)+ drainHPathRefreshTest(t)+ assertHPathTestDoc(t, database, child, "/Final/Leaf")+ assertHPathTestDoc(t, database, grandchild, "/Final/Leaf/Grandchild")+ assertHPathTestDoc(t, database, sibling, "/Parent")+ })++ t.Run("interrupted source writes and restart", func(t *testing.T) {+ for _, item := range []struct {+ doc *parse.Tree+ title string+ }{{parent, "Recovered"}, {child, "RecoveredChild"}} {+ tree, err := filesys.LoadTree(box.ID, item.doc.Path, util.NewLute())+ if err != nil {+ t.Fatal(err)+ }+ tree.Root.SetIALAttr("title", item.title)+ tree.HPath = path.Join(path.Dir(tree.HPath), item.title)+ hpathRefresh.Lock()+ _, err = queueHPathRefreshLocked(tree)+ hpathRefresh.Unlock()+ if err != nil {+ t.Fatal(err)+ }+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ }+ hpathRefresh.Lock()+ hpathRefresh.tasks, hpathRefresh.file = nil, ""+ hpathRefresh.Unlock()+ recoverDocHPaths()+ if got := treenode.GetBlockTreeRootByHPath(box.ID, "/Recovered/RecoveredChild/Grandchild"); got == nil || got.ID != grandchild.ID {+ t.Fatalf("startup did not restore document metadata: %#v", got)+ }+ drainHPathRefreshTest(t)+ assertHPathTestDoc(t, database, grandchild, "/Recovered/RecoveredChild/Grandchild")+ })++ t.Run("failed content commit retains recovery", func(t *testing.T) {+ if err := RenameDoc(box.ID, parent.Path, "Retry"); err != nil {+ t.Fatal(err)+ }+ sql.FlushQueue()+ if _, err := database.Exec("CREATE TRIGGER fail_hpath BEFORE UPDATE OF hpath ON blocks BEGIN SELECT RAISE(ABORT, 'injected hpath failure'); END"); err != nil {+ t.Fatal(err)+ }+ doc := treenode.GetBlockTreeInBox(child.ID, box.ID)+ oldPath := treenode.GetBlockTreeInBox(child.Root.FirstChild.ID, box.ID).HPath+ if _, _, _, _, err := sql.RefreshHPathsBatch(doc, 0, 0, 64); err == nil {+ t.Fatal("injected commit failure was ignored")+ }+ if got := treenode.GetBlockTreeInBox(child.Root.FirstChild.ID, box.ID); got.HPath != oldPath {+ t.Fatal("blocktree batch was not rolled back")+ }+ if len(hpathRefresh.tasks) == 0 {+ t.Fatal("pending recovery was lost")+ }+ if _, err := database.Exec("DROP TRIGGER fail_hpath"); err != nil {+ t.Fatal(err)+ }+ drainHPathRefreshTest(t)+ assertHPathTestDoc(t, database, child, "/Retry/RecoveredChild")+ })++ t.Run("move delete and synced title", func(t *testing.T) {+ if err := RenameDoc(box.ID, parent.Path, "BeforeMove"); err != nil {+ t.Fatal(err)+ }+ destination := newHPathTestDoc(t, box.ID, "/", "Destination", 1)+ sql.FlushQueue()+ stale, err := filesys.LoadTree(box.ID, child.Path, util.NewLute())+ if err != nil {+ t.Fatal(err)+ }+ staleDoc := treenode.GetBlockTreeInBox(child.ID, box.ID)+ if err := MoveDocs([]string{box.ID + child.Path}, box.ID, destination.Path, nil); err != nil {+ t.Fatal(err)+ }+ moved := treenode.GetBlockTreeInBox(child.ID, box.ID)+ child.Path = moved.Path+ sql.RenameDocQueue(stale)+ sql.FlushQueue()+ assertHPathTestDoc(t, database, child, "/Destination/RecoveredChild")+ if err := treenode.RefreshDocHPaths(stale); err == nil {+ t.Fatal("stale recovery snapshot accepted after move")+ }+ if _, _, _, _, err := sql.RefreshHPathsBatch(staleDoc, 0, 0, 64); err == nil {+ t.Fatal("stale background batch accepted after move")+ }+ if err := RemoveDoc(box.ID, parent.Path); err != nil {+ t.Fatal(err)+ }+ tree, err := filesys.LoadTree(box.ID, destination.Path, util.NewLute())+ if err != nil {+ t.Fatal(err)+ }+ tree.Root.SetIALAttr("title", "Synced")+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ if ids := upsertIndexes([]string{box.ID + destination.Path}); len(ids) != 1 {+ t.Fatalf("sync did not index document: %v", ids)+ }+ drainHPathRefreshTest(t)+ assertHPathTestDoc(t, database, child, "/Synced/RecoveredChild")+ })+}++func prepareHPathRefreshTest(t *testing.T) {+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir, util.TempDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "conf")+ util.HistoryDir, util.QueueDir = filepath.Join(root, "history"), filepath.Join(util.TempDir, "queue")+ util.DBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, util.DBName), filepath.Join(util.TempDir, "blocktree.db")+ util.HistoryDBPath, util.AssetContentDBPath = filepath.Join(util.TempDir, "history.db"), filepath.Join(util.TempDir, "asset_content.db")+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir, util.QueueDir} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ }+ Conf = NewAppConf()+ Conf.FileTree, Conf.NotebookCrypto, Conf.Sync = conf.NewFileTree(), conf.NewNotebookCrypto(), conf.NewSync()+ Conf.Editor, Conf.Export, Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()+ Conf.Lang, util.Lang = "en", "en"+ util.StatusBarCfg = util.NewStatusBar(false)+ util.WorkingDir, _ = filepath.Abs(filepath.Join("..", "..", "app"))+ initLang()+ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ t.Cleanup(sql.CloseDatabase)+ util.SetBooted()+}++func newHPathTestDoc(t *testing.T, box, parentPath, title string, blocks int) *parse.Tree {+ id := ast.NewNodeID()+ p := path.Join(strings.TrimSuffix(parentPath, ".sy"), id+".sy")+ hpath := "/" + title+ if parentPath != "/" {+ parent := treenode.GetBlockTreeInBox(util.GetTreeID(parentPath), box)+ hpath = parent.HPath + "/" + title+ }+ tree := treenode.NewTree(box, p, hpath, title)+ for i := 1; i < blocks; i++ {+ tree.Root.AppendChild(treenode.NewParagraph("hpath refresh regression"))+ }+ if err := os.MkdirAll(filepath.Dir(filepath.Join(util.DataDir, box, p)), 0755); err != nil {+ t.Fatal(err)+ }+ if err := indexWriteTreeIndexQueue(tree); err != nil {+ t.Fatal(err)+ }+ return tree+}++func drainHPathRefreshTest(t *testing.T) {+ t.Helper()+ deadline := time.Now().Add(30 * time.Second)+ for time.Now().Before(deadline) {+ sql.FlushQueue()+ hpathRefresh.Lock()+ pending := len(hpathRefresh.tasks)+ for _, task := range hpathRefresh.tasks {+ task.due = time.Time{}+ }+ hpathRefresh.Unlock()+ if pending == 0 {+ return+ }+ RefreshHPathsJob()+ }+ t.Fatalf("hpath refresh did not finish: %#v", hpathRefresh.tasks)+}++func assertHPathTestDoc(t *testing.T, database *gosql.DB, tree *parse.Tree, expected string) {+ t.Helper()+ var total, wrong int+ if err := database.QueryRow("SELECT COUNT(*), COALESCE(SUM(hpath != ?), 0) FROM blocks WHERE root_id = ? AND box = ?", expected, tree.ID, tree.Box).Scan(&total, &wrong); err != nil || total == 0 || wrong != 0 {+ t.Fatalf("content paths for %s: total=%d wrong=%d expected=%s err=%v", tree.ID, total, wrong, expected, err)+ }+ for _, bt := range treenode.GetBlockTreesByRootIDInBox(tree.ID, tree.Box) {+ if bt.HPath != expected {+ t.Fatalf("blocktree path for %s: %s, expected %s", bt.ID, bt.HPath, expected)+ }+ }+}diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex bd7dc949cd..d249022e06 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -478,6 +478,8 @@ func upsertIndexes(upsertFilePaths []string) (upsertRootIDs []string) {}p := strings.TrimPrefix(upsertFile, box)+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()msg := fmt.Sprintf(Conf.Language(40), util.GetTreeID(p))util.IncBootProgress(bootProgressPart, msg)pushSyncStatusBar(msg)@@ -488,7 +490,23 @@ func upsertIndexes(upsertFilePaths []string) (upsertRootIDs []string) {if nil != err0 {return "", false}+ oldDoc := treenode.GetBlockTreeInBox(rootID, box)+ refreshPath := oldDoc != nil && oldDoc.BoxID == box && oldDoc.HPath != tree.HPath+ var refreshKey string+ if refreshPath {+ if refreshKey, err0 = queueHPathRefreshLocked(tree); err0 != nil {+ logging.LogErrorf("queue synced document hpaths [%s] failed: %s", rootID, err0)+ return "", false+ }+ }treenode.UpsertBlockTree(tree)+ if refreshPath {+ if err0 = treenode.RefreshDocHPaths(tree); err0 != nil {+ logging.LogErrorf("refresh synced document paths [%s] failed: %s", rootID, err0)+ return "", false+ }+ hpathRefresh.tasks[refreshKey].recover = false+ }sql.UpsertTreeQueue(tree)bts := treenode.GetBlockTreesByRootIDInBox(rootID, tree.Box)diff --git a/kernel/sql/hpath.go b/kernel/sql/hpath.gonew file mode 100644index 0000000000..c4711fd205--- /dev/null+++ b/kernel/sql/hpath.go@@ -0,0 +1,75 @@+package sql++import (+ "database/sql"+ "errors"++ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// RefreshHPathsBatch 只在普通索引空闲时执行一个批次,不占用普通任务队列等待下一批。+func RefreshHPathsBatch(doc *treenode.BlockTree, blockAfter, treeAfter int64, limit int) (nextBlock, nextTree int64, done, busy bool, err error) {+ if !initDatabaseLock.TryLock() {+ return blockAfter, treeAfter, false, true, nil+ }+ defer initDatabaseLock.Unlock()+ dbQueueLock.Lock()+ pending := len(operationQueue) != 0+ dbQueueLock.Unlock()+ if pending || util.IsExiting.Load() {+ return blockAfter, treeAfter, false, true, nil+ }+ nextBlock, nextTree = blockAfter, treeAfter+ blockDone := false+ nextTree, treeDone, err := treenode.RefreshBlockHPathsBatch(doc, treeAfter, limit, func() error {+ tx, txErr := beginTxForBox(doc.BoxID)+ if txErr != nil {+ return txErr+ }+ defer tx.Rollback()+ var last sql.NullInt64+ if txErr = tx.QueryRow("SELECT MAX(rowid) FROM (SELECT rowid FROM blocks WHERE root_id = ? AND box = ? AND path = ? AND rowid > ? ORDER BY rowid LIMIT ?)", doc.ID, doc.BoxID, doc.Path, blockAfter, limit).Scan(&last); txErr != nil {+ return txErr+ }+ blockDone = !last.Valid+ if last.Valid {+ rows, queryErr := tx.Query("SELECT id FROM blocks WHERE root_id = ? AND box = ? AND path = ? AND rowid > ? AND rowid <= ? AND hpath != ?", doc.ID, doc.BoxID, doc.Path, blockAfter, last.Int64, doc.HPath)+ if queryErr != nil {+ return queryErr+ }+ var ids []string+ for rows.Next() {+ var id string+ if queryErr = rows.Scan(&id); queryErr != nil {+ rows.Close()+ return queryErr+ }+ ids = append(ids, id)+ }+ queryErr = rows.Err()+ rows.Close()+ if queryErr != nil {+ return queryErr+ }+ if len(ids) > 0 {+ if _, txErr = tx.Exec("UPDATE blocks SET hpath = ? WHERE root_id = ? AND box = ? AND path = ? AND rowid > ? AND rowid <= ? AND hpath != ?", doc.HPath, doc.ID, doc.BoxID, doc.Path, blockAfter, last.Int64, doc.HPath); txErr != nil {+ return txErr+ }+ }+ if txErr = tx.Commit(); txErr != nil {+ return txErr+ }+ for _, id := range ids {+ removeBlockCache(id)+ }+ nextBlock = last.Int64+ return nil+ }+ return tx.Commit()+ })+ if errors.Is(err, treenode.ErrHPathRefreshBusy) {+ return blockAfter, treeAfter, false, true, nil+ }+ return nextBlock, nextTree, blockDone && treeDone, false, err+}diff --git a/kernel/sql/index_queue.go b/kernel/sql/index_queue.goindex b1dbd1127e..63e95c5d3d 100644--- a/kernel/sql/index_queue.go+++ b/kernel/sql/index_queue.go@@ -107,8 +107,8 @@ func dbOpToIndexEntry(op *dbQueueOperation) *indexEntry {return &indexEntry{Action: "upsert", ID: op.upsertTree.ID, Box: op.upsertTree.Box, Path: op.upsertTree.Path}case "index":return &indexEntry{Action: "index", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}- case "rename":- return &indexEntry{Action: "rename", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}+ case "rename", "rename_doc":+ return &indexEntry{Action: op.action, ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}case "move":return &indexEntry{Action: "move", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}case "update_refs":@@ -273,13 +273,13 @@ func indexEntryToOp(e indexEntry, luteEngine *lute.Lute, prefix string) *dbQueuereturn nil}return &dbQueueOperation{indexTree: tree, inQueueTime: time.Now(), action: "index"}- case "rename":+ case "rename", "rename_doc":tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)if err != nil {logIndexEntryLoadError(prefix, "rename", e, err)return nil}- return &dbQueueOperation{indexTree: tree, inQueueTime: time.Now(), action: "rename"}+ return &dbQueueOperation{indexTree: tree, inQueueTime: time.Now(), action: e.Action}case "move":tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)if err != nil {diff --git a/kernel/sql/index_queue_test.go b/kernel/sql/index_queue_test.goindex 7647fa111d..7430f411ae 100644--- a/kernel/sql/index_queue_test.go+++ b/kernel/sql/index_queue_test.go@@ -17,11 +17,59 @@package sqlimport (+ "os"+ "path/filepath""testing"+ "github.com/88250/lute"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")+func TestIndexQueueRenameRecovery(t *testing.T) {+ prepareIndexQueueTest(t)+ oldDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = oldDataDir })+ box := "20260915000000-hpath01"+ id := "20260915000001-hpath01"+ if err := os.MkdirAll(filepath.Join(util.DataDir, box), 0755); err != nil {+ t.Fatal(err)+ }+ tree := treenode.NewTree(box, "/"+id+".sy", "/Latest", "Latest")+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ for _, action := range []string{"rename", "rename_doc"} {+ entry := dbOpToIndexEntry(&dbQueueOperation{action: action, indexTree: tree})+ op := indexEntryToOp(*entry, lute.New(), "test rename recovery")+ if op == nil || op.action != action || op.indexTree.HPath != "/Latest" {+ t.Fatalf("rename queue format did not recover: %s, %#v", action, op)+ }+ }++ RenameDocQueue(tree)+ latest := *tree+ latest.HPath = "/Newer"+ RenameDocQueue(&latest)+ other := *tree+ other.Box = "20260915000002-hpath02"+ RenameDocQueue(&other)+ ops, _ := getOperations()+ if len(ops) != 2 {+ t.Fatalf("unexpected coalesced operations: %d", len(ops))+ }+ byBox := map[string]*parse.Tree{}+ for _, op := range ops {+ byBox[op.indexTree.Box] = op.indexTree+ }+ if byBox[box].HPath != "/Newer" || byBox[other.Box].HPath != "/Latest" {+ t.Fatalf("rename coalescing crossed notebook boundaries: %#v", byBox)+ }+}+func TestIndexQueuePreservesOperationsAppendedDuringFlush(t *testing.T) {prepareIndexQueueTest(t)diff --git a/kernel/sql/queue.go b/kernel/sql/queue.goindex 47d03be67c..ce49f92cce 100644--- a/kernel/sql/queue.go+++ b/kernel/sql/queue.go@@ -20,7 +20,6 @@ import ("database/sql""errors""fmt"- "math""path""runtime/debug""sort"@@ -79,7 +78,7 @@ func (change *backlinkIndexChange) addRootID(rootID string) {func (change *backlinkIndexChange) addOperation(op *dbQueueOperation) {switch op.action {- case "index", "rename", "move":+ case "index", "rename", "rename_doc", "move":change.changed = trueif op.indexTree == nil {change.full = true@@ -138,7 +137,7 @@ func (change *backlinkIndexChange) data() map[string]any {// delete_ids/delete_assets 无 box 上下文,返回空串 → 走全局 db。func (op *dbQueueOperation) boxID() string {switch op.action {- case "index", "rename", "move":+ case "index", "rename", "rename_doc", "move":if op.indexTree != nil {return op.indexTree.Box}@@ -224,30 +223,6 @@ func FlushQueue() {// logging.LogInfof("flushing database queue, total operations [%d]", total)- // 如果有重命名树的操作,则统计各路径前缀的块树数量,数量较大的话阻塞整个队列,以便尽可能合并重命名树的操作 RenameTreeQueue(tree)- var renameTreeOp *dbQueueOperation- for _, op := range ops {- if "rename" == op.action {- renameTreeOp = op- break- }- }- if nil != renameTreeOp {- childCount := treenode.CountBlockTreesByPathPrefix(renameTreeOp.indexTree.Box, path.Dir(renameTreeOp.indexTree.Path))- if 512 < childCount {- scale := math.Log(float64(childCount)/512.0+1.0) / math.Log(2.0)- secs := 1.0 * scale- if secs < 1.0 {- secs = 1.0- }- if secs > 12.0 {- secs = 12.0- }- logging.LogInfof("rename tree [%s] with large child count [%d], sleep [%.2fs] to wait for more operations", renameTreeOp.indexTree.Path, childCount, secs)- time.Sleep(time.Duration(secs * float64(time.Second)))- }- }-context := map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBar}if 512 < len(ops) {disableCache()@@ -338,6 +313,26 @@ func invalidateRefsCacheForOperation(op *dbQueueOperation) {}func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err error) {+ // 排队中的内容快照保留编辑内容,但路径采用已经提交的文档元数据。+ currentOp := *op+ op = ¤tOp+ if op.action == "rename_doc" {+ doc := treenode.GetBlockTreeInBox(op.indexTree.ID, op.indexTree.Box)+ if doc == nil || doc.BoxID != op.indexTree.Box || doc.Path != op.indexTree.Path {+ // 移动或删除后的文档由对应操作维护,旧重命名快照不能写回原路径。+ return nil+ }+ }+ if op.indexTree != nil && op.action != "rename" {+ tree := *op.indexTree+ tree.HPath = treenode.CurrentTreeHPath(&tree)+ op.indexTree = &tree+ }+ if op.upsertTree != nil && op.action == "upsert" {+ tree := *op.upsertTree+ tree.HPath = treenode.CurrentTreeHPath(&tree)+ op.upsertTree = &tree+ }switch op.action {case "index":err = indexTree(tx, op.indexTree, context)@@ -360,8 +355,13 @@ func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err errortx.Exec("DELETE FROM block_embeddings WHERE root_id = ?", rootID)}}- case "rename":- err = batchUpdateHPath(tx, op.indexTree, context)+ case "rename", "rename_doc":+ if op.action == "rename_doc" {+ err = execStmtTx(tx, "UPDATE blocks SET hpath = ? WHERE id = ? AND box = ? AND type = 'd'", op.indexTree.HPath, op.indexTree.ID, op.indexTree.Box)+ } else {+ // 保留既有磁盘队列的逐文档重命名恢复行为。+ err = batchUpdateHPath(tx, op.indexTree, context)+ }if err != nil {break}@@ -533,16 +533,25 @@ func UpsertTreeQueue(tree *parse.Tree) {}func RenameTreeQueue(tree *parse.Tree) {+ renameTreeQueue(tree, "rename")+}++// RenameDocQueue 及时更新文档标题,内容块的路径副本由独立后台任务补齐。+func RenameDocQueue(tree *parse.Tree) {+ renameTreeQueue(tree, "rename_doc")+}++func renameTreeQueue(tree *parse.Tree, action string) {dbQueueLock.Lock()defer dbQueueLock.Unlock()newOp := &dbQueueOperation{indexTree: tree,inQueueTime: time.Now(),- action: "rename",+ action: action,}for i, op := range operationQueue {- if "rename" == op.action && op.indexTree.ID == tree.ID { // 相同树则覆盖+ if action == op.action && op.indexTree.Box == tree.Box && op.indexTree.ID == tree.ID { // 相同树则覆盖operationQueue[i] = newOpreturn}diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.goindex d43d2eb495..332ddab288 100644--- a/kernel/treenode/blocktree.go+++ b/kernel/treenode/blocktree.go@@ -74,6 +74,9 @@ func initDatabase(forceRebuild bool) {}}if !forceRebuild {+ if err := ensureDocPathIndex(db); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create document path index failed: %s", err)+ }if _, err := db.Exec("CREATE INDEX IF NOT EXISTS idx_blocktrees_box_id ON blocktrees(box_id)"); err != nil {logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create blocktree box index failed: %s", err)}@@ -113,6 +116,9 @@ func initDBTables() {if err != nil {logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create index [idx_blocktrees_box_id] failed: %s", err)}+ if err = ensureDocPathIndex(db); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create document path index failed: %s", err)+ }}func cleanupInvalidBlockTrees(database *sql.DB) (err error) {@@ -705,6 +711,7 @@ func RemoveBlockTree(boxID, id string) {var indexBlockTreeLock = sync.Mutex{}func IndexBlockTree(tree *parse.Tree) {+ tree.HPath = CurrentParentHPath(tree)var changedNodes []*ast.Nodeast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering || !n.IsBlock() || "" == n.ID {@@ -742,6 +749,7 @@ func IndexBlockTree(tree *parse.Tree) {}func UpsertBlockTree(tree *parse.Tree) {+ tree.HPath = CurrentParentHPath(tree)oldBts := map[string]*BlockTree{}bts := GetBlockTreesByRootIDInBox(tree.ID, tree.Box)for _, bt := range bts {@@ -1030,6 +1038,7 @@ func initEncryptedBlockTreeTables(boxDB *sql.DB) (err error) {"CREATE INDEX IF NOT EXISTS idx_blocktrees_id ON blocktrees(id)","CREATE INDEX IF NOT EXISTS idx_blocktrees_root_id ON blocktrees(root_id)","CREATE INDEX IF NOT EXISTS idx_blocktrees_box_id ON blocktrees(box_id)",+ "CREATE INDEX IF NOT EXISTS idx_blocktrees_doc_path ON blocktrees(box_id, path) WHERE type = 'd'",}for _, s := range stmts {if _, err = boxDB.Exec(s); err != nil {diff --git a/kernel/treenode/hpath.go b/kernel/treenode/hpath.gonew file mode 100644index 0000000000..01b906a9ee--- /dev/null+++ b/kernel/treenode/hpath.go@@ -0,0 +1,131 @@+package treenode++import (+ "database/sql"+ "errors"+ "path"+ "strings"++ "github.com/88250/lute/parse"+)++var ErrHPathRefreshBusy = errors.New("blocktree writer is busy")++func ensureDocPathIndex(database *sql.DB) error {+ _, err := database.Exec("CREATE INDEX IF NOT EXISTS idx_blocktrees_doc_path ON blocktrees(box_id, path) WHERE type = 'd'")+ return err+}++// DocHPaths 返回文档及其后代的文档行,不加载正文或枚举内容块。+func DocHPaths(boxID, docPath string) (ret []*BlockTree, err error) {+ prefix := strings.TrimSuffix(docPath, ".sy") + "/"+ rows, err := queryForBox(boxID, "SELECT id, path, hpath FROM blocktrees WHERE box_id = ? AND type = 'd' AND (path = ? OR (path >= ? AND path < ?)) ORDER BY path", boxID, docPath, prefix, prefix+"\uffff")+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ for rows.Next() {+ bt := &BlockTree{BoxID: boxID, Type: "d"}+ if err = rows.Scan(&bt.ID, &bt.Path, &bt.HPath); err != nil {+ return nil, err+ }+ bt.RootID = bt.ID+ ret = append(ret, bt)+ }+ return ret, rows.Err()+}++// RefreshDocHPaths 同步维护文档行,保证按可读路径定位、创建文档时不会命中过期的父路径。+// 内容块的路径副本由后台补齐,重命名不删除或重建块树。+func RefreshDocHPaths(tree *parse.Tree) (err error) {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ current := GetBlockTreeInBox(tree.ID, tree.Box)+ if current == nil || current.BoxID != tree.Box || current.Path != tree.Path {+ return errors.New("document moved or was removed during hpath refresh")+ }+ docs, err := DocHPaths(tree.Box, tree.Path)+ if err != nil {+ return err+ }+ tx, err := beginTxForBox(tree.Box)+ if err != nil {+ return err+ }+ defer tx.Rollback()+ depth := strings.Count(tree.Path, "/")+ for _, doc := range docs {+ hpath := tree.HPath+ if doc.Path != tree.Path {+ parts := strings.Split(doc.HPath, "/")+ if len(parts) <= depth+1 {+ return errors.New("invalid descendant document hpath")+ }+ hpath += "/" + strings.Join(parts[depth+1:], "/")+ }+ if _, err = tx.Exec("UPDATE blocktrees SET hpath = ? WHERE id = ? AND box_id = ? AND path = ? AND type = 'd' AND hpath != ?", hpath, doc.ID, tree.Box, doc.Path, hpath); err != nil {+ return err+ }+ }+ if _, err = tx.Exec("UPDATE blocktrees SET updated = ? WHERE id = ? AND box_id = ? AND type = 'd'", tree.Root.IALAttr("updated"), tree.ID, tree.Box); err != nil {+ return err+ }+ return tx.Commit()+}++// CurrentTreeHPath 使排队期间加载的树使用最新文档路径,避免旧索引操作写回重命名前的路径。+func CurrentTreeHPath(tree *parse.Tree) string {+ if doc := GetBlockTreeInBox(tree.ID, tree.Box); doc != nil && doc.BoxID == tree.Box && doc.Path == tree.Path {+ return doc.HPath+ }+ return tree.HPath+}++// CurrentParentHPath 保留本次编辑的标题,同时采用当前父文档路径。+func CurrentParentHPath(tree *parse.Tree) string {+ parent := path.Dir(tree.Path)+ if parent == "/" {+ return tree.HPath+ }+ if doc := GetBlockTreeInBox(path.Base(parent), tree.Box); doc != nil && doc.BoxID == tree.Box && doc.Path == parent+".sy" {+ return doc.HPath + "/" + tree.Root.IALAttr("title")+ }+ return tree.HPath+}++// RefreshBlockHPathsBatch 在块树写锁内校验文档快照,并提交一个有界批次。+// apply 在同一临界区更新内容库;两库任一提交失败时,由未清除的恢复任务重试。+func RefreshBlockHPathsBatch(doc *BlockTree, after int64, limit int, apply func() error) (next int64, done bool, err error) {+ if !indexBlockTreeLock.TryLock() {+ return after, false, ErrHPathRefreshBusy+ }+ defer indexBlockTreeLock.Unlock()+ current := GetBlockTreeInBox(doc.ID, doc.BoxID)+ if current == nil || current.BoxID != doc.BoxID || current.Path != doc.Path || current.HPath != doc.HPath {+ return after, false, errors.New("document changed during hpath refresh")+ }+ tx, err := beginTxForBox(doc.BoxID)+ if err != nil {+ return after, false, err+ }+ defer tx.Rollback()+ var last sql.NullInt64+ if err = tx.QueryRow("SELECT MAX(rowid) FROM (SELECT rowid FROM blocktrees WHERE root_id = ? AND box_id = ? AND path = ? AND rowid > ? ORDER BY rowid LIMIT ?)", doc.ID, doc.BoxID, doc.Path, after, limit).Scan(&last); err != nil {+ return after, false, err+ }+ if last.Valid {+ if _, err = tx.Exec("UPDATE blocktrees SET hpath = ? WHERE root_id = ? AND box_id = ? AND path = ? AND rowid > ? AND rowid <= ? AND hpath != ?", doc.HPath, doc.ID, doc.BoxID, doc.Path, after, last.Int64, doc.HPath); err != nil {+ return after, false, err+ }+ }+ if err = apply(); err != nil {+ return after, false, err+ }+ if err = tx.Commit(); err != nil {+ return after, false, err+ }+ if !last.Valid {+ return after, true, nil+ }+ return last.Int64, false, nil+}diff --git a/kernel/treenode/hpath_test.go b/kernel/treenode/hpath_test.gonew file mode 100644index 0000000000..2e42e29c9d--- /dev/null+++ b/kernel/treenode/hpath_test.go@@ -0,0 +1,27 @@+package treenode++import (+ "errors"+ "testing"+ "time"+)++func TestHPathRefreshYieldsToBlockTreeWriter(t *testing.T) {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ result := make(chan error, 1)+ go func() {+ _, _, err := RefreshBlockHPathsBatch(&BlockTree{}, 0, 32, func() error {+ return errors.New("content write attempted while blocktree writer was busy")+ })+ result <- err+ }()+ select {+ case err := <-result:+ if !errors.Is(err, ErrHPathRefreshBusy) {+ t.Fatalf("background did not yield to writer: %v", err)+ }+ case <-time.After(time.Second):+ t.Fatal("background waited for the blocktree writer")+ }+}