Skip to content

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

:perf: Size cache counters and account lookup data in bytes https://github.com/siyuan-note/siyuan/issues/20366

Danieleed42b1b6fff
diff --git a/kernel/cache/av.go b/kernel/cache/av.go
index af38eb7637..b621d31b76 100644
--- a/kernel/cache/av.go
+++ b/kernel/cache/av.go
@@ -25,8 +25,8 @@ import (
)
var avCache, _ = ristretto.NewCache(&ristretto.Config{
- NumCounters: 100000,
- MaxCost: 1024 * 1024 * 200,
+ NumCounters: AdmissionCounters,
+ MaxCost: DefaultMaxCostBytes,
BufferItems: 64,
})
diff --git a/kernel/cache/budget.go b/kernel/cache/budget.go
new file mode 100644
index 0000000000..ee0927b323
--- /dev/null
+++ b/kernel/cache/budget.go
@@ -0,0 +1,10 @@
+package cache
+
+const (
+ // AdmissionCounters 为约一千个常用键保留十倍频率计数器,不限制缓存条数。
+ AdmissionCounters = 10000
+ // DefaultMaxCostBytes 是文档、属性和属性视图缓存各自的字节预算。
+ DefaultMaxCostBytes = 200 * 1024 * 1024
+ // LookupMaxCostBytes 是块查询和虚拟引用缓存各自的字节预算。
+ LookupMaxCostBytes = 10 * 1024 * 1024
+)
diff --git a/kernel/cache/ial.go b/kernel/cache/ial.go
index 6a4233c511..de41b2f0a5 100644
--- a/kernel/cache/ial.go
+++ b/kernel/cache/ial.go
@@ -24,8 +24,8 @@ import (
)
var docIALCache, _ = ristretto.NewCache(&ristretto.Config{
- NumCounters: 100000,
- MaxCost: 1024 * 1024 * 200,
+ NumCounters: AdmissionCounters,
+ MaxCost: DefaultMaxCostBytes,
BufferItems: 64,
})
var docIALCacheKeys = map[string]map[string]struct{}{}
@@ -108,8 +108,8 @@ func ClearDocsIAL() {
}
var blockIALCache, _ = ristretto.NewCache(&ristretto.Config{
- NumCounters: 100000,
- MaxCost: 1024 * 1024 * 200,
+ NumCounters: AdmissionCounters,
+ MaxCost: DefaultMaxCostBytes,
BufferItems: 64,
})
var blockIALCacheKeys = map[string]map[string]struct{}{}
diff --git a/kernel/cache/tree.go b/kernel/cache/tree.go
index 23a6ea03b6..256ac42d4f 100644
--- a/kernel/cache/tree.go
+++ b/kernel/cache/tree.go
@@ -31,7 +31,7 @@ type treeCacheEntry struct {
generation uint64
}
-const treeCacheMaxCost = 1024 * 1024 * 200
+const treeCacheMaxCost = DefaultMaxCostBytes
var (
treeCacheEncoder, _ = zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedFastest),
@@ -39,7 +39,7 @@ var (
treeCacheDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderConcurrency(1),
zstd.WithDecoderMaxMemory(treeCacheMaxCost), zstd.WithDecodeAllCapLimit(true))
treeCache, _ = ristretto.NewCache(&ristretto.Config{
- NumCounters: 100000,
+ NumCounters: AdmissionCounters,
MaxCost: treeCacheMaxCost,
BufferItems: 64,
})
diff --git a/kernel/model/virtualref_cache_budget_test.go b/kernel/model/virtualref_cache_budget_test.go
new file mode 100644
index 0000000000..63f0eba359
--- /dev/null
+++ b/kernel/model/virtualref_cache_budget_test.go
@@ -0,0 +1,32 @@
+package model
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestVirtualRefCacheByteBudgetAndTTL(t *testing.T) {
+ previous := virtualBlockRefCache.MaxCost()
+ virtualBlockRefCache.Clear()
+ virtualBlockRefCache.UpdateMaxCost(4096)
+ t.Cleanup(func() {
+ virtualBlockRefCache.Clear()
+ virtualBlockRefCache.UpdateMaxCost(previous)
+ })
+ putVirtualRefCache("box\x00doc", []string{"keyword"}, time.Minute)
+ virtualBlockRefCache.Wait()
+ if ttl, ok := virtualBlockRefCache.GetTTL("box\x00doc"); !ok || ttl <= 0 || ttl > time.Minute {
+ t.Fatalf("cached document lost its TTL: %v, %v", ttl, ok)
+ }
+ putVirtualRefCache("box\x00doc", []string{strings.Repeat("x", 4096)}, time.Minute)
+ virtualBlockRefCache.Wait()
+ if _, ok := virtualBlockRefCache.Get("box\x00doc"); ok {
+ t.Fatal("oversized keywords retained the old cached value")
+ }
+ putVirtualRefCache("box\x00virtual_ref", []string{"keyword"}, 0)
+ virtualBlockRefCache.Wait()
+ if ttl, ok := virtualBlockRefCache.GetTTL("box\x00virtual_ref"); !ok || ttl != 0 {
+ t.Fatalf("keyword list unexpectedly expires: %v, %v", ttl, ok)
+ }
+}
diff --git a/kernel/model/virutalref.go b/kernel/model/virutalref.go
index fa17545ae9..ab070b0963 100644
--- a/kernel/model/virutalref.go
+++ b/kernel/model/virutalref.go
@@ -22,6 +22,7 @@ import (
"sort"
"strings"
"time"
+ "unsafe"
"github.com/88250/gulu"
"github.com/88250/lute"
@@ -30,6 +31,7 @@ import (
"github.com/88250/lute/parse"
"github.com/ClarkThan/ahocorasick"
"github.com/dgraph-io/ristretto"
+ "github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/search"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
@@ -40,11 +42,24 @@ import (
// virtualBlockRefCache 用于保存块关联的虚拟引用关键字。
// 改进打开虚拟引用后加载文档的性能 https://github.com/siyuan-note/siyuan/issues/7378
var virtualBlockRefCache, _ = ristretto.NewCache(&ristretto.Config{
- NumCounters: 100000,
- MaxCost: 10240,
+ NumCounters: cache.AdmissionCounters,
+ MaxCost: cache.LookupMaxCostBytes,
BufferItems: 64,
})
+// putVirtualRefCache 按关键字切片及字符串的驻留字节数计费,保留调用方指定的有效期。
+func putVirtualRefCache(key string, keywords []string, ttl time.Duration) {
+ cost := int64(unsafe.Sizeof(keywords)) + int64(cap(keywords))*int64(unsafe.Sizeof("")) + int64(len(key))
+ for _, keyword := range keywords {
+ cost += int64(len(keyword))
+ }
+ virtualBlockRefCache.Del(key)
+ if cost >= virtualBlockRefCache.MaxCost() {
+ return
+ }
+ virtualBlockRefCache.SetWithTTL(key, keywords, cost, ttl)
+}
+
func getBlockVirtualRefKeywords(root *ast.Node, boxID string) (ret []string) {
key := boxID + "\x00" + root.ID
val, ok := virtualBlockRefCache.Get(key)
@@ -100,7 +115,7 @@ func putBlockVirtualRefKeywords(blockContent string, root *ast.Node, boxID strin
ret = gulu.Str.RemoveDuplicatedElem(ret)
key := boxID + "\x00" + root.ID
- virtualBlockRefCache.SetWithTTL(key, ret, 1, 10*time.Minute)
+ putVirtualRefCache(key, ret, 10*time.Minute)
return
}
@@ -123,10 +138,10 @@ func ResetVirtualBlockRefCache() {
searchIgnoreLines := getSearchIgnoreLines()
refSearchIgnoreLines := getRefSearchIgnoreLines()
keywords := sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias, Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines)
- virtualBlockRefCache.Set("virtual_ref", keywords, 1)
+ putVirtualRefCache("virtual_ref", keywords, 0)
for _, boxID := range treenode.GetOpenedEncryptedBoxIDs() {
boxKeywords := sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias, Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxID)
- virtualBlockRefCache.Set(boxID+"\x00virtual_ref", boxKeywords, 1)
+ putVirtualRefCache(boxID+"\x00virtual_ref", boxKeywords, 0)
}
}
@@ -292,7 +307,7 @@ func getVirtualRefKeywords(root *ast.Node, boxIDs ...string) (ret []string) {
refSearchIgnoreLines := getRefSearchIgnoreLines()
ret = sql.QueryVirtualRefKeywords(Conf.Search.VirtualRefName, Conf.Search.VirtualRefAlias,
Conf.Search.VirtualRefAnchor, Conf.Search.VirtualRefDoc, searchIgnoreLines, refSearchIgnoreLines, boxIDs...)
- virtualBlockRefCache.Set(key, ret, 1)
+ putVirtualRefCache(key, ret, 0)
}
includes := parseKeywords(Conf.Editor.VirtualBlockRefInclude)
diff --git a/kernel/sql/cache.go b/kernel/sql/cache.go
index 68d97cd3f7..983d8e1dbd 100644
--- a/kernel/sql/cache.go
+++ b/kernel/sql/cache.go
@@ -20,6 +20,7 @@ import (
"strings"
"sync"
"time"
+ "unsafe"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
@@ -27,6 +28,7 @@ import (
"github.com/jinzhu/copier"
gcache "github.com/patrickmn/go-cache"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/search"
)
@@ -41,17 +43,17 @@ func disableCache() {
}
var blockCache, _ = ristretto.NewCache(&ristretto.Config{
- NumCounters: 100000,
- MaxCost: 10240,
+ NumCounters: cache.AdmissionCounters,
+ MaxCost: cache.LookupMaxCostBytes,
BufferItems: 64,
OnExit: func(value any) {
if entry, ok := value.(*blockCacheEntry); ok {
- removeBlockCacheKey(entry.block.ID, entry.key)
+ removeBlockCacheKey(entry.block.ID, entry.key, entry)
}
},
})
-var blockCacheKeys = map[string]map[string]struct{}{}
+var blockCacheKeys = map[string]map[string]*blockCacheEntry{}
var blockCacheKeysMu sync.Mutex
type blockCacheEntry struct {
@@ -59,6 +61,17 @@ type blockCacheEntry struct {
block *Block
}
+// blockCacheCost 估算块结构、字符串和失效索引的驻留字节数,内部条目成本由缓存另行计入。
+func blockCacheCost(key string, block *Block) int64 {
+ cost := int64(unsafe.Sizeof(Block{})+unsafe.Sizeof(blockCacheEntry{})) + 256 + int64(len(key))
+ for _, value := range []string{block.ID, block.ParentID, block.RootID, block.Hash, block.Box, block.Path,
+ block.HPath, block.Name, block.Alias, block.Memo, block.Tag, block.Content, block.FContent,
+ block.Markdown, block.Type, block.SubType, block.IAL, block.Created, block.Updated} {
+ cost += int64(len(value))
+ }
+ return cost
+}
+
func encryptedBoxCacheUnavailable(boxID string) bool {
return IsEncryptedBoxFn != nil && IsEncryptedBoxFn(boxID) &&
(IsBoxUnlockedFn == nil || !IsBoxUnlockedFn(boxID))
@@ -75,7 +88,7 @@ func blockCacheKey(id, boxID string) string {
func ClearCache() {
blockCache.Clear()
blockCacheKeysMu.Lock()
- blockCacheKeys = map[string]map[string]struct{}{}
+ blockCacheKeys = map[string]map[string]*blockCacheEntry{}
blockCacheKeysMu.Unlock()
clearRefCache()
}
@@ -93,9 +106,17 @@ func putBlockCache(block *Block) {
cloned.Content = strings.ReplaceAll(cloned.Content, search.SearchMarkLeft, "")
cloned.Content = strings.ReplaceAll(cloned.Content, search.SearchMarkRight, "")
key := blockCacheKey(cloned.ID, cloned.Box)
- addBlockCacheKey(cloned.ID, key)
- if !blockCache.Set(key, &blockCacheEntry{key: key, block: cloned}, 1) {
- removeBlockCacheKey(cloned.ID, key)
+ cost := blockCacheCost(key, cloned)
+ if cost >= blockCache.MaxCost() {
+ removeBlockCache(cloned.ID)
+ return
+ }
+ // 删除后重新准入,让变大的条目也接受字节预算检查。
+ blockCache.Del(key)
+ entry := &blockCacheEntry{key: key, block: cloned}
+ addBlockCacheKey(cloned.ID, key, entry)
+ if !blockCache.Set(key, entry, cost) {
+ removeBlockCacheKey(cloned.ID, key, entry)
}
}
@@ -128,21 +149,25 @@ func removeBlockCache(id string) {
removeRefCacheByDefID(id)
}
-func addBlockCacheKey(id, key string) {
+func addBlockCacheKey(id, key string, entry *blockCacheEntry) {
blockCacheKeysMu.Lock()
defer blockCacheKeysMu.Unlock()
keys := blockCacheKeys[id]
if keys == nil {
- keys = map[string]struct{}{}
+ keys = map[string]*blockCacheEntry{}
blockCacheKeys[id] = keys
}
- keys[key] = struct{}{}
+ keys[key] = entry
}
-func removeBlockCacheKey(id, key string) {
+func removeBlockCacheKey(id, key string, entry *blockCacheEntry) {
blockCacheKeysMu.Lock()
defer blockCacheKeysMu.Unlock()
if keys := blockCacheKeys[id]; keys != nil {
+ // 异步拒绝或淘汰只能移除对应版本的失效索引。
+ if keys[key] != entry {
+ return
+ }
delete(keys, key)
if len(keys) == 0 {
delete(blockCacheKeys, id)
diff --git a/kernel/sql/cache_budget_test.go b/kernel/sql/cache_budget_test.go
new file mode 100644
index 0000000000..6f738a0e71
--- /dev/null
+++ b/kernel/sql/cache_budget_test.go
@@ -0,0 +1,52 @@
+package sql
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestBlockCacheByteBudgetRejectsLargeReplacement(t *testing.T) {
+ previousDisabled, previousCost := cacheDisabled, blockCache.MaxCost()
+ cacheDisabled = false
+ blockCache.UpdateMaxCost(4096)
+ ClearCache()
+ t.Cleanup(func() {
+ ClearCache()
+ cacheDisabled = previousDisabled
+ blockCache.UpdateMaxCost(previousCost)
+ })
+ block := &Block{ID: "budget-block", Content: "small"}
+ putBlockCache(block)
+ blockCache.Wait()
+ if getBlockCache(block.ID) == nil {
+ t.Fatal("small block was not admitted")
+ }
+ block.Content = strings.Repeat("x", 4096)
+ putBlockCache(block)
+ blockCache.Wait()
+ if getBlockCache(block.ID) != nil {
+ t.Fatal("oversized replacement retained cached data")
+ }
+ if len(blockCacheKeys) != 0 {
+ t.Fatal("rejected block retained an invalidation index")
+ }
+}
+
+func TestBlockCacheReplacementRemainsInvalidatable(t *testing.T) {
+ previousDisabled := cacheDisabled
+ cacheDisabled = false
+ ClearCache()
+ t.Cleanup(func() { ClearCache(); cacheDisabled = previousDisabled })
+ for i := 0; i < 64; i++ {
+ putBlockCache(&Block{ID: "replaced", Content: strings.Repeat("x", i+1)})
+ }
+ blockCache.Wait()
+ if block := getBlockCache("replaced"); block == nil || len(block.Content) != 64 {
+ t.Fatalf("replacement was lost: %+v", block)
+ }
+ removeBlockCache("replaced")
+ blockCache.Wait()
+ if getBlockCache("replaced") != nil || len(blockCacheKeys) != 0 {
+ t.Fatal("replacement survived invalidation")
+ }
+}