An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Reject stale disk reads when repopulating source caches https://github.com/siyuan-note/siyuan/issues/20985
Danielb29e5cf1209b
diff --git a/kernel/av/av.go b/kernel/av/av.goindex f01887f1e4..33dffe010f 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -869,6 +869,7 @@ func parseAttributeViewByPathInBoxWithOptions(avJSONPath, boxID string, resolveCdataVersion = version} else {var readErr error+ readVersion := cache.AVDataReadVersion()data, readErr = filelock.ReadFile(avJSONPath)if nil != readErr {logging.LogErrorf("read attribute view [%s] failed: %s", avID, readErr)@@ -886,7 +887,7 @@ func parseAttributeViewByPathInBoxWithOptions(avJSONPath, boxID string, resolveC// 这会在加密笔记本的 AV 因路径迁移(同步、导入、历史布局)落到全局位置时发生。return nil, nil}- dataVersion = cache.SetAVDataWithVersionInBox(avID, boxID, data)+ dataVersion = cache.SetAVDataFromReadInBox(avID, boxID, data, readVersion)}if normalized, ok := cache.GetAVNormalizedDataInBox(avID, boxID, dataVersion); ok {diff --git a/kernel/av/cache_read_test.go b/kernel/av/cache_read_test.gonew file mode 100644index 0000000000..3e241be31f--- /dev/null+++ b/kernel/av/cache_read_test.go@@ -0,0 +1,61 @@+package av++import (+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestParseAttributeViewRejectsStaleDiskRead(t *testing.T) {+ previousDir, previousProvider := util.DataDir, AVDEKProvider+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir, AVDEKProvider = previousDir, previousProvider+ cache.ClearAVCache()+ })+ cache.ClearAVCache()+ const id, box = "20261027000000-abcdefg", "20261027000001-abcdefg"+ path := filepath.Join(util.DataDir, box, "storage", "av", id+".json")+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ t.Fatal(err)+ }+ old := []byte(`{"id":"` + id + `","name":"old","keyValues":[],"views":[]}`)+ current := []byte(`{"id":"` + id + `","name":"current","keyValues":[],"views":[]}`)+ if err := os.WriteFile(path, old, 0600); err != nil {+ t.Fatal(err)+ }+ // This callback runs after the old bytes are read, before their publication.+ // Publish a newer disk/cache state at that boundary without timing a race.+ AVDEKProvider = func(string) ([]byte, error) {+ if err := os.WriteFile(path, current, 0600); err != nil {+ return nil, err+ }+ cache.SetAVDataInBox(id, box, current)+ return nil, nil+ }+ if _, err := parseAttributeViewByPathInBoxWithOptions(path, box, false); err != nil {+ t.Fatal(err)+ }+ AVDEKProvider = nil+ deadline := time.Now().Add(time.Second)+ for {+ if raw, ok := cache.GetAVDataInBox(id, box); ok {+ if string(raw) != string(current) {+ t.Fatalf("old disk read replaced the newer cache: %s", raw)+ }+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("newer cache admission did not complete")+ }+ time.Sleep(time.Millisecond)+ }+ view, err := parseAttributeViewByPathInBoxWithOptions(path, box, false)+ if err != nil || view.Name != "current" {+ t.Fatalf("subsequent parse restored stale data: %v, %v", view, err)+ }+}diff --git a/kernel/cache/av.go b/kernel/cache/av.goindex 4a32cac069..d5ff3cf0ff 100644--- a/kernel/cache/av.go+++ b/kernel/cache/av.go@@ -163,12 +163,30 @@ func SetAVDataWithVersionInBox(avID, boxID string, raw []byte) uint64 {return setAVDataInBox(avID, boxID, raw)}+// AVDataReadVersion captures source-read admission without allocating key tombstones.+func AVDataReadVersion() uint64 {+ avSearchDataCacheLock.RLock()+ defer avSearchDataCacheLock.RUnlock()+ return avDataVersion+}++func SetAVDataFromReadInBox(avID, boxID string, raw []byte, version uint64) uint64 {+ return setAVDataFromReadInBox(avID, boxID, raw, &version)+}+func setAVDataInBox(avID, boxID string, raw []byte) (version uint64) {+ return setAVDataFromReadInBox(avID, boxID, raw, nil)+}++func setAVDataFromReadInBox(avID, boxID string, raw []byte, expected *uint64) (version uint64) {if raw == nil {return}avSearchDataCacheLock.Lock()defer avSearchDataCacheLock.Unlock()+ if expected != nil && *expected != avDataVersion {+ return 0+ }key := avCacheKey(avID, boxID)version = invalidateAVSearchDataByKeyLocked(key)replaceAVCacheLocked(avID, key, &avCacheEntry{raw: raw, version: version}, int64(len(raw)))@@ -204,6 +222,7 @@ func RemoveAVData(avID string) {func ClearAVCache() {avSearchDataCacheLock.Lock()defer avSearchDataCacheLock.Unlock()+ avDataVersion++avCacheGeneration.Add(1)clearAVOrderedIDs("")avCacheKeys = map[string]map[string]uint64{}diff --git a/kernel/cache/av_test.go b/kernel/cache/av_test.goindex a1de0b8e07..a261430a15 100644--- a/kernel/cache/av_test.go+++ b/kernel/cache/av_test.go@@ -23,6 +23,40 @@ import ("github.com/dgraph-io/ristretto")+func TestAVCacheRejectsStaleDiskRead(t *testing.T) {+ defer ClearAVCache()+ for name, mutate := range map[string]func(){+ "write": func() { SetAVDataInBox("database", "box", []byte("new")) },+ "remove": func() { RemoveAVData("database") },+ "remove box": func() { RemoveAVDataInBox("database", "box") },+ "clear": ClearAVCache,+ } {+ t.Run(name, func(t *testing.T) {+ ClearAVCache()+ version := AVDataReadVersion()+ mutate()+ if got := SetAVDataFromReadInBox("database", "box", []byte("old disk bytes"), version); got != 0 {+ t.Fatal("stale disk read was admitted after a cache mutation")+ }+ avCache.Wait()+ if data, ok := GetAVDataInBox("database", "box"); ok && string(data) != "new" {+ t.Fatalf("stale disk read replaced current cache: %q", data)+ }+ if SetAVSearchDataInBox("database", "box", 0, "stale derived state") {+ t.Fatal("rejected source must not admit derived search data")+ }+ version = AVDataReadVersion()+ if got := SetAVDataFromReadInBox("database", "box", []byte("fresh disk bytes"), version); got == 0 {+ t.Fatal("unchanged source read was rejected")+ }+ avCache.Wait()+ if data, ok := GetAVDataInBox("database", "box"); !ok || string(data) != "fresh disk bytes" {+ t.Fatalf("fresh source was not cached: %q, %v", data, ok)+ }+ })+ }+}+func TestAVSearchDataInvalidation(t *testing.T) {const avID = "20260728120000-search"const boxID = "20260728120000-box"diff --git a/kernel/cache/tree.go b/kernel/cache/tree.goindex 256ac42d4f..309cd9fc0f 100644--- a/kernel/cache/tree.go+++ b/kernel/cache/tree.go@@ -86,12 +86,30 @@ func GetTreeDataInBox(rootID, boxID string) (raw []byte, ok bool) {}func SetTreeDataInBox(rootID, boxID string, raw []byte) {+ setTreeDataInBox(rootID, boxID, raw, nil)+}++// TreeDataReadVersion captures the mutation boundary before reading source bytes.+// A global clock avoids retaining per-document tombstones for in-flight reads.+func TreeDataReadVersion() uint64 {+ treeCacheKeysMu.Lock()+ defer treeCacheKeysMu.Unlock()+ return treeCacheGeneration+}++func SetTreeDataFromReadInBox(rootID, boxID string, raw []byte, version uint64) bool {+ return setTreeDataInBox(rootID, boxID, raw, &version)+}++func setTreeDataInBox(rootID, boxID string, raw []byte, expected *uint64) bool {if raw == nil {- return+ return false}if len(raw) >= treeCacheMaxCost {- RemoveTreeDataInBox(rootID, boxID)- return+ if expected == nil {+ RemoveTreeDataInBox(rootID, boxID)+ }+ return false}entry := &treeCacheEntry{rawSize: len(raw)}// 小文档不压缩;只有实际减少驻留字节时才保存压缩结果。@@ -108,6 +126,9 @@ func SetTreeDataInBox(rootID, boxID string, raw []byte) {key := treeCacheKey(rootID, boxID)treeCacheKeysMu.Lock()defer treeCacheKeysMu.Unlock()+ if expected != nil && *expected != treeCacheGeneration {+ return false+ }treeCacheGeneration++entry.generation = treeCacheGenerationkeys := treeCacheKeys[rootID]@@ -116,12 +137,13 @@ func SetTreeDataInBox(rootID, boxID string, raw []byte) {treeCacheKeys[rootID] = keys}keys[key] = entry.generation- treeCache.Set(key, entry, int64(cap(entry.raw))+64)+ return treeCache.Set(key, entry, int64(cap(entry.raw))+64)}func RemoveTreeData(rootID string) {treeCacheKeysMu.Lock()defer treeCacheKeysMu.Unlock()+ treeCacheGeneration++keys := treeCacheKeys[rootID]delete(treeCacheKeys, rootID)@@ -136,6 +158,7 @@ func RemoveTreeDataInBox(rootID, boxID string) {key := treeCacheKey(rootID, boxID)treeCacheKeysMu.Lock()defer treeCacheKeysMu.Unlock()+ treeCacheGeneration++treeCache.Del(key)if keys := treeCacheKeys[rootID]; keys != nil {delete(keys, key)@@ -148,6 +171,7 @@ func RemoveTreeDataInBox(rootID, boxID string) {func ClearTreeCache() {treeCacheKeysMu.Lock()defer treeCacheKeysMu.Unlock()+ treeCacheGeneration++treeCacheKeys = map[string]map[string]uint64{}treeCache.Clear()}diff --git a/kernel/cache/tree_test.go b/kernel/cache/tree_test.goindex 6234afdd49..d1618d7071 100644--- a/kernel/cache/tree_test.go+++ b/kernel/cache/tree_test.go@@ -12,6 +12,37 @@ import ("github.com/dgraph-io/ristretto")+func TestTreeCacheRejectsStaleDiskRead(t *testing.T) {+ defer ClearTreeCache()+ for name, mutate := range map[string]func(){+ "write": func() { SetTreeDataInBox("document", "box", []byte("new")) },+ "remove": func() { RemoveTreeData("document") },+ "remove box": func() { RemoveTreeDataInBox("document", "box") },+ "clear": ClearTreeCache,+ } {+ t.Run(name, func(t *testing.T) {+ ClearTreeCache()+ version := TreeDataReadVersion()+ mutate()+ if SetTreeDataFromReadInBox("document", "box", []byte("old disk bytes"), version) {+ t.Fatal("stale disk read was admitted after a cache mutation")+ }+ treeCache.Wait()+ if data, ok := GetTreeDataInBox("document", "box"); ok && string(data) != "new" {+ t.Fatalf("stale disk read replaced current cache: %q", data)+ }+ version = TreeDataReadVersion()+ if !SetTreeDataFromReadInBox("document", "box", []byte("fresh disk bytes"), version) {+ t.Fatal("unchanged source read was rejected")+ }+ treeCache.Wait()+ if data, ok := GetTreeDataInBox("document", "box"); !ok || string(data) != "fresh disk bytes" {+ t.Fatalf("fresh source was not cached: %q, %v", data, ok)+ }+ })+ }+}+func TestTreeCacheRejectsStaleAsyncAdmission(t *testing.T) {original := treeCacheentered, release := make(chan struct{}), make(chan struct{})diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex 212fc6f61b..6a498f3e71 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -222,6 +222,7 @@ func LoadTreeWithFix(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, nreturn}+ readVersion := cache.TreeDataReadVersion()data, err := filelock.ReadFile(filePath)if nil != err {if !os.IsNotExist(err) {@@ -243,7 +244,7 @@ func LoadTreeWithFix(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, nret, err = loadTreeByDataInMode(data, boxID, p, luteEngine, mode)if nil == err {- cache.SetTreeDataInBox(rootID, boxID, data)+ cache.SetTreeDataFromReadInBox(rootID, boxID, data, readVersion)}return}