Skip to content

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

:art: Block reference candidate list sorted by most recently referenced https://github.com/siyuan-note/siyuan/issues/16468

Danielbf457168e4a1
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 3347e37b96..9d1fe27cb0 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -336,11 +336,28 @@ func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBrac
}
if "" == keyword {
- // 查询为空时默认的块引排序规则按最近使用优先 https://github.com/siyuan-note/siyuan/issues/3218
+ // 查询为空时默认的块引排序规则按最近引用优先 https://github.com/siyuan-note/siyuan/issues/3218
typeFilter := Conf.Search.TypeFilter()
ignoreLines := getRefSearchIgnoreLines()
refs := sql.QueryRefsRecentInBox(onlyDoc, typeFilter, ignoreLines, boxID)
+ // 候选已按 refs.id DESC 兜底排序,这里再按"最近引用时间"精确排序:
+ // 有记录的目标块按时间戳降序排前,无记录的(历史数据)保持兜底序排后
+ refUsed := GetRefUsed()
+ sort.SliceStable(refs, func(i, j int) bool {
+ ti, oki := refUsed[refs[i].DefBlockID]
+ tj, okj := refUsed[refs[j].DefBlockID]
+ if oki && okj {
+ return ti > tj
+ }
+ if oki != okj {
+ return oki
+ }
+ return false
+ })
+ if 32 < len(refs) {
+ refs = refs[:32]
+ }
var btsID []string
for _, ref := range refs {
btsID = append(btsID, ref.DefBlockRootID)
diff --git a/kernel/model/storage.go b/kernel/model/storage.go
index 20d3fa360d..26178bbec6 100644
--- a/kernel/model/storage.go
+++ b/kernel/model/storage.go
@@ -715,6 +715,98 @@ func setRecentDocs(recentDocs []*RecentDoc) (err error) {
return
}
+var refUsedLock = sync.Mutex{}
+
+// refUsedMaxCount 限制最近引用记录的最大条数,超出时淘汰最旧的记录,防止文件无限膨胀。
+const refUsedMaxCount = 512
+
+// TouchRefUsed 在用户真实插入引用时刷新目标块的最近引用时间。该时间独立于 refs 表的重建机制,
+// 仅在事务处理(真实编辑)时写入,用于稳定块引"最近引用"排序。
+func TouchRefUsed(defBlockIDs []string) {
+ if 1 > len(defBlockIDs) {
+ return
+ }
+
+ refUsedLock.Lock()
+ defer refUsedLock.Unlock()
+
+ used := loadRefUsed()
+ now := time.Now().Unix()
+ for _, defBlockID := range defBlockIDs {
+ used[defBlockID] = now
+ }
+ if refUsedMaxCount < len(used) {
+ // 超出上限时按时间戳淘汰最旧的记录
+ type entry struct {
+ id string
+ ts int64
+ }
+ entries := make([]entry, 0, len(used))
+ for id, ts := range used {
+ entries = append(entries, entry{id, ts})
+ }
+ sort.Slice(entries, func(i, j int) bool {
+ return entries[i].ts > entries[j].ts
+ })
+ used = map[string]int64{}
+ for i := 0; i < refUsedMaxCount && i < len(entries); i++ {
+ used[entries[i].id] = entries[i].ts
+ }
+ }
+ setRefUsed(used)
+}
+
+// GetRefUsed 返回目标块→最近引用时间戳映射,供块引排序使用。
+func GetRefUsed() (ret map[string]int64) {
+ refUsedLock.Lock()
+ defer refUsedLock.Unlock()
+ ret = loadRefUsed()
+ return
+}
+
+func loadRefUsed() (ret map[string]int64) {
+ ret = map[string]int64{}
+ dataPath := filepath.Join(util.DataDir, "storage/ref-used.json")
+ if !filelock.IsExist(dataPath) {
+ return
+ }
+
+ data, err := filelock.ReadFile(dataPath)
+ if err != nil {
+ logging.LogErrorf("read storage [ref-used] failed: %s", err)
+ return
+ }
+
+ if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil {
+ logging.LogErrorf("unmarshal storage [ref-used] failed: %s", err)
+ ret = map[string]int64{}
+ return
+ }
+ return
+}
+
+func setRefUsed(used map[string]int64) (err error) {
+ dirPath := filepath.Join(util.DataDir, "storage")
+ if err = os.MkdirAll(dirPath, 0755); err != nil {
+ logging.LogErrorf("create storage [ref-used] dir failed: %s", err)
+ return
+ }
+
+ data, err := gulu.JSON.MarshalIndentJSON(used, "", " ")
+ if err != nil {
+ logging.LogErrorf("marshal storage [ref-used] failed: %s", err)
+ return
+ }
+
+ dataPath := filepath.Join(dirPath, "ref-used.json")
+ err = filelock.WriteFile(dataPath, data)
+ if err != nil {
+ logging.LogErrorf("write storage [ref-used] failed: %s", err)
+ return
+ }
+ return
+}
+
type OutlineDoc struct {
DocID string `json:"docID"`
Data map[string]any `json:"data"`
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index f4af2846ed..0711eda85d 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -1404,6 +1404,8 @@ func (tx *Transaction) doInsert0(operation *Operation, tree *parse.Tree) (ret *T
for _, defID := range refDefIDs {
task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, defID)
}
+ // 新插入块中的引用均为本次新增,刷新其最近引用时间用于块引"最近引用"排序
+ TouchRefUsed(refDefIDs)
// 粘贴被引用的块后需刷新目标文档的引用计数,否则目标文档级计数角标不会更新
task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, tree.Root.ID)
@@ -1567,6 +1569,15 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {
for _, defID := range refDefIDs {
task.AppendAsyncTaskWithDelay(task.SetDefRefCount, util.SQLFlushInterval, refreshRefCount, defID)
}
+
+ // 本次新增引用的目标块,刷新其最近引用时间用于块引"最近引用"排序
+ var newRefDefIDs []string
+ for _, defID := range newDefIDs {
+ if !gulu.Str.Contains(defID, oldDefIDs) {
+ newRefDefIDs = append(newRefDefIDs, defID)
+ }
+ }
+ TouchRefUsed(newRefDefIDs)
}
updatedNode := subTree.Root.FirstChild
@@ -1870,6 +1881,8 @@ func (tx *Transaction) doUpdateUpdated(operation *Operation) (ret *TxErr) {
func (tx *Transaction) doCreate(operation *Operation) (ret *TxErr) {
tree := operation.Data.(*parse.Tree)
tx.writeTree(tree)
+ // 新建文档中的引用均为本次新增,刷新其最近引用时间用于块引"最近引用"排序
+ TouchRefUsed(getRefDefIDs(tree.Root))
return
}