Skip to content

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

:zap: Improve Add to Database list opening performance https://github.com/siyuan-note/siyuan/issues/18474

Daniele2effdfe96e9
diff --git a/kernel/av/av.go b/kernel/av/av.go
index da930a3f38..a8362c0d73 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -560,6 +560,29 @@ type AttributeViewSearchInfo struct {
Views []*AttributeViewSearchView `json:"views"`
}
+func newAttributeViewSearchInfo(attrView *AttributeView) *AttributeViewSearchInfo {
+ if attrView == nil {
+ return nil
+ }
+ ret := &AttributeViewSearchInfo{Spec: attrView.Spec, Name: attrView.Name}
+ for _, view := range attrView.Views {
+ if view == nil {
+ continue
+ }
+ ret.Views = append(ret.Views, &AttributeViewSearchView{
+ ID: view.ID,
+ Name: view.Name,
+ LayoutType: view.LayoutType,
+ })
+ }
+ return ret
+}
+
+func cacheAttributeViewData(attrView *AttributeView, boxID string, data []byte) {
+ version := cache.SetAVDataWithVersionInBox(attrView.ID, boxID, data)
+ cache.SetAVSearchDataInBox(attrView.ID, boxID, version, newAttributeViewSearchInfo(attrView))
+}
+
func parseAttributeViewSearchInfo(data []byte) (ret *AttributeViewSearchInfo, err error) {
ret = &AttributeViewSearchInfo{}
if err = json.Unmarshal(data, ret); err != nil {
@@ -590,6 +613,7 @@ func GetAttributeViewSearchInfoInBox(avID, boxID string) (ret *AttributeViewSear
data = cached
dataVersion = version
} else {
+ dataVersion = cache.EnsureAVDataVersionInBox(avID, avBoxID)
if data, err = filelock.ReadFile(avJSONPath); err != nil {
logging.LogErrorf("read attribute view [%s] failed: %s", avJSONPath, err)
return
@@ -602,7 +626,6 @@ func GetAttributeViewSearchInfoInBox(avID, boxID string) (ret *AttributeViewSear
} else if util.IsCiphertext(data) {
return
}
- dataVersion = cache.SetAVDataWithVersionInBox(avID, avBoxID, data)
}
if ret, err = parseAttributeViewSearchInfo(data); err != nil {
@@ -735,8 +758,10 @@ func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeView
avID = strings.TrimSuffix(avID, filepath.Ext(avID))
var data []byte
- if cached, ok := cache.GetAVDataInBox(avID, boxID); ok {
+ var dataVersion uint64
+ if cached, version, ok := cache.GetAVDataWithVersionInBox(avID, boxID); ok {
data = cached
+ dataVersion = version
} else {
var readErr error
data, readErr = filelock.ReadFile(avJSONPath)
@@ -756,7 +781,7 @@ func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeView
// 这会在加密笔记本的 AV 因路径迁移(同步、导入、历史布局)落到全局位置时发生。
return nil, nil
}
- cache.SetAVDataInBox(avID, boxID, data)
+ dataVersion = cache.SetAVDataWithVersionInBox(avID, boxID, data)
}
ret = &AttributeView{RenderedViewables: map[string]Viewable{}}
@@ -819,6 +844,9 @@ func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeView
if nil == err {
err = CheckSpec(ret)
}
+ if nil == err {
+ cache.SetAVSearchDataInBox(avID, boxID, dataVersion, newAttributeViewSearchInfo(ret))
+ }
return
}
@@ -897,8 +925,9 @@ func SaveAttributeView(av *AttributeView) (err error) {
// 加密笔记本的首次创建由 handler 层通过 SetAVBoxID 预设路径
avJSONPath = GetAttributeViewDataPath(av.ID)
}
- if cachedData, ok := cache.GetAVDataInBox(av.ID, avBoxID); ok {
+ if cachedData, version, ok := cache.GetAVDataWithVersionInBox(av.ID, avBoxID); ok {
if len(cachedData) == len(data) && bytes.Equal(cachedData, data) {
+ cache.SetAVSearchDataInBox(av.ID, avBoxID, version, newAttributeViewSearchInfo(av))
return
}
} else {
@@ -908,7 +937,7 @@ func SaveAttributeView(av *AttributeView) (err error) {
diskData, _ = decryptAVData(avBoxID, av.ID, diskData)
}
if len(diskData) == len(data) && bytes.Equal(diskData, data) {
- cache.SetAVDataInBox(av.ID, avBoxID, data)
+ cacheAttributeViewData(av, avBoxID, data)
return
}
}
@@ -935,7 +964,7 @@ func SaveAttributeView(av *AttributeView) (err error) {
}
}
- cache.SetAVDataInBox(av.ID, avBoxID, data)
+ cacheAttributeViewData(av, avBoxID, data)
if util.ExceedLargeFileWarningSize(len(data)) {
msg := fmt.Sprintf(util.Langs[util.Lang][268], av.Name+" "+filepath.Base(avJSONPath), util.LargeFileWarningSize)
diff --git a/kernel/av/av_search_test.go b/kernel/av/av_search_test.go
index 875ea03fad..a28e62bdd0 100644
--- a/kernel/av/av_search_test.go
+++ b/kernel/av/av_search_test.go
@@ -16,7 +16,11 @@
package av
-import "testing"
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/cache"
+)
func TestParseAttributeViewSearchInfo(t *testing.T) {
data := []byte(`{
@@ -48,3 +52,38 @@ func TestParseAttributeViewSearchInfo(t *testing.T) {
t.Fatalf("expected newer spec error, got %v", err)
}
}
+
+func TestNewAttributeViewSearchInfo(t *testing.T) {
+ view := &View{ID: "view-1", Name: "状态:进行", LayoutType: LayoutTypeTable}
+ attrView := &AttributeView{
+ ID: "20260801120000-search",
+ Spec: CurrentSpec,
+ Name: "Schedule",
+ Views: []*View{view, nil},
+ }
+
+ info := newAttributeViewSearchInfo(attrView)
+ if info.Spec != CurrentSpec || info.Name != "Schedule" || len(info.Views) != 1 {
+ t.Fatalf("unexpected search info: %+v", info)
+ }
+ if info.Views[0].ID != "view-1" || info.Views[0].Name != "状态:进行" ||
+ info.Views[0].LayoutType != LayoutTypeTable {
+ t.Fatalf("unexpected search view: %+v", info.Views[0])
+ }
+
+ view.Name = "Changed"
+ if info.Views[0].Name != "状态:进行" {
+ t.Fatalf("search info should not retain mutable view data: %+v", info.Views[0])
+ }
+
+ const boxID = "20260801120000-box"
+ cacheAttributeViewData(attrView, boxID, []byte(`{"name":"Schedule"}`))
+ cached, ok := cache.GetAVSearchDataInBox[*AttributeViewSearchInfo](attrView.ID, boxID)
+ if !ok || cached.Name != "Schedule" || len(cached.Views) != 1 || cached.Views[0].Name != "Changed" {
+ t.Fatalf("unexpected cached search info: %+v, %v", cached, ok)
+ }
+ view.Name = "Changed again"
+ if cached.Views[0].Name != "Changed" {
+ t.Fatalf("cached search info should remain immutable: %+v", cached.Views[0])
+ }
+}
diff --git a/kernel/cache/av.go b/kernel/cache/av.go
index 4fe76ba3b0..11ac1eacf8 100644
--- a/kernel/cache/av.go
+++ b/kernel/cache/av.go
@@ -68,6 +68,19 @@ func GetAVDataWithVersionInBox(avID, boxID string) (raw []byte, version uint64,
return entry.raw, entry.version, true
}
+func EnsureAVDataVersionInBox(avID, boxID string) (version uint64) {
+ avSearchDataCacheLock.Lock()
+ defer avSearchDataCacheLock.Unlock()
+ key := avCacheKey(avID, boxID)
+ version = avDataVersions[key]
+ if version == 0 {
+ avDataVersion++
+ version = avDataVersion
+ avDataVersions[key] = version
+ }
+ return
+}
+
func SetAVData(avID string, raw []byte) {
SetAVDataInBox(avID, "", raw)
}
diff --git a/kernel/cache/av_test.go b/kernel/cache/av_test.go
index 0c9991e247..d61e82fa73 100644
--- a/kernel/cache/av_test.go
+++ b/kernel/cache/av_test.go
@@ -49,3 +49,27 @@ func TestAVSearchDataInvalidation(t *testing.T) {
t.Fatal("removing AV data should invalidate search data")
}
}
+
+func TestAVSearchDataWithoutRawData(t *testing.T) {
+ const avID = "20260801120000-search"
+ const boxID = "20260801120000-box"
+
+ version := EnsureAVDataVersionInBox(avID, boxID)
+ if version == 0 || EnsureAVDataVersionInBox(avID, boxID) != version {
+ t.Fatalf("unexpected AV data version: %d", version)
+ }
+ if !SetAVSearchDataInBox(avID, boxID, version, "cached") {
+ t.Fatal("failed to cache search data without raw data")
+ }
+ if _, ok := GetAVDataInBox(avID, boxID); ok {
+ t.Fatal("caching search data should not cache raw data")
+ }
+
+ newVersion := SetAVDataWithVersionInBox(avID, boxID, []byte(`{"name":"new"}`))
+ if newVersion == version {
+ t.Fatal("setting raw data should advance the data version")
+ }
+ if _, ok := GetAVSearchDataInBox[string](avID, boxID); ok {
+ t.Fatal("setting raw data should invalidate standalone search data")
+ }
+}
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index b6413975d3..27c03dd5b2 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -29,6 +29,7 @@ import (
"sort"
"strconv"
"strings"
+ "sync"
"time"
"unicode/utf8"
@@ -2742,6 +2743,27 @@ type SearchAttributeViewOptions struct {
IncludeViewMatches bool
}
+var attributeViewSearchCacheWarmups sync.Map
+
+func warmAttributeViewSearchCache(boxID string, avIDs []string) {
+ if len(avIDs) == 0 {
+ return
+ }
+ if _, loaded := attributeViewSearchCacheWarmups.LoadOrStore(boxID, struct{}{}); loaded {
+ return
+ }
+ ids := slices.Clone(avIDs)
+ go func() {
+ defer attributeViewSearchCacheWarmups.Delete(boxID)
+ for _, avID := range ids {
+ if isSyncingStorages() {
+ return
+ }
+ _, _ = av.GetAttributeViewSearchInfoInBox(avID, boxID)
+ }
+ }()
+}
+
func matchAttributeViewSearchName(name string, keywords []string) (score float64, hit bool) {
if name == "" || len(keywords) == 0 {
return
@@ -2778,7 +2800,7 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
var eligibleFileSize int64
defer func() {
totalElapsed := time.Since(searchStart)
- if totalElapsed < 10*time.Millisecond {
+ if totalElapsed < 500*time.Millisecond {
return
}
logging.LogInfof("search attribute views [total=%dms, waitSync=%dms, readDir=%dms, getBlockRels=%dms, scan=%dms, readNames=%dms, readFileInfo=%dms, sort=%dms, resolve=%dms, loadTrees=%dms, findNodes=%dms, readSearchInfo=%dms, resolveHPaths=%dms, entries=%d, validFiles=%d, eligibleFiles=%d, matched=%d, results=%d, readNameCount=%d, loadTreeCount=%d, findNodeCount=%d, readSearchInfoCount=%d, resolveHPathCount=%d, eligibleSizeBytes=%d, keywordEmpty=%t, includeViewMatches=%t]",
@@ -2800,6 +2822,7 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
keywords := strings.Fields(keyword)
var avSearchTmpResults []*AvSearchTempResult
+ var warmupAvIDs []string
boxID := ""
if options.CurrentBlockID != "" {
if bt := treenode.GetBlockTree(options.CurrentBlockID); nil != bt && IsEncryptedBox(bt.BoxID) {
@@ -2840,25 +2863,39 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
}
validFileCount++
- if gulu.Str.Contains(id, options.ExcludeAvIDs) {
+ if nil == avBlockRels[id] {
continue
}
+ warmupAvIDs = append(warmupAvIDs, id)
- if nil == avBlockRels[id] {
+ if gulu.Str.Contains(id, options.ExcludeAvIDs) {
continue
}
eligibleFileCount++
+ readFileInfoStart := time.Now()
+ info, _ := entry.Info()
+ readFileInfoElapsed += time.Since(readFileInfoStart)
+ if info != nil {
+ eligibleFileSize += info.Size()
+ }
+ a := &AvSearchTempResult{AvID: id}
+ if nil != info && !info.ModTime().IsZero() {
+ a.AvUpdated = info.ModTime().UnixMilli()
+ }
+ if keyword == "" {
+ avSearchTmpResults = append(avSearchTmpResults, a)
+ continue
+ }
+
var searchInfo *av.AttributeViewSearchInfo
+ readSearchInfoStart := time.Now()
+ searchInfo, _ = av.GetAttributeViewSearchInfoInBox(id, boxID)
+ readSearchInfoElapsed += time.Since(readSearchInfoStart)
+ readSearchInfoCount++
var name string
- if options.IncludeViewMatches && keyword != "" {
- readSearchInfoStart := time.Now()
- searchInfo, _ = av.GetAttributeViewSearchInfoInBox(id, boxID)
- readSearchInfoElapsed += time.Since(readSearchInfoStart)
- readSearchInfoCount++
- if searchInfo != nil {
- name = searchInfo.Name
- }
+ if searchInfo != nil {
+ name = searchInfo.Name
}
if searchInfo == nil {
readNameStart := time.Now()
@@ -2866,46 +2903,25 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
readNameElapsed += time.Since(readNameStart)
readNameCount++
}
-
- readFileInfoStart := time.Now()
- info, _ := entry.Info()
- readFileInfoElapsed += time.Since(readFileInfoStart)
- if info != nil {
- eligibleFileSize += info.Size()
- }
- if "" != keyword {
- score, hit := matchAttributeViewSearchName(name, keywords)
- matchedViewIDs := map[string]bool{}
- if options.IncludeViewMatches && searchInfo != nil {
- for _, view := range searchInfo.Views {
- viewScore, viewHit := matchAttributeViewSearchName(view.Name, keywords)
- if viewHit {
- matchedViewIDs[view.ID] = true
- if viewScore > score {
- score = viewScore
- }
+ score, hit := matchAttributeViewSearchName(name, keywords)
+ matchedViewIDs := map[string]bool{}
+ if options.IncludeViewMatches && searchInfo != nil {
+ for _, view := range searchInfo.Views {
+ viewScore, viewHit := matchAttributeViewSearchName(view.Name, keywords)
+ if viewHit {
+ matchedViewIDs[view.ID] = true
+ if viewScore > score {
+ score = viewScore
}
}
}
+ }
- if hit || len(matchedViewIDs) > 0 {
- a := &AvSearchTempResult{
- AvID: id,
- AvName: name,
- Score: score,
- SearchInfo: searchInfo,
- MatchedViewIDs: matchedViewIDs,
- }
- if nil != info && !info.ModTime().IsZero() {
- a.AvUpdated = info.ModTime().UnixMilli()
- }
- avSearchTmpResults = append(avSearchTmpResults, a)
- }
- } else {
- a := &AvSearchTempResult{AvID: id, AvName: name}
- if nil != info && !info.ModTime().IsZero() {
- a.AvUpdated = info.ModTime().UnixMilli()
- }
+ if hit || len(matchedViewIDs) > 0 {
+ a.AvName = name
+ a.Score = score
+ a.SearchInfo = searchInfo
+ a.MatchedViewIDs = matchedViewIDs
avSearchTmpResults = append(avSearchTmpResults, a)
}
}
@@ -2932,6 +2948,7 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
for _, tmpResult := range avSearchTmpResults {
bIDs := avBlockRels[tmpResult.AvID]
var node *ast.Node
+ var treeHPath string
for _, bID := range bIDs {
loadTreeStart := time.Now()
tree, _ := loadTreeByBlockIDInBox(bID, boxID)
@@ -2950,6 +2967,7 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
continue
}
+ treeHPath = tree.HPath
break
}
@@ -2967,13 +2985,12 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
if searchInfo == nil {
continue
}
+ if tmpResult.AvName == "" {
+ tmpResult.AvName = searchInfo.Name
+ }
- var hPath string
resolveHPathStart := time.Now()
- baseBlock := treenode.GetBlockTreeRootByPath(node.Box, node.Path)
- if nil != baseBlock {
- hPath = baseBlock.HPath
- }
+ hPath := treeHPath
box := Conf.Box(node.Box)
if nil != box {
hPath = box.Name + hPath
@@ -3004,6 +3021,9 @@ func SearchAttributeViewWithOptions(options SearchAttributeViewOptions) (ret []*
}
}
resolveElapsed = time.Since(resolveStart)
+ if keyword == "" {
+ warmAttributeViewSearchCache(boxID, warmupAvIDs)
+ }
return
}