Files
memoryweave/go/internal/governance/graph_expander.go
T
小唯 7f7171ac14 feat(recall): 召回契约字段 + trace 回溯 + 生命周期/实体质量判据(工作树收口)
这批是 10-26~27 已在生产二进制(zhiyid-protectrails-20261027)里运行、
但一直留在工作树未提交的改动。收口原因:三件改造要开分支,工作树脏 =
分支基准与回滚点都不存在。

主要内容:
- api/routes/contract.go + trace.go:召回响应契约字段(trace_id/status/scope/
  continuation/channel)与 /api/v1/trace 回溯端点
- governance/entity_quality.go:实体质量闸
- storage/trace.go + recall.go/recall_write_buffer.go:召回写入缓冲与轨迹
- 测试:contract/recall_contract_fields/recall_lifecycle/stale_lifecycle/
  entity_quality/trace

同时修一个 flaky:recall_lifecycle_test 原本硬编码「今天 11:00 已过」,
凌晨跑就会把「已失效」fixture 当成仍有效。改成相对时间(过期=now-1h),
生命周期判据与运行时刻无关。修完 go test ./internal/api/routes ./internal/storage 全绿。
2026-10-28 02:09:19 +08:00

234 lines
6.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — 图谱扩展器(供 Recall 管线调用)
package governance
import (
"fmt"
"log"
"os"
"strings"
"github.com/xiaoxue/memoryweave/internal/models"
)
// graphExpandDebugEnabled 控制「图谱扩展」debug 日志(AC 可观测性,t_818f77be)。
// 默认关;设 ZHIYI_GRAPH_EXPAND_DEBUG=1 打开。每次 recall 至多一条(低频),避免刷屏。
func graphExpandDebugEnabled() bool {
return os.Getenv("ZHIYI_GRAPH_EXPAND_DEBUG") == "1"
}
// ExpandFromResults 从 recall 结果出发,双向 BFS 扩展图谱邻接节点
// 实现 GraphStore 接口
//
// 导航起点 = 从 r.Content 提实体(复用 extractPotentialEntitiesFromContent + normalizeEntityID,
// 与同文件 ExpandWithSummary 同一套逻辑)。旧实现拿 r.Category(类目名,如 "distilled")
// 当实体去 Navigate,永远匹配不到任何图节点 ⇒ 结构性零产出(t_818f77be 实测 10/10 全 distilled)。
// 且 InMemoryGraph.Navigate 返回字段是 source/target(非 to/from),旧读法 p["to"]/p["from"]
// 恒取到空 ⇒ 即便实体修对也补 0。两处一并修正。
func (g *InMemoryGraph) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult {
var expanded []models.RecallResult
seen := make(map[string]bool)
seenEntities := make(map[string]bool)
// 收集已有结果 ID
for _, r := range results {
seen[r.ID] = true
}
startEntities := 0 // 可观测性:去重后实际导航的起点实体数 N
totalPathsHit := 0 // 可观测性:命中路径总数 M(补前去重)
rejectedJunk := 0 // P0-4:被质量闸①丢弃的垃圾实体数
rejectedLowDegree := 0 // P0-4:被质量闸②丢弃的低度数实体数
// 从每个结果正文提实体出发扩展
for _, r := range results {
entities := extractPotentialEntitiesFromContent(r.Content)
// P0-4 第①道闸:垃圾实体不导航
entities, rejected := FilterEntitiesForGraph(entities)
rejectedJunk += rejected
for _, entity := range entities {
if seenEntities[entity] {
continue
}
seenEntities[entity] = true
startEntities++
nodeID := normalizeEntityID(entity)
paths, err := g.Navigate(nodeID, maxHops, namespace, nil)
if err != nil {
continue
}
// P0-4 第②道闸:路径数 <2 ⇒ 孤边节点,不构成语义关联(内存图无 degree 查询,用路径数代理)
if len(paths) < 2 {
rejectedLowDegree++
continue
}
totalPathsHit += len(paths)
for _, p := range paths {
to, _ := p["target"].(string)
from, _ := p["source"].(string)
for _, id := range []string{to, from} {
if id != "" && !seen[id] {
seen[id] = true
expanded = append(expanded, models.RecallResult{
ID: id,
Category: "graph_expanded",
Score: 0.5, // 图谱扩展降权
})
}
}
}
}
}
// 可观测性:默认关(ZHIYI_GRAPH_EXPAND_DEBUG=1 打开),保证「下次坏了不沉默」。
if graphExpandDebugEnabled() {
log.Printf("[graph-expand] ns=%s maxHops=%d 起点实体 %d 个 / 命中 %d 条 / 补入 %d 条 / 质量闸拒 垃圾 %d 低度 %d",
namespace, maxHops, startEntities, totalPathsHit, len(expanded), rejectedJunk, rejectedLowDegree)
}
return expanded
}
// ExpandWithSummary BFS 扩展 + 生成汇总语句 — E1 图谱导航增强
func (g *InMemoryGraph) ExpandWithSummary(results []models.RecallResult, namespace string, maxHops int) models.GraphBFSResult {
if maxHops <= 0 {
maxHops = 2
}
seenEntities := make(map[string]bool)
var relations []models.ExpandedRelation
// 从 recall 结果提取实体
for _, r := range results {
entities := extractPotentialEntitiesFromContent(r.Content)
for _, entity := range entities {
if seenEntities[entity] {
continue
}
seenEntities[entity] = true
nodeID := normalizeEntityID(entity)
paths, _ := g.Navigate(nodeID, maxHops, namespace, nil)
for _, p := range paths {
from, _ := p["source"].(string)
to, _ := p["target"].(string)
rel, _ := p["relation"].(string)
weight, _ := p["weight"].(float64)
hop, _ := p["hop"].(int)
fromName := strings.TrimPrefix(from, "n_")
toName := strings.TrimPrefix(to, "n_")
rel = strings.TrimSpace(rel)
if rel == "" {
rel = "RELATED_TO"
}
relations = append(relations, models.ExpandedRelation{
From: fromName,
To: toName,
Relation: rel,
Hops: hop,
Weight: weight,
Score: r.Score * weight,
})
}
}
}
summary := buildBFSSummary(relations)
return models.GraphBFSResult{
ExpandedRelations: relations,
Summary: summary,
}
}
// extractPotentialEntitiesFromContent 从文本提取实体(InMemoryGraph 用)
func extractPotentialEntitiesFromContent(text string) []string {
var entities []string
seen := make(map[string]bool)
runes := []rune(text)
for i := 0; i < len(runes); {
r := runes[i]
// 中文字符
if r >= 0x4E00 && r <= 0x9FFF {
start := i
i++
for i < len(runes) && runes[i] >= 0x4E00 && runes[i] <= 0x9FFF {
i++
}
chinese := string(runes[start:i])
if len(chinese) >= 2 && len(chinese) <= 8 && !seen[chinese] {
seen[chinese] = true
entities = append(entities, chinese)
}
continue
}
// 英文/其他
start := i
for i < len(runes) {
r2 := runes[i]
if r2 >= 0x4E00 && r2 <= 0x9FFF {
break
}
i++
}
if i-start < 2 {
continue
}
w := string(runes[start:i])
w = strings.Trim(w, ",.;:!?,。;:!?、\"'()()[]【】")
if len(w) < 2 {
continue
}
first := []rune(w)
if len(first) > 0 && first[0] >= 'A' && first[0] <= 'Z' {
lower := strings.ToLower(w)
if !seen[lower] {
seen[lower] = true
entities = append(entities, w)
}
}
}
return entities
}
// buildBFSSummary 从扩展关系列表生成一句话汇总
func buildBFSSummary(relations []models.ExpandedRelation) string {
if len(relations) == 0 {
return "未发现图谱关联"
}
if len(relations) == 1 {
r := relations[0]
return fmt.Sprintf("%s --[%s]--> %s(%d跳,权重%.2f)", r.From, r.Relation, r.To, r.Hops, r.Weight)
}
relCounts := make(map[string]int)
var totalWeight float64
maxHops := 0
for _, r := range relations {
relCounts[r.Relation]++
totalWeight += r.Weight
if r.Hops > maxHops {
maxHops = r.Hops
}
}
var topRel string
topCount := 0
for rel, cnt := range relCounts {
if cnt > topCount {
topCount = cnt
topRel = rel
}
}
avgWeight := totalWeight / float64(len(relations))
uniqueEntities := make(map[string]bool)
for _, r := range relations {
uniqueEntities[r.From] = true
uniqueEntities[r.To] = true
}
return fmt.Sprintf("发现 %d 条关联(跨越 %d 个实体,最深 %d 跳),关系以 [%s] 为主(%d 条),平均权重 %.2f",
len(relations), len(uniqueEntities), maxHops, topRel, topCount, avgWeight)
}