gofmt -l 实测 66 文件不合规(历史遗留+gofmt 1.25 规范化: 单行 if/for/case 展开成块、Go1.19+ doc 注释 // 与段落 // 空行)。 本 commit 只含格式化,零逻辑改动: - 66/66 文件「去注释+去空白+分号归一」后 token 流与 HEAD 完全一致 - go build ./... exit 0;go vet ./... exit 0(改前后一致) - go test ./... 17 包全 ok(改前后一致) 验收: gofmt -l . 为空;git diff -w 非空系 gofmt 1.25 非纯空白特性, 非逻辑改动(等价性以 token 流 + test 兜底)。
278 lines
6.5 KiB
Go
278 lines
6.5 KiB
Go
// 织忆 MemoryWeave — CO_OCCURS 共访统计 + 预取引擎
|
||
// 追踪哪些记忆常一起被 recall → 构建关联图谱 → WebSocket 预取推送
|
||
|
||
package storage
|
||
|
||
import (
|
||
"encoding/json"
|
||
"sync"
|
||
"time"
|
||
)
|
||
|
||
// CoOccurEdge 共访边
|
||
type CoOccurEdge struct {
|
||
SourceID string `json:"source_id"`
|
||
TargetID string `json:"target_id"`
|
||
CoCount int `json:"co_count"` // 共现次数
|
||
Weight float64 `json:"weight"` // 共被recall次数/min(A_count, B_count)
|
||
LastCoOccur time.Time `json:"last_co_occur"`
|
||
Namespace string `json:"namespace"`
|
||
}
|
||
|
||
// CoOccurTracker 共访追踪器
|
||
type CoOccurTracker struct {
|
||
mu sync.RWMutex
|
||
edges map[string]map[string]*CoOccurEdge // sourceID → targetID → edge
|
||
recallCounts map[string]int // memoryID → recall_count
|
||
|
||
// 预取阈值
|
||
prefetchThreshold float64 // weight > 0.6 → 预取
|
||
|
||
// 衰减窗口
|
||
decayWindowDays int // 14 天
|
||
|
||
// 重量记录器(持久化到 SQLite/Redis)
|
||
persist func(*CoOccurEdge) error
|
||
}
|
||
|
||
func NewCoOccurTracker(persistFn func(*CoOccurEdge) error) *CoOccurTracker {
|
||
return &CoOccurTracker{
|
||
edges: make(map[string]map[string]*CoOccurEdge),
|
||
recallCounts: make(map[string]int),
|
||
prefetchThreshold: 0.6,
|
||
decayWindowDays: 14,
|
||
persist: persistFn,
|
||
}
|
||
}
|
||
|
||
// RecordRecall 记录一次 recall 的 top-5 结果
|
||
// 任意两条都能产生一个共访计数
|
||
func (ct *CoOccurTracker) RecordRecall(memoryIDs []string, namespace string) {
|
||
ct.mu.Lock()
|
||
defer ct.mu.Unlock()
|
||
|
||
// 更新 recall_count
|
||
for _, id := range memoryIDs {
|
||
ct.recallCounts[id]++
|
||
}
|
||
|
||
// 取 top-5 建立共访边
|
||
topN := memoryIDs
|
||
if len(topN) > 5 {
|
||
topN = topN[:5]
|
||
}
|
||
|
||
now := time.Now()
|
||
for i, a := range topN {
|
||
for j := i + 1; j < len(topN); j++ {
|
||
b := topN[j]
|
||
if a == b {
|
||
continue
|
||
}
|
||
|
||
// 确保双向边的存在
|
||
if ct.edges[a] == nil {
|
||
ct.edges[a] = make(map[string]*CoOccurEdge)
|
||
}
|
||
if ct.edges[b] == nil {
|
||
ct.edges[b] = make(map[string]*CoOccurEdge)
|
||
}
|
||
|
||
// 更新 (a → b)
|
||
edgeAB := ct.edges[a][b]
|
||
if edgeAB == nil {
|
||
edgeAB = &CoOccurEdge{
|
||
SourceID: a,
|
||
TargetID: b,
|
||
Namespace: namespace,
|
||
LastCoOccur: now,
|
||
}
|
||
ct.edges[a][b] = edgeAB
|
||
}
|
||
edgeAB.CoCount++
|
||
edgeAB.LastCoOccur = now
|
||
edgeAB.Weight = ct.calcWeight(a, b)
|
||
if ct.persist != nil {
|
||
ct.persist(edgeAB)
|
||
}
|
||
|
||
// 更新 (b → a)
|
||
edgeBA := ct.edges[b][a]
|
||
if edgeBA == nil {
|
||
edgeBA = &CoOccurEdge{
|
||
SourceID: b,
|
||
TargetID: a,
|
||
Namespace: namespace,
|
||
LastCoOccur: now,
|
||
}
|
||
ct.edges[b][a] = edgeBA
|
||
}
|
||
edgeBA.CoCount++
|
||
edgeBA.LastCoOccur = now
|
||
edgeBA.Weight = ct.calcWeight(b, a)
|
||
if ct.persist != nil {
|
||
ct.persist(edgeBA)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// calcWeight 计算 CO_OCCURS 权重
|
||
// weight = 共被recall次数 / min(A_recall_count, B_recall_count)
|
||
func (ct *CoOccurTracker) calcWeight(a, b string) float64 {
|
||
ca := ct.recallCounts[a]
|
||
cb := ct.recallCounts[b]
|
||
minCount := ca
|
||
if cb < ca {
|
||
minCount = cb
|
||
}
|
||
if minCount == 0 {
|
||
return 0
|
||
}
|
||
edge := ct.edges[a][b]
|
||
if edge == nil {
|
||
return 0
|
||
}
|
||
return float64(edge.CoCount) / float64(minCount)
|
||
}
|
||
|
||
// GetPrefetchCandidates 获取预取候选项
|
||
// 给定 memory ID,返回 weight > 0.6 的配套记忆
|
||
func (ct *CoOccurTracker) GetPrefetchCandidates(memoryID string) []string {
|
||
ct.mu.RLock()
|
||
defer ct.mu.RUnlock()
|
||
|
||
neighbors := ct.edges[memoryID]
|
||
if neighbors == nil {
|
||
return nil
|
||
}
|
||
|
||
var candidates []string
|
||
for targetID, edge := range neighbors {
|
||
// 检查衰减:14天无共现 → 丢弃
|
||
if time.Since(edge.LastCoOccur) > time.Duration(ct.decayWindowDays)*24*time.Hour {
|
||
continue
|
||
}
|
||
// 权重阈值检查
|
||
if edge.Weight >= ct.prefetchThreshold {
|
||
candidates = append(candidates, targetID)
|
||
}
|
||
}
|
||
return candidates
|
||
}
|
||
|
||
// CollectCandidates 从多条 recall 结果收集预取候选项
|
||
func (ct *CoOccurTracker) CollectCandidates(memoryIDs []string) []string {
|
||
seen := make(map[string]bool)
|
||
var all []string
|
||
for _, id := range memoryIDs {
|
||
cands := ct.GetPrefetchCandidates(id)
|
||
for _, c := range cands {
|
||
if !seen[c] {
|
||
seen[c] = true
|
||
all = append(all, c)
|
||
}
|
||
}
|
||
}
|
||
return all
|
||
}
|
||
|
||
// Prune 修剪过期边 (weight < 0.3 且 14天无共现)
|
||
func (ct *CoOccurTracker) Prune() int {
|
||
ct.mu.Lock()
|
||
defer ct.mu.Unlock()
|
||
|
||
pruned := 0
|
||
cutoff := time.Now().Add(-time.Duration(ct.decayWindowDays) * 24 * time.Hour)
|
||
|
||
for src, neighbors := range ct.edges {
|
||
for tgt, edge := range neighbors {
|
||
if edge.Weight < 0.3 && edge.LastCoOccur.Before(cutoff) {
|
||
delete(neighbors, tgt)
|
||
pruned++
|
||
}
|
||
}
|
||
// 清理空映射
|
||
if len(neighbors) == 0 {
|
||
delete(ct.edges, src)
|
||
}
|
||
}
|
||
|
||
return pruned
|
||
}
|
||
|
||
// Stats 获取统计
|
||
type CoOccurStats struct {
|
||
TotalEdges int `json:"total_edges"`
|
||
HighWeight int `json:"high_weight"` // weight >= prefetchThreshold
|
||
AvgWeight float64 `json:"avg_weight"`
|
||
}
|
||
|
||
func (ct *CoOccurTracker) Stats() CoOccurStats {
|
||
ct.mu.RLock()
|
||
defer ct.mu.RUnlock()
|
||
|
||
stats := CoOccurStats{}
|
||
var sum float64
|
||
for _, neighbors := range ct.edges {
|
||
for _, edge := range neighbors {
|
||
stats.TotalEdges++
|
||
sum += edge.Weight
|
||
if edge.Weight >= ct.prefetchThreshold {
|
||
stats.HighWeight++
|
||
}
|
||
}
|
||
}
|
||
if stats.TotalEdges > 0 {
|
||
stats.AvgWeight = sum / float64(stats.TotalEdges)
|
||
}
|
||
return stats
|
||
}
|
||
|
||
// GlobalCoOccurTracker 全局实例
|
||
var CoOccurTrackerInstance = NewCoOccurTracker(nil)
|
||
|
||
const cooccurRedisKey = "zhiyi:cooccur"
|
||
|
||
// RedisCoOccurPersist 创建 Redis 持久化函数
|
||
func RedisCoOccurPersist() func(*CoOccurEdge) error {
|
||
rc := GetRedisClient()
|
||
if rc == nil {
|
||
return nil
|
||
}
|
||
return func(edge *CoOccurEdge) error {
|
||
key := edge.SourceID + ":" + edge.TargetID
|
||
data, _ := json.Marshal(edge)
|
||
_ = rc.HSet(cooccurRedisKey, key, string(data))
|
||
_ = rc.Expire(cooccurRedisKey, 90*24*time.Hour)
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// LoadCoOccurFromRedis 从 Redis 加载共访边
|
||
func LoadCoOccurFromRedis() {
|
||
rc := GetRedisClient()
|
||
if rc == nil || CoOccurTrackerInstance == nil {
|
||
return
|
||
}
|
||
data, err := rc.HGetAll(cooccurRedisKey)
|
||
if err != nil || len(data) == 0 {
|
||
return
|
||
}
|
||
CoOccurTrackerInstance.mu.Lock()
|
||
defer CoOccurTrackerInstance.mu.Unlock()
|
||
for key, jsonStr := range data {
|
||
var edge CoOccurEdge
|
||
if json.Unmarshal([]byte(jsonStr), &edge) == nil {
|
||
src := edge.SourceID
|
||
tgt := edge.TargetID
|
||
if CoOccurTrackerInstance.edges[src] == nil {
|
||
CoOccurTrackerInstance.edges[src] = make(map[string]*CoOccurEdge)
|
||
}
|
||
CoOccurTrackerInstance.edges[src][tgt] = &edge
|
||
_ = src
|
||
_ = key
|
||
}
|
||
}
|
||
}
|